Skip to content

Instantly share code, notes, and snippets.

@nbortolotti
Last active January 22, 2021 16:01
Show Gist options
  • Save nbortolotti/4ec0ceb23667beb8c46b22f5326de3c7 to your computer and use it in GitHub Desktop.
Save nbortolotti/4ec0ceb23667beb8c46b22f5326de3c7 to your computer and use it in GitHub Desktop.
Iris inference using tfliego. more information about example: https://github.com/nbortolotti/tflitego_examples/ & and about the library: https://github.com/nbortolotti/tflitego
package main
import (
"fmt"
"log"
"github.com/nbortolotti/tflitego"
)
// topSpecie provide the name of the specia infered by the model
func topSpecie(results []float32) string {
pos := 0
var max = results[0]
for i := range results {
if results[i] > max {
max = results[i]
pos = i
}
}
specie := ""
switch position := pos; {
case position == 0:
specie = "Setosa"
case position == 1:
specie = "Versicolor"
case position == 2:
specie = "Virginica"
}
return specie
}
func main() {
model, err := tflitego.NewTFLiteModelFromFile("iris_lite.tflite")
defer model.Delete()
if err != nil {
if model == nil {
log.Fatal("cannot load model")
}
}
options, err := tflitego.NewInterpreterOptions()
defer options.Delete()
if err != nil {
options.SetNumThread(4)
}
interpreter, err := tflitego.NewInterpreter(model, options)
defer interpreter.Delete()
if err != nil {
if interpreter == nil {
log.Println("cannot create interpreter")
return
}
}
status := interpreter.AllocateTensors()
if status != tflitego.TfLiteOk {
log.Println("allocate Tensors failed")
return
}
// here is possible change the new specie to test other inference responses.
newspecie := []float32{7.9, 3.8, 6.4, 2.0}
input, err := interpreter.GetInputTensor(0)
input.SetFloat32(newspecie)
status = interpreter.Invoke()
if status != tflitego.TfLiteOk {
log.Println("invoke interpreter failed")
return
}
output := interpreter.GetOutputTensor(0)
out := output.OperateFloat32()
//here is optional use the function to decode the specie.
fmt.Println(topSpecie(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment