java - 通过java加载机器学习sklearn模型(RandomForestClassifier)并作为参数发送到python文件中的函数
问题描述
我有一个 ML 模型,它被训练为保存为 pickle 文件 Randomforestclassifier.pkl。我想使用java加载一次,然后执行我用python编写的“预测”部分代码。所以我的工作流程是这样的:
- 读取 Randomforestclassifier.pkl 文件(一次)
- 将此模型作为输入发送到“python_file.py”中定义的函数,该函数从 java 为每个请求执行
- python_file.py 有预测代码,返回的预测应该被java代码捕获
请为此工作流程要求提供建议
解决方案
你可以使用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
希望这可以帮助。
推荐阅读
- matlab - 如何使用 Matlab 加速非常长的表达式计算?
- python - 在 Python 中将数组与精确值和近似值进行比较
- html - CSS 文件没有反映
- arrays - 具有嵌套 ID 数组的 Mongo 聚合
- python-3.x - pandas_ml 坏了吗?
- php - SQLSTATE[HY000] [1045] 用户 'username_a'@'localhost' 的访问被拒绝
- gradle - 只为所需平台构建带有二进制文件的 jar (javacpp)
- oracle - Oracle PL/SQL 中的校验和
- android - 为什么权限 Manifest.permission.ACCESS_FINE_LOCATION 没有激活“位置”选项?
- c# - MacOSX 的独立文件浏览器