我最近一直在学习 Andrew Ng 的类(class),我想我不妨尝试用其他语言(对我来说恰好是 Python)来实现我所学到的东西,但我遇到了障碍。 这是我的代码:
train_x = [[1,2,3,4], [5,6,7,8]]
train_y = [24, 1680]
train_x = np.asarray(train_x)
train_y = np.asarray(train_y)
m = train_x.shape[0]
n = train_x.shape[1]
X = tf.placeholder(tf.float32, [None, n])
Y = tf.placeholder(tf.float32, [None, n])
W = tf.Variable(tf.zeros(n, 1))
b = tf.Variable(tf.zeros(1, 1))
model = tf.add(tf.multiply(X, W), b)
cost = tf.reduce_sum(tf.pow(model-Y, 2)) / (2*m)
然后我使用以下方法训练 GradientDescentOptimizer:
for i in range(1000):
for x, y in zip(train_x, train_y):
sess.run(optimizer, feed_dict={X: x, Y: y})
我收到的错误是(在最后一行):
ValueError: Cannot feed value of shape (4,) for Tensor 'Placeholder:0', which has shape '(?, 4)'
任何帮助将不胜感激。有解释就更好了。
最佳答案
您需要将输入 x
reshape 为 (some_number, 4)
。还要修复 y
占位符
train_x = [[1, 2, 3, 4], [5, 6, 7, 8]]
train_y = [24, 1680]
train_x = np.asarray(train_x)
train_y = np.asarray(train_y)
m = train_x.shape[0]
n = train_x.shape[1]
X = tf.placeholder(tf.float32, [None, n])
Y = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.random_normal((n, 1)))
b = tf.Variable(tf.zeros(1, 1))
model = tf.add(tf.matmul(X, W), b)
cost = tf.reduce_sum(tf.pow(model - Y, 2)) / (2 * m)
...
for i in range(1000):
for x, y in zip(train_x, train_y):
x = np.reshape(x, (-1, 4))
y = np.reshape(y, (-1, 1))
sess.run(optimizer, feed_dict={X: x, Y: y})
关于python - Tensorflow 向量的形状为 (col,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45985682/