1
$\begingroup$

I was writing a code for linear regression using tensor flow but I was getting errors while calculating matrix multiplication using tensor flow and while calculating accuracy.

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

tf.set_random_seed(777)  

x_train = [1, 2, 3, 4, 5]
y_train = [2,3,4,5,6]


X = tf.placeholder(tf.float32, shape=[None, 1])
Y = tf.placeholder(tf.float32, shape=[None, 1])

W = tf.Variable(tf.random_normal([1,1]), name='weight')
b = tf.Variable(tf.random_normal([1]), name='bias')


hypothesis = tf.sigmoid(tf.matmul(X, W) + b)


cost = tf.reduce_mean(tf.square(hypothesis - Y))


optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train = optimizer.minimize(cost)


# Accuracy computation
#predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
accuracy = tf.reduce_mean(tf.cast(tf.equal(hypothesis, Y), dtype=tf.float32))
# Launch the graph in a session.
sess = tf.Session()

sess.run(tf.global_variables_initializer())


for step in range(3001):
    sess.run(train,feed_dict = {X:x_train,Y:y_train})
    if step % 100 == 0:
        print(step, sess.run(cost,feed_dict = {X:x_train,Y:y_train}), sess.run(W), sess.run(b),sess.run(accuracy))

the error was

 for step in range(3001):
---> 38     sess.run(train,feed_dict = {X:x_train,Y:y_train})
     39     if step % 100 == 0:
     40         print(step, sess.run(cost,feed_dict = {X:x_train,Y:y_train}), sess.run(W), sess.run(b),sess.run(accuracy))

~\anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    965 
    966     try:
--> 967       result = self._run(None, fetches, feed_dict, options_ptr,
    968                          run_metadata_ptr)
    969       if run_metadata:

~\anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1162           if (not is_tensor_handle_feed and
   1163               not subfeed_t.get_shape().is_compatible_with(np_val.shape)):
-> 1164             raise ValueError(
   1165                 'Cannot feed value of shape %r for Tensor %r, '
   1166                 'which has shape %r' %

ValueError: Cannot feed value of shape (5,) for Tensor 'Placeholder_14:0', which has shape '(?, 1)'
```
$\endgroup$