公司代碼都用java編寫咏窿,但是我做機器學習離不開python砖第,而且還包含第三方包sklearn〕仿現(xiàn)在再搞tensorflow,在老公的唐僧念之下梧兼,跑通了放吩,分享一下代碼。
package javaTopython;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class tensorflow_helloworld {
public void java2python() throws Exception{
// python解析器的路徑
String s1 = "D:\\ProgramData\\Anaconda3\\envs\\tensorflow\\python";
// 要執(zhí)行的python腳本
String s2 = "D:\\pythonworkspace\\DeepLearning\\temp.py";
// 傳入python腳本的參數(shù)
String s3 = 3+"";
String s4 = 4+"";
String[] arguments = new String[] {s1, s2, s3, s4};
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String result = "";
// python里的運行結果羽杰,想傳給java渡紫,就需要用這種readline的形式了到推。
while ((line = in.readLine()) != null) {
result += line;
System.out.println(line);
}
in.close();
// System.out.println(result);
}
public static void main(String[] args) throws Exception {
tensorflow_helloworld t = new tensorflow_helloworld();
t.java2python();
}
}
python部分的代碼很簡單,就是tensorflow的一個helloword
# -*- coding: utf-8 -*-
import tensorflow as tf
hello = tf.constant("Hello!TensorFlow")
test = tf.constant("bye")
sess = tf.Session()
print(sess.run(hello))
print(sess.run(test))
# 下面沒用惕澎,只是為了嘗試java調python時傳參用的
import sys
a = sys.argv[1] # 接收第一個參數(shù)
b = sys.argv[2] # 接收第二個參數(shù)
print(int(a) + int(b))
這是運行結果