knn

package module
v0.0.0-...-34af58a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

README

knn-go

K-Nearest Neighbours library for Golang

Note: This is alpha software at best. I make no guarantees as to the correctness of the implementation, nor to the stability of the API. Use at your own risk.

Sample Usage

https://github.com/prateek/knn-go/blob/eff5ea74d6fa18f95a5cc1a84bb64fa53a727253/naive_example_test.go#L7-L37

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CosineDistance

func CosineDistance(a, b Vector) float64

Types

type DistanceFn

type DistanceFn func(a, b Vector) float64

type ID

type ID string

type KNN

type KNN interface {
	Search(k int, targetVector Vector) []Vector
}

type NaiveKNN

type NaiveKNN struct {
	// contains filtered or unexported fields
}
Example
// Define the input vectors
vecs := []Vector{
	{ID: "vec1", Point: []float64{1.0, 2.0, 3.0}},
	{ID: "vec2", Point: []float64{4.0, 5.0, 6.0}},
	{ID: "vec3", Point: []float64{7.0, 8.0, 9.0}},
}

// Create a new NaiveKNN instance
knn, err := NewNaiveKNN(vecs, CosineDistance)
if err != nil {
	fmt.Println("Failed to create NaiveKNN:", err)
	return
}

// Define the target vector
target := Vector{ID: "target", Point: []float64{1., 5., 9.}}

// Perform the KNN search
k := 2
result := knn.Search(k, target)

// Print the result
for _, vec := range result {
	fmt.Println(vec.ID, vec.Point)
}
Output:

vec1 [1 2 3]
vec2 [4 5 6]

func NewNaiveKNN

func NewNaiveKNN(vecs []Vector, fn DistanceFn) (*NaiveKNN, error)

func (*NaiveKNN) Search

func (n *NaiveKNN) Search(k int, targetVector Vector) []Vector

type Payload

type Payload []byte

type Vector

type Vector struct {
	ID      ID
	Payload Payload
	Point   []float64
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL