Run importing TensorFlow graph fails for uninitialized variables

254 views
Skip to first unread message

linfeng

unread,
Nov 25, 2016, 5:41:38 AM11/25/16
to javacpp, samuel...@gmail.com
Hi All,
    I'm attempting to run tensorflow training in java by using javacpp-presets for tensorflow. I've generated a .pb file by using "tf.train.write_graph(sess.graph_def, '.', 'example.pb', as_text=False)" as below.

import tensorflow as tf
import numpy as np

x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0), name='Weights')
biases = tf.Variable(tf.zeros([1]), name='biases')
y = Weights * x_data + biases
loss = tf.reduce_mean(tf.square(y - y_data)) #compute the loss
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss, name='train')
init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init) #Very important
sess.run(train)
print(sess.run(Weights), sess.run(biases))
tf.train.write_graph(sess.graph_def, '.', 'example.pb', as_text=False)

I got "Exception in thread "main" java.lang.Exception: Attempting to use uninitialized value Weights"  when I run "tensorflow.Status s = session.Run(new StringTensorPairVector(new String[] {}, new Tensor[] {}), new tensorflow.StringVector(), new tensorflow.StringVector("train"), outputs);"  after loading the graph,"tensorflow.ReadBinaryProto(Env.Default(), "./example.pb", def);". 

Is there any javacpp-presets api to do the same work as "init = tf.global_variables_initializer()"? Or other way I can train a importing tensorflow graph?

I know tensorflow provide freeze_graph.py  takes a graphdef (.pb) and a checkpoint (.ckpt) file as input and outputs a graphdef file which contains the weights in the form of constants. However, the graph was trained and variable was inited. How could I train a graph defined by user's python file in java?

Thank you


Samuel Audet

unread,
Nov 25, 2016, 9:25:52 PM11/25/16
to linfeng, javacpp

Would this post answer your question by any chance?
https://medium.com/google-cloud/how-to-invoke-a-trained-tensorflow-model-from-java-programs-27ed5f4f502d


2016/11/25 19:41 "linfeng" <matri...@gmail.com>:
Reply all
Reply to author
Forward
0 new messages