我是机器学习和Tensorflow的新手,通过使用其示例教程源代码,模型得到训练并打印出准确性,但它不包括导出模型和变量的源代码以及用于预测新图像的导入。
所以我修改了源代码以导出模型,并创建一个新的python脚本来使用测试数据集进行预测。
以下是导出培训模型的源代码:
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
print("run here3")
# Create the model
x = tf.placeholder(tf.float32, [None, 784], name="x")
W = tf.Variable(tf.zeros([784, 10]), name="W")
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
saver = tf.train.Saver()
sess = tf.InteractiveSession()
... ignore the source code for the cost function definition and train the model
#after the model get trained, save the variables and y
tf.add_to_collection('W', W)
tf.add_to_collection('b', b)
tf.add_to_collection('y', y)
saver.save(sess, 'result')
在新的python脚本中,我尝试恢复模型并重新执行y函数
sess = tf.Session()
saver = tf.train.import_meta_graph('result.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
W = tf.get_collection('W')[0]
b = tf.get_collection('b')[0]
y = tf.get_collection('y')[0]
mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data', one_hot=True)
img = mnist.test.images[0]
x = tf.placeholder(tf.float32, [None, 784])
sess.run(y, feed_dict={x: mnist.test.images})
一切正常,如果我打印它,我可以得到W和b值,但是在执行最后一个语句时遇到错误(运行y函数)。
Caused by op u'x', defined at:
File "predict.py", line 58, in <module>
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
File "/Users/zhouqi/git/machine-learning/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 44, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "predict.py", line 25, in main
saver = tf.train.import_meta_graph('result.meta')
File "/Users/zhouqi/git/machine-learning/tensorflow/lib/python2.7/site- packages/tensorflow/python/training/saver.py", line 1566, in import_meta_graph
**kwargs)
File "/Users/zhouqi/git/machine-learning/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/meta_graph.py", line 498, in import_scoped_meta_graph
producer_op_list=producer_op_list)
File "/Users/zhouqi/git/machine-learning/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 288, in import_graph_def
op_def=op_def)
File "/Users/zhouqi/git/machine-learning/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2327, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/Users/zhouqi/git/machine-learning/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1226, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x' with dtype float
[[Node: x = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
这很奇怪,因为我使用相同的语句来定义x,并在执行y函数时使用相同的方法提供x,我不知道为什么它不起作用?
答案 0 :(得分:1)
问题是新的占位符:
x = tf.placeholder(tf.float32, [None, 784])
创建具有相同名称的占位符是不够的。实际上,您需要在创建模型时使用的占位符。因此,您还必须在第一个文件中将x添加到集合中:
tf.add_to_collection('x', x)
并将其加载到新文件中:
x = tf.get_collection('x')[0]
而不是创建一个新的。