我用 Python 开发了一个 ML 分类器模型,我想从 java 中使用它。 我查找了一些选项,例如 Jython 等。 谁能帮助我,我怎样才能实现这个用例?
我尝试使用 Jython,但没有找到适合此用例的任何好的文档
一个简单的方法是为java提供一个Web api,这是一个例子:
import uvicorn
from fastapi import FastAPI
app = FastAPI()
model = lambda x: "positive" if len(x) > 5 else "negative"
@app.get("/{sentence}")
async def inference(sentence: str):
return {"message": model(sentence)}
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=5000)
model 是你的机器学习模型或推理函数,在 java 中,你应该这样使用:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequestExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://localhost:5000/"); // 替换为你要访问的API地址
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 设置请求头(可选)
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应数据
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println(response.toString());
} else {
System.out.println("GET request failed with response code: " + responseCode);
}
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}