如何在GoLang中使用训练好的Scikit Learn Python模型?

huangapple go评论106阅读模式
英文:

How to use trained Scikit Learn Python model in GoLang?

问题

我在Python环境中训练了一个Scikit Learn模型,现在我需要在GoLang中使用它进行推断。你能帮我解决如何在Python中导出/保存我的模型,并在GoLang中重新使用它吗?

我找到了一个解决方案,可以将Tensorflow模型保存为ONNX格式,并使用Onnx-go在GoLang中加载它。但这只适用于神经网络模型。对于Scikit Learn模型,我还没有找到解决方法。

英文:

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.

答案1

得分: 2

找到了以下解决方案。

解决方案1:

我们应该将Python模型以PMML格式导出,然后使用GoScore库在GoLang中导入。

以下是使用GoScore加载PMML文件的GoLang代码片段:

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") // 得分为0.486
score, _ := model.Score(features, "1") // 得分为0.514
score, _ := model.LabelScores(features) // map[0:243 1:257]

这篇Medium文章中找到了这个解决方案。(尽管它是将R模型转换为GoLang,但仍然相关)

解决方案2:

SkLearn-Porter是一个用于将模型转换为各种语言的Python库。不幸的是,目前它不支持所有Go的模型。

英文:

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.

答案2

得分: 0

你可以开发一个 REST JSON API 服务来暴露你的 scikit-learn 模型,并与 Go 客户端进行通信。

英文:

You can develop an REST json API service to expose your scikit-learn model and communicate with go client.

huangapple
  • 本文由 发表于 2022年3月9日 10:38:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/71403705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定