1. 程式人生 > >Train TF models in Python and Invoke models in Java

Train TF models in Python and Invoke models in Java

  • Plan A
#Train in Python
import tensorflow as tf
# good idea
# https://stackoverflow.com/documentation/tensorflow/10718/save-tensorflow-model-in-python-and-load-with-java#t=201709030336395954421
tf.reset_default_graph()

# DO MODEL STUFF
# Pretrained weighting of 2.0
W = tf.get_variable('w', initializer=tf.constant
(2.0), dtype=tf.float32) # Model input x x = tf.placeholder(tf.float32, name='x') # Model output y = W*x y = tf.multiply(W, x, name='y') # DO SESSION STUFF sess = tf.Session() sess.run(tf.global_variables_initializer()) # SAVE THE MODEL builder = tf.saved_model.builder.SavedModelBuilder("/tmp/model" ) builder.add
_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING] ) builder.save()
//Invoke in Java
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;

import java.io.IOException;
import java.nio.FloatBuffer;

/**
 * Created by apollo on 17-9-3.
 * https://stackoverflow.com/documentation/tensorflow/10718/save-tensorflow-model-in-python-and-load-with-java#t=201709030336395954421
 */
public class LoadModel { public static void main(String[] args) throws IOException { // good idea to print the version number, 1.2.0 as of this writing System.out.println(TensorFlow.version()); final int NUM_PREDICTIONS = 1; /* load the model Bundle */ SavedModelBundle b = SavedModelBundle.load("/tmp/model", "serve"); // create the session from the Bundle Session sess = b.session(); // create an input Tensor, value = 2.0f Tensor x = Tensor.create( new long[]{NUM_PREDICTIONS}, FloatBuffer.wrap(new float[]{2.0f}) ); // run the model and get the result, 4.0f. float[] y = sess.runner() .feed("x", x) .fetch("y") .run() .get(0) .copyTo(new float[NUM_PREDICTIONS]); // print out the result. System.out.println(y[0]); } }

==============================================

||||Plan B|||| {only in python , only import}
On the Python side, Tensorflow suggests to use a Saver object to save a model to disk. It creates a .meta file that has the definition and has .data files for the weights. In Python, I use new_saver=tf.train.import_meta_graph(var_filename)
new_saver.restore(sess, model_filename) to read the model from the disk.

||||Plan C|||| {only in python, only save}
tf.train.write_graph(sess.graph_def, “./data”, “aaa.pb”);
this aaa.pb contains graph and variables , not like Plan A(that pb only contain graph)

||||Plan D|||| {only in python, only save , import and perdict have error}
//https://github.com/jiegzhan/multi-class-text-classification-cnn-rnn
saver = tf.train.Saver(tf.all_variables())

error===
saver = tf.train.import_meta_graph(“{}.meta”.format(checkpoint_file[:-5]))
saver.restore(sess, checkpoint_file)
path = saver.save(sess, checkpoint_prefix, global_step=current_step)

classifier = learn.DNNClassifier(hidden_units=[10, 20, 5], n_classes=5,feature_columns=feature_columns)
A model_saved.pbtxt file is created.

SavedModelBundle bundle=SavedModelBundle.load(“/java/…/ModelSave”,”serve”);

Reference Website:

相關推薦

Train TF models in Python and Invoke models in Java

Plan A #Train in Python import tensorflow as tf # good idea # https://stackoverflow.com/documentation/tensorflow/10718/save-te

[Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript

In this lesson we are going to setup a project from scratch by introducing the JavaScript snippet to load a WebAssembly module. We demonstrate two differen

round() Function in Python and Matlab

Python always round to nearest even. test_1 = np.around(3.5) test_2 = np.around(4.5) test_1 = 4 test

Understanding Built-In User and Group Accounts in IIS 7

Understanding Built-In User and Group Accounts in IIS 7 By lzb October 19, 2018 Introduction In earlier versions of IIS, a local account called&nb

How to Sort a HashMap by Values in Ascending and Descending Order in Java 8

In the last article, I have shown you how to sort a Map in Java 8 by keys and today, I'll teach you how to sort a Map by values using Java 8 features e.g.

The Roots of Writing Lie in Hopes and Dreams, Not in Accounting

This story is for Medium members.Continue with FacebookContinue with GoogleMedium curates expert stories from leading publishers exclusively for members (w

install glm library in ubuntu and use it in qt

1. open link http://sourceforge.net/projects/ogl-math/?source=typ_redirect then download and extract 2. sudo cp -r /home/tjiang/Download

Save and Load Machine Learning Models in Python with scikit

Hello Jason, I am new to machine learning. I am your big fan and read a lot of your blog and books. Thank you very much for teaching us machine le

How to Build Exponential Smoothing Models Using Python: Simple Exponential Smoothing, Holt, and

How to Build Exponential Smoothing Models Using Python: Simple Exponential Smoothing, Holt, and Holt-WintersHow many iPhone XS will be sold in first 12 mon

How to rapidly test dozens of deep learning models in Python

Although k-fold cross validation is a great way of assessing a model’s performance, it’s computationally expensive to obtain these results. We can simply s

Training Machine Learning Models in Pharma and Biotech Manufacturing with Bigfinite Amazon Web Services

Creating and training machine learning models has become less time consuming and more cost efficient thanks to technology advancements like open source sof

Build and train a neural net from scratch in Python

Deep learning frameworks like TensorFlow or PyTorch are being used with some frequency. but using such a framework hides a lot of internals which can help

[Python] How to unpack and pack collection in Python?

ide ont add off art video lec ref show It is a pity that i can not add the video here. As a result, i offer the link as below: How to

Mutable and Immutable Variables in Python

pytho src 賦值 參數 解決 再看 變量 復制 left 本文解決python中比較令人困惑的一個小問題:傳遞到函數中的參數若在函數中進行了重新賦值,對於函數外的原變量有何影響。看一個小栗子: def fun(a): a=2 return a=1

DIY 3D SCANNER BASED ON STRUCTURED LIGHT AND STEREO VISION IN PYTHON LANGUAGE

可惜拿不到原始碼,有獲取到原始碼的朋友可以共享下(學術用),謝謝! 以下是轉載內容: Published Mar 19th, 2015DownloadFavorite   Intro: DIY 3D Scanner Based on Structured Light

西遊之路——python全棧——django中models配置 python---django使用資料庫(orm)

目錄   Django支援多種資料庫,sqlite,mysql,oracle等,其預設資料庫是sqlite 在settings檔案中可以發現: DATABASES = { 'default': { 'ENGINE': '

Python文摘:More About Unicode in Python 2 and 3

原文地址:http://lucumr.pocoo.org/2014/1/5/unicode-in-2-and-3/   It's becoming increasingly harder to have reasonable discussions about the differences b

資料分析文摘:Reading and Writing JSON to a File in Python

原文地址:https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/   Over the last 5-10 years, the JSON format has been one of, if