Song Wu
Song Wu

Reputation: 31

tensorflow multiple regression error

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))

In this code, Xfortrain is a 278*5 list, and Yfortrain is a 278*1 list. I keep getting the following error:

ValueError: Cannot feed value of shape (278, 5) for Tensor 
'Placeholder_23:0', which has shape '(?, 1)'

I did many researches but couldn't solve the problem. I know it's an architecture error but I don't know what code to solve it. I am new to tensorflow, and I want to use it for solving the multiple regression model. Many thanks in advance!

Upvotes: 0

Views: 62

Answers (1)

Clock Slave
Clock Slave

Reputation: 7967

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))

Upvotes: 1

Related Questions