【问题标题】:Java and Python Integration using Jep使用 Jep 集成 Java 和 Python
【发布时间】:2018-10-19 02:08:38
【问题描述】:

我正在尝试使用 Jep 集成 python 和 java。我已经从使用 Jep 的 java 程序中将随机森林模型从 pickle 文件(rf.pkl)加载为 sklearn.ensemble.forest.RandomForestClassifier 对象。 我希望这种加载是一次,所以我想通过从 java 发送“rfmodel”参数来调用 python 函数来执行 python 脚本 prediction.py 中定义的 python 函数(使用 rf 模型进行预测)。 但是从 java 发送到 python 的参数在 python 中被读取为字符串。如何将python中参数的数据类型保留为sklearn.ensemble.forest.RandomForestClassifier?

Jep jep = new Jep();
jep.eval("import pickle");
jep.eval("clf = pickle.load(open('C:/Downloads/DSRFmodel.pkl', 'rb'))");
jep.eval("print(type(clf))");
Object randomForest = jep.getValue("clf");

jep.eval("import integration");
jep.set("arg1", requestId);
jep.set("arg2", randomForest);
jep.eval("result = integration.trainmodel(arg1, arg2)");

------------
python.py

import pickle
def trainmodel(requestid, rf):

//when rf is printed it is 'str' format.

【问题讨论】:

  • 你的字符串是什么样子的?此外,这不是 Java 问题。您已经有一个 Python-String - 所以您的问题是“如何从字符串创建 klearn.ensemble.forest.RandomForestClassifier 对象?”

标签: java python jepp


【解决方案1】:

当 Jep 将 Python 对象转换为 Java 对象时,如果它无法识别 Python 类型,它将返回 Python 对象的字符串表示形式,有关该行为的讨论,请参阅 this bug。如果您正在运行最新版本的 Jep(3.8),您可以通过将 Java 类传递给 getValue 函数来覆盖此行为。创建 PyObject 类是为了充当任意 python 对象的通用包装器。下面的代码应该做你想做的事:

Jep jep = new Jep();
jep.eval("import pickle");
jep.eval("clf = pickle.load(open('C:/Downloads/DSRFmodel.pkl', 'rb'))");
jep.eval("print(type(clf))");
Object randomForest = jep.getValue("clf", PyObject.class);

jep.eval("import integration");
jep.set("arg1", requestId);
jep.set("arg2", randomForest);
jep.eval("result = integration.trainmodel(arg1, arg2)");

【讨论】:

    猜你喜欢
    • 2022-11-07
    • 2023-03-16
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多