ValueError:无法为形状为((1,2)''的张量'Placeholder:0'提供形状(2,)的值

时间:2018-07-14 18:33:31

标签: python numpy tensorflow machine-learning linear-regression

我是Tensorflow的新手,正在尝试创建线性回归模型。我的代码是

import numpy as np
import tensorflow as tf

bias = np.ones((50, 1))
trainX = np.arange(0, 10, 0.2).reshape(50, 1)
trainY = (3 * trainX + np.random.rand(trainX.shape[0]) * 20 - 10) + 10
trainX = np.append(bias, trainX, axis=1)

X = tf.placeholder("float", shape=(1, 2))
Y = tf.placeholder("float")
w = tf.Variable([[0.0, 0.0]], name="weights")

model = tf.matmul(X, tf.transpose(w))
cost = tf.pow((Y - model), 2)

init = tf.global_variables_initializer()
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost)

with tf.Session() as sess:
    sess.run(init)

    for i in range(50):
        for (x, y) in zip(trainX, trainY):
            sess.run(train_op, feed_dict={X: x, Y: y})

    print(sess.run(w))

我不知道我在做什么错。我认为问题在于初始化权重。这个想法很容易预测两个权重常数,它们最能预测拟合数据的线。

I'm getting this error in colaboratory notebook

1 个答案:

答案 0 :(得分:0)

这里有很多阴谋。我假设您希望trainY的形状为(50,),但是由于仅在重塑后才添加噪声,因此广播会导致trainX + np.random.rand(trainX.shape[0])的形状为(50, 50)。如果您将代码的初始部分更改为

bias = np.ones(50)
trainX = np.arange(0, 10, 0.2)
trainY = (3 * trainX + np.random.rand(trainX.shape[0]) * 20 - 10) + 10
trainX = np.vstack([bias, trainX]).T

并确保通过以下方式正确设置形状

sess.run(train_op, feed_dict={X: x.reshape((1, 2)), Y: y})

然后您的代码将运行。

但是,由于您只处理二维向量的内积,因此可以通过完全使用tf.tensordot来避免重塑:

X = tf.placeholder("float", shape=(2,))
Y = tf.placeholder("float")
w = tf.Variable([0.0, 0.0], name="weights")

model = tf.tensordot(X, w, 1)

最后,请注意,虽然在将样本传递给优化器之前进行分割的方法(通常称为批处理)对于大型数据集非常有效,但在您的情况下,您也可以将整个样本传递给一旦;也就是说,某事等于

X = tf.placeholder("float", shape=(50, 2))
Y = tf.placeholder("float", shape=(50, 1))
w = tf.Variable(tf.zeros([2, 1], "float"), name="weights")

model = tf.matmul(X, w)
cost = tf.reduce_sum(tf.pow((Y - model), 2))

init = tf.global_variables_initializer()
train_op = tf.train.GradientDescentOptimizer(0.0001).minimize(cost)

with tf.Session() as sess:
    sess.run(init)
    for i in range(10000):
        sess.run(train_op, feed_dict={X: trainX, Y: trainY.reshape((50, 1))})