Python 张量流多元回归误差

Python 张量流多元回归误差,python,tensorflow,linear-regression,Python,Tensorflow,Linear Regression,在这段代码中,Xfortrain是278*5列表,Yfortrain是278*1列表。我不断得到以下错误: import tensorflow as tf X = tf.placeholder(tf.float32, [None,5]) w = tf.Variable(tf.zeros([5,1]), name = 'weight') b = tf.Variable(tf.zeros([1]), name = 'bias') y = tf.matmul(X, w) + b Y = tf.plac

在这段代码中,Xfortrain是278*5列表,Yfortrain是278*1列表。我不断得到以下错误:

import tensorflow as tf
X = tf.placeholder(tf.float32, [None,5])
w = tf.Variable(tf.zeros([5,1]), name = 'weight')
b = tf.Variable(tf.zeros([1]), name = 'bias')
y = tf.matmul(X, w) + b
Y = tf.placeholder(tf.float32, [None,1])

cost = tf.reduce_mean(tf.square(Y-y))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(cost)

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

x_train = Xfortrain
y_train = Yfortrain

for i in range(10000):
    cost_val, hy_val, _ = sess.run([cost,y,train_step], feed_dict = {X: 
x_train, Y: y_train})

print('w0:%f' % sess.run(w[0]))
print('w1:%f' % sess.run(w[1]))
print('w2:%f' % sess.run(w[2]))
print('w3:%f' % sess.run(w[3]))
print('w4:%f' % sess.run(w[4]))
print('b:%f' % sess.run(b))

我做了很多研究,但没能解决这个问题。我知道这是一个架构错误,但我不知道用什么代码来解决它。我是tensorflow的新手,我想用它来解决多元回归模型。非常感谢

我运行了你的代码,工作正常。可能是您错误地加载了Xfortrain和Yfortrain。我将我的代码张贴在答案部分。看看。你能发布Xfortrain和Yfortrain变量值吗?很有效。向上投票,你能补充一下你的代码和宋武的代码有什么区别吗。它是如何帮助解决问题的?代码结构基本相同。当我看到错误时,我怀疑列车数据有问题。因此,我创建了一些具有所需尺寸/形状的随机数据,代码工作正常。正如我在评论中提到的,我添加代码只是为了证明代码运行良好,并且提要数据可能有问题。我认为原始代码存在一些形状问题。由于您已经生成了满足代码形状要求的随机变量,因此您的代码可以正常工作。您好,Clock和Vikash,谢谢您的帮助,这非常奇怪,因为代码确实可以正常工作,但是当它在我的训练数据上运行时,就会出现错误。我仔细检查了我的训练数据,它们确实是正确的。有点无助……@SongWu,您是否在代码中的某个地方意外更改了占位符变量的维度?在使用培训数据并运行优化器之前,请检查Yfortrain的形状
ValueError: Cannot feed value of shape (278, 5) for Tensor 
'Placeholder_23:0', which has shape '(?, 1)'
import tensorflow as tf
import numpy as np

X = tf.placeholder(tf.float32, [None,5])
w = tf.Variable(tf.zeros([5,1]), name = 'weight') 
b = tf.Variable(tf.zeros([1]), name = 'bias')
y = tf.matmul(X, w) + b
Y = tf.placeholder(tf.float32, [None,1])

cost = tf.reduce_mean(tf.square(Y-y))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(cost)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

x_train = np.asarray(np.random.normal(size = (278,5))) # using random values from normal distribution to create some training data
weights = np.random.randint(100,size = (5,1)) #generate weights
a = np.dot(x_train, weights) # matrix multiplication
y_train = a + np.random.normal(size = (278,1))# add some noise to the data

for i in range(10000):
    cost_val, hy_val, _ = sess.run([cost,y,train_step], feed_dict = {X: 
x_train, Y: y_train})

print('w0:%f' % sess.run(w[0]))
print('w1:%f' % sess.run(w[1]))
print('w2:%f' % sess.run(w[2]))
print('w3:%f' % sess.run(w[3]))
print('w4:%f' % sess.run(w[4]))
print('b:%f' % sess.run(b))