knn

package module
v0.0.0-...-38627f9 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2021 License: MIT Imports: 3 Imported by: 0

README

knn

Sample of k-NN (K-Nearest Neighbor algorithm) by GoLang

Document

https://godoc.org/github.com/bunji2/knn

Documentation

Overview

Example
// import "github.com/bunji2/knn"

data := [][]float32{
	[]float32{11, 11},
	[]float32{1, 1},
	[]float32{-11, 11},
	[]float32{-1, 1},
	[]float32{-11, -11},
	[]float32{-1, -1},
	[]float32{11, -11},
	[]float32{1, -1},
}
labels := []int{
	0,
	0,
	1,
	1,
	2,
	2,
	3,
	3,
}

k := 3
numDataElm := 2
numLabels := 4
cls := knn.New(k, numDataElm, numLabels)
err := cls.Add(data, labels)
if err != nil {
	fmt.Fprintln(os.Stderr, err)
	return
}

xx := []float32{10, 10}
fmt.Println(xx, "==>", cls.Predict(xx)) // 0

xx = []float32{-10, 10}
fmt.Println(xx, "==>", cls.Predict(xx)) // 1

xx = []float32{-10, -10}
fmt.Println(xx, "==>", cls.Predict(xx)) // 2

xx = []float32{10, -10}
fmt.Println(xx, "==>", cls.Predict(xx)) // 3

xx = []float32{5, -5}
fmt.Println(xx, "==>", cls.Predict(xx)) // 3
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Classifier

type Classifier struct {
	// contains filtered or unexported fields
}

Classifier : kNN を使った分類器

func New

func New(k, numDataElm, numLabels int) (r *Classifier)

New : 分類器の作成。 Params:

k --- 調べる近傍点の個数
numDataElm --- データの要素の個数 (!=データの個数)
numLabels --- ラベルの個数(0<=ラベル番号<numLabels)

func (*Classifier) Add

func (cls *Classifier) Add(data [][]float32, labels []int) (err error)

Add : データとラベルの追加

func (*Classifier) Len

func (cls *Classifier) Len() int

func (*Classifier) Less

func (cls *Classifier) Less(i, j int) bool

func (*Classifier) Predict

func (cls *Classifier) Predict(data []float32) (label int)

Predict : ラベルの予測

func (*Classifier) Swap

func (cls *Classifier) Swap(i, j int)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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