DEV Community

Salah Elhossiny
Salah Elhossiny

Posted on

Build a Simple KNN Model using Golang

In this article, we are going to build a simple knn model but using Golang. The model is trained on Iris data.


package main

import (
    "errors"
    "fmt"
    "log"
    "os"

    "github.com/kniren/gota/dataframe"
    "github.com/sjwhitworth/golearn/base"
    "github.com/sjwhitworth/golearn/evaluation"
    "github.com/sjwhitworth/golearn/knn"
)

func check(err error){
   if err != nil {
      panic(err)
   }
}

func main() {

       fmt.Println("Load our csv data")

       rawData, err :=
          base.ParseCSVToInstances("iris_headers.csv", true)

       check(err)

       fmt.Println("Initialize our KNN classifier")
       cls := knn.NewKnnClassifier("euclidean", "linear", 2)

       fmt.Println("Perform a training-test split")

       trainData, testData := 
            base.InstancesTrainTestSplit(rawData, 0.50)

       cls.Fit(trainData)


       predictions, err := cls.Predict(testData)
       check(err)

       fmt.Println(predictions)

       fmt.Println("Print our summary metrics")

       confusionMat, err := 
          evaluation.GetConfusionMatrix(
               testData,
               predictions
          )

       check(err)

       fmt.Println(evaluation.GetSummary(confusionMat))

}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)