python - 从张量流模型中获取预测
问题描述
我想从我训练有素的张量流模型中获得预测。以下是我用于训练模型的代码。
def train_model(self, train, test, learning_rate=0.0001, num_epochs=16, minibatch_size=32, print_cost=True, graph_filename='costs'):
# Ensure that model can be rerun without overwriting tf variables
ops.reset_default_graph()
# For reproducibility
tf.set_random_seed(42)
seed = 42
# Get input and output shapes
(n_x, m) = train.images.T.shape
n_y = train.labels.T.shape[0]
costs = []
# Create placeholders of shape (n_x, n_y)
X, Y = self.create_placeholders(n_x, n_y)
# Initialize parameters
parameters = self.initialize_parameters()
# Forward propagation
Z3 = self.forward_propagation(X, parameters)
# Cost function
cost = self.compute_cost(Z3, Y)
# Backpropagation (using Adam optimizer)
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)
# Initialize variables
init = tf.global_variables_initializer()
# Start session to compute Tensorflow graph
with tf.Session() as sess:
# Run initialization
sess.run(init)
# Training loop
for epoch in range(num_epochs):
epoch_cost = 0.
num_minibatches = int(m / minibatch_size)
seed = seed + 1
for i in range(num_minibatches):
# Get next batch of training data and labels
minibatch_X, minibatch_Y = train.next_batch(minibatch_size)
# Execute optimizer and cost function
_, minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X.T, Y: minibatch_Y.T})
# Update epoch cost
epoch_cost += minibatch_cost / num_minibatches
# Print the cost every epoch
if print_cost == True:
print("Cost after epoch {epoch_num}: {cost}".format(epoch_num=epoch, cost=epoch_cost))
costs.append(epoch_cost)
# Plot costs
plt.figure(figsize=(16,5))
plt.plot(np.squeeze(costs), color='#2A688B')
plt.xlim(0, num_epochs-1)
plt.ylabel("cost")
plt.xlabel("iterations")
plt.title("learning rate = {rate}".format(rate=learning_rate))
plt.savefig(graph_filename, dpi=300)
plt.show()
# Save parameters
parameters = sess.run(parameters)
print("Parameters have been trained!")
# Calculate correct predictions
correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))
# Calculate accuracy on test set
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print ("Train Accuracy:", accuracy.eval({X: train.images.T, Y: train.labels.T}))
print ("Test Accuracy:", accuracy.eval({X: test.images.T, Y: test.labels.T}))
return parameters
训练模型后,我想从模型中提取预测。所以我添加
print(sess.run(accuracy, feed_dict={X: test.images.T}))
但是在运行上面的代码后我看到了下面的错误:
InvalidArgumentError:您必须使用 dtype 浮点数和形状 [10,?] [[{{node Y}} = Placeholderdtype=DT_FLOAT, shape=[10,?], _device="/job:本地主机/副本:0/任务:0/设备:CPU:0“]]
欢迎任何帮助..
解决方案
张量accuracy
是张量的函数,而张量correct_prediction
又是(在其余部分中)的函数Y
。
因此,您被正确地告知您也应该为该占位符提供值。
我假设持有您的标签,因此您的 feed_dict 也将包含正确的值Y
也应该具有直观的意义。
希望有帮助。
祝你好运!Y
推荐阅读
- javascript - 在javascript中单击按钮时如何显示模式?我需要一个例子,谢谢
- javascript - 在 .reduce() 中使用时,在空对象上设置属性会创建一个字符串
- angular - 如何完全阻止 ngx boostrap modal 后面的屏幕,使后台的按钮即使使用键盘输入也不起作用?
- android - DialogPreference 没有在我期望的时候保存首选项?
- python-3.x - Python - 可以在 MRZ 上执行 OCR(100% 准确度)吗?
- visual-studio - Visual Studio 2015 调试加载缓慢
- sbt - 没有 .repositories 文件的built.sbt,m2compatible 设置为 true
- php - Font Awesome 未显示 - Avada 主题 (Wordpress) - 添加 fa 类
- reactjs - 我可以在一个 monorepo 中有多个 babel.config.js 吗?
- excel - 宏/UDF 从单元格中提取多次出现的文本 URL