Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use trained Scikit Learn Python model in GoLang?

I have trained a Scikit Learn model in Python environment which i need to use it for inference in GoLang. Could you please help me how can i export/save my model in python and then use it back in GoLang.

I found a solution for Neural Network model where i can save Tensorflow model in ONNX format and load it using Onnx-go in GoLang. But this is specific for Neural Network models. But I am unable to figure it out for scikit-learn models.

like image 689
Raju Saladi Avatar asked Sep 11 '25 23:09

Raju Saladi


1 Answers

Found out the following solutions.

Solution1:

We should be exporting the python model in PMML format and then import in GoLang using GoScore Library

Here is a GoLang code snippet loading PMML file using GoScore

modelXml, err := ioutil.ReadFile("titanic_rf.pmml")
if (err != nil) {
  panic(err)    
}
var model goscore.RandomForest 
xml.Unmarshal([]byte(modelXml), &model)

features := map[string]interface{}{
  "Sex": "male",
  "Parch": 0,
  "Age": 30,
  "Fare": 9.6875,
  "Pclass": 2,
  "SibSp": 0,
  "Embarked": "Q",
}

score, _ := model.Score(features, "0") // scores 0.486
score, _ := model.Score(features, "1") // scores 0.514
score, _ := model.LabelScores(features) // map[0:243 1:257]

Found this solution referring to this medium article. (Although its R Model to GoLang, it still relevant)

Solution2:

SkLearn-Porter is library in python to port models into various languages. Unfortunately, It doesn't support all the models for Go at the moment.

like image 145
Raju Saladi Avatar answered Sep 14 '25 12:09

Raju Saladi