首页 > 解决方案 > 通过java加载机器学习sklearn模型(RandomForestClassifier)并作为参数发送到python文件中的函数

问题描述

我有一个 ML 模型,它被训练为保存为 pickle 文件 Randomforestclassifier.pkl。我想使用java加载一次,然后执行我用python编写的“预测”部分代码。所以我的工作流程是这样的:

  1. 读取 Randomforestclassifier.pkl 文件(一次)
  2. 将此模型作为输入发送到“python_file.py”中定义的函数,该函数从 java 为每个请求执行
  3. python_file.py 有预测代码,返回的预测应该被java代码捕获

请为此工作流程要求提供建议

标签: javapythonscikit-learn

解决方案


你可以使用Jep

我实际上从未在 Jep 中测试过 pickle 模块,但对于你的情况,它会是这样的:

try(Jep jep = new Jep()) {
    // Load model
    jep.eval("import pickle");
    jep.eval("with open('Randomforestclassifier.pkl', 'rb'): as f: clf = pickle.load(f)");
    Object randomForest = jep.getValue("clf");

    ...

    // Then in another context you can pass your model to your function
    jep.eval("import predictionModule");
    jep.set("arg", randomForest);
    jep.eval("result = predictionModule.use(arg)");
    Object result = jep.getValue("result");
}

假设您有一个名为的模块predictionModule.py,它应该是这样的:

import pickle

def use(model_as_bytes):
    model = pickle.loads(model_as_bytes)
    print(model)
    # do other stuff
    ...
    return prediction

希望这可以帮助。


推荐阅读