Java 后端跑机器学习模型方法
使用Runtime.getRuntime().exec()
1、 步骤一: 安装pytorch
pytorch官网
选择自己的配置进行下载安装,复制命令然后执行即可,在windows本地python环境安装的会发现出现因为路径过长而安装失败的现象。
解决方案:打开注册表,修改HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem的主键:将LongPathsEnabled的键值改成1,使能长路径即可。
2、 步骤二: 安装其它你需要的库
…略
3、 步骤三: 通过Runtime.getRuntime().exec()执行命令行指令跑脚本即可,Service代码如下:
/**
* @Function: runModel
* @Parameters: none
* @Todo: 调用python脚本,使用模型判断结果
* */
public String runModel() throws JSONException, IOException, InterruptedException {
String command [] = {"python", "你的python文件的绝对路径", "python文件的入口参数"};
Process process = null;
process = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(process.getInputStream()));
System.out.println("The result is:\n");
String s = null;
String resultBack = "";
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
resultBack = s;
}
return 你需要返回的内容;
}
结论:
其实原本我的pytorch是配置在anaconda的,但是搜索了很多却没有发现如何通过cmd打开Anaconda Promt然后再执行py文件, 因此最后还是在本地的python环境下配置了Pytorch,使用本地的python环境来跑模型。、
2021/03/30新增
Runtime.getRuntime().exec() 在同一个命令行中执行多命令的方法(可以解决Anaconda下python环境的运行),下面的代码块是我在树莓派上写的后台部署程序;
/**
* @Function: runModel
* @Parameters: MultipartFile file, String fileName
* @Todo: 调用python脚本,使用模型判断图片结果
* */
public String runModel(MultipartFile file, String fileName) throws JSONException, IOException, InterruptedException {
// IO流先读入图片保存在根目录
try (OutputStream outputStream = new FileOutputStream(fileName);
InputStream inputStream = file.getInputStream()) {
byte[] buffer = new byte[1024];
while (inputStream.read(buffer) > 0) {
outputStream.write(buffer);
}
} catch (IOException e) {
// 错误操作
}
// 命令行运行判断模型
Process process = null;
process = Runtime.getRuntime().exec("su pi");
// 执行多条命令
DataOutputStream os = new DataOutputStream(process.getOutputStream());
// 命令1
os.writeBytes("python 你的python文件绝对路径 "+ fileName + "\n");
// 命令2
os.writeBytes("exit\n");
os.flush();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(process.getErrorStream()));
System.out.println("The result is:\n");
String s = null;
String resultBack = "";
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
resultBack = s;
}
System.out.println("ErrorInfo is:\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
return 你要返回的信息
}
这里运行su pi是因为我当时配置树莓派上pytorch和numpy的时候是在pi用户下配置的,所以要切换到pi用户,才能在脚本中导入自己需要的库,否则会提示找不到模块;