请参考下面的tensorflow代码:
#!/usr/bin/env python3
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
import numpy.random as rnd
housing = fetch_california_housing()
m, n = (50000, 3)
n_epochs = 50000
learning_rate = 0.1
X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta")
y_pred = tf.matmul(X, theta, name="predictions")
error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(mse)
init = tf.global_variables_initializer()
ans_theta = np.array([[4],[3],[2],[1]]).astype(np.float32)
X_train = rnd.rand(m, n + 1)
y_train = X_train.dot(ans_theta).reshape(m, 1)
print("ans_theta=%s" % (ans_theta.transpose()))
print("X_train=%s" % (X_train[0]))
print("Expect y=%s" % (np.sum(X_train[0] * ans_theta.transpose())))
print("y_train=%s" % (y_train[0]))
def fetch_batch(epoch, batch_index, batch_size):
rnd.seed(epoch * n_batches + batch_index)
indices = rnd.randint(m, size=batch_size)
X_batch = X_train[indices]
y_batch = y_train[indices]
return X_batch, y_batch
n_epochs = 500
batch_size = 2000
n_batches = int(np.ceil(m / batch_size))
with tf.Session() as sess:
sess.run(init)
for epoch in range(n_epochs):
# for batch_index in range(n_batches):
# X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
#print("X_batch(%s):\n%s\n" % (X_batch.shape, X_batch[:1]))
#print("y_batch(%s):\n%s\n" % (y_batch.shape, y_batch[:1]))
# sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
sess.run(training_op, feed_dict={X:X_train, y:y_train})
best_theta = theta.eval()
print("MSE=%s" % (mse.eval()))
print("Best theta:")
print(best_theta)
它会导致异常,如下所示:
由op'X'引起,定义于:文件“./ch9_t00.py”,第19行,in X = tf.placeholder(tf.float32,shape =(None,n + 1),name =“X”)File “/usr/local/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py” 第1507行,占位符 name = name)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py”, 1997年,在_placeholder name = name)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py”, 第768行,在apply_op中 op_def = op_def)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第2336行,在create_op中 original_op = self._default_original_op,op_def = op_def)文件“/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py”, 第1228行,在 init 中 self._traceback = _extract_stack()
InvalidArgumentError(请参阅上面的回溯):您必须提供值 对于占位符张量'X'与dtype float [[Node:X = Placeholderdtype = DT_FLOAT,shape = [],_ device =“/ job:localhost / replica:0 / task:0 / cpu:0”]]
我不知道为什么。如果我删除行“print(”MSE =%s“%(mse.eval()))”,那么一切都会好的。 有什么建议吗?
提前致谢!
答案 0 :(得分:3)
如果没有任何数据,您无法评估您的MSE,您必须为占位符x
和y
提供值,以评估输入{{1}上的网络预测之间的均方误差和x
中给出的地面实况标签。
您可以使用
y
或在训练时这样做:
print("MSE=%s" % sess.run(mse, feed_dict={X:X_train, y:y_train}))