首页 文章

ValueError:无法为Tensor 'Placeholder:0'提供shape(2,)的值,其形状为'(1, 2)'

提问于
浏览
0

我是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

    有几件事情在这里密谋 . 我假设您希望 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))})
    

相关问题