【发布时间】:2017-04-04 10:02:29
【问题描述】:
我正在尝试加载以前保存的 TENSOFLOW 模型(图形和变量)。
这是我在训练期间导出模型的方式
tf.global_variables_initializer().run()
y = tf.matmul(x, W) + b
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
for batch_index in range(batch_size):
batch_xs, batch_ys = sample_dataframe(train_df, N=batch_size)
#print(batch_xs.shape)
#print(batch_ys.shape)
sess.run(train_step, feed_dict = {x: batch_xs, y_:batch_ys})
if batch_index % 100 == 0:
print("Batch "+str(batch_index))
correct_predictions = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
print("Accuracy: "+str(sess.run(accuracy,
feed_dict = {x: batch_xs, y_: batch_ys})))
#print("Predictions "+str(y))
#print("Training accuracy: %.1f%%" %accuracy())
if batch_index + 1 == batch_size:
#Save the trained model
print("Exporting trained model")
builder = saved_model_builder.SavedModelBuilder(EXPORT_DIR)
builder.add_meta_graph_and_variables(sess, ['simple-MNIST'])
builder.save(as_text=True)
请忽略模型是如何定义的(这只是一个玩具示例),只检查调用 save 方法的最后几行。一切顺利,模型正确保存在 FS 中。
当我尝试加载导出的模型时,我总是收到以下错误:
TypeError: 无法将 MetaGraphDef 转换为张量或操作。
这是我加载模型的方式:
with tf.Session() as sess:
print(tf.saved_model.loader.maybe_saved_model_directory(export_dir))
saved_model = tf.saved_model.loader.load(sess, ['simple-MNIST'], export_dir)
sess.run(saved_model)
知道如何解决吗?似乎模型以错误的格式导出,但我不知道如何更改它。
这是一个用于加载模型并对其评分的简单脚本。
with tf.device("/cpu:0"):
x = tf.placeholder(tf.float32, shape =(batch_size, 784))
W = tf.Variable(tf.truncated_normal(shape=(784, 10), stddev=0.1))
b = tf.Variable(tf.zeros([10]))
y_ = tf.placeholder(tf.float32, shape=(batch_size, 10))
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(tf.saved_model.loader.maybe_saved_model_directory(export_dir))
saved_model = tf.saved_model.loader.load(sess, ['simple-MNIST'], export_dir)
batch_xs, batch_ys = sample_dataframe(train_df, N=batch_size)
y = tf.matmul(x, W) + b
correct_predictions = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
print("Test Accuracy: "+ str(sess.run(accuracy, feed_dict = {x: batch_xs, y_: batch_ys})))
在全新的 PYTHON 上下文中运行此脚本,会以非常低的准确度对模型进行评分(似乎加载模型方法没有正确设置图形变量)
谢谢!
【问题讨论】:
标签: python tensorflow tensorflow-serving