tensorflow訓練的模型在java中的使用

來源:互聯網
上載者:User

tensorflow訓練模型通常使用python api編寫,簡單記錄下這些模型儲存後怎麼在java中調用。

python中訓練完成,模型儲存使用如下api儲存:

# 儲存二進位模型output_graph_def = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, output_node_names=['y_conv_add'])with tf.gfile.FastGFile('/logs/mnist.pb', mode='wb') as f:    f.write(output_graph_def.SerializeToString())
儲存為二進位pb檔案,主要的點是output_node_names數組,該資料的名稱表示需要儲存的tensorflow tensor名。既是在python中定義模型時指定的計算操作的name。填寫什麼就儲存到什麼節點。在cnn模型中,通常是分類輸出的名稱。

例如模型定義時代碼為:

y_conv = tf.add(tf.matmul(h_fc1_drop, W_fc2), b_fc2, name='y_conv_add') # cnn輸出層,名稱y_conv_add# 訓練和評價模型softmax = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)

模型在java中使用需要關心模型輸入tensor和輸出tensor名,所以定義模型時,所有的輸入tensor最好指定名稱,如輸入x和dropout名。

java中調用程式碼片段:

public static void main(String[] args) {String labels = "17,16,7,8,3,15,4,14,2,5,12,18,9,10,1,11,13,6";TensorFlowInferenceInterface tfi = new TensorFlowInferenceInterface("D:/tf_mode/output_graph.pb","imageType");final Operation operation = tfi.graphOperation("y_conv_add");Output output = operation.output(0);Shape shape = output.shape();final int numClasses = (int) shape.size(1);float[] floatValues = getImagePixel("D:/tf_mode/ci/ci/333.jpg"); //將圖片處理為輸入對應張量格式// 輸入圖片tfi.feed("x_input", floatValues, 1, 2048); //將資料複製給輸入張量x_input即為模型定義時的x名稱tfi.run(new String[] { "y_conv_add" }, false);//輸出張量float[] outPuts = new float[numClasses];//結果分類tfi.fetch("y_conv_add", outPuts);//接收結果 outPuts儲存的即為預測結果對應的機率,最大的一個通常為本次預測結果}

TensorFlowInferenceInterface參考:

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/android/java/org/tensorflow/contrib/android/TensorFlowInferenceInterface.java

java api和tensorflow的依賴:

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java

調用過程參考:

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowImageClassifier.java

註:內容為隨手記錄,未檢查錯別字、是否遺漏等。

鑒於多人所要代碼,在此提供python及java調用實現:

http://pan.baidu.com/s/1mi1hklM   交代下背景python實現為基於.pb檔案的二次訓練,只訓練最後一層分類層的代碼,項目初始為解決單個漢字的識別問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.