Skip to content

Instantly share code, notes, and snippets.

@james-bowman
Last active April 4, 2019 22:19
Show Gist options
  • Select an option

  • Save james-bowman/3e68c618ab53c094be985bb31026e7ea to your computer and use it in GitHub Desktop.

Select an option

Save james-bowman/3e68c618ab53c094be985bb31026e7ea to your computer and use it in GitHub Desktop.
Example solution to the Fresh8 Gaming ML Workshop challenge (https://github.com/fresh8/mlworkshop)
import (
"log"
"math"
"github.com/fresh8/mlworkshop/harness"
"gonum.org/v1/gonum/floats"
"gonum.org/v1/gonum/mat"
)
func main() {
log.Println("Evaluating KNN model")
model := KNNClassifier{
K: 2,
Distance: EuclideanDistance,
}
result, err := harness.Evaluate("diabetes.csv", &model)
if err != nil {
log.Fatal(err)
}
log.Printf("Result = %+v", result)
}
func EuclideanDistance(a, b mat.Vector) float64 {
var v mat.VecDense
v.SubVec(a, b)
return math.Sqrt(mat.Dot(&v, &v))
}
type KNNClassifier struct {
K int
Distance func(a, b mat.Vector) float64
datapoints *mat.Dense
classes []string
}
func (k *KNNClassifier) Fit(X *mat.Dense, Y []string) {
k.datapoints = X
k.classes = Y
}
func (k *KNNClassifier) Predict(X *mat.Dense) []string {
r, _ := X.Dims()
targets := make([]string, r)
distances := make([]float64, len(k.classes))
inds := make([]int, len(k.classes))
for i := 0; i < r; i++ {
votes := make(map[string]float64)
for j := 0; j < len(k.classes); j++ {
distances[j] = k.Distance(k.datapoints.RowView(j), X.RowView(i))
}
floats.Argsort(distances, inds)
for n := 0; n < k.K; n++ {
votes[k.classes[inds[n]]]++
}
var winningCount float64
for k, v := range votes {
if v > winningCount {
targets[i] = k
winningCount = v
}
}
}
return targets
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment