# Matrix multiplication using tensor flow

I am trying to run this code for linear regression using Tensor Flow. I have to use Tensor Flow matrix multiplication, but I am getting errors.

My code:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
tf.set_random_seed(777)
tf.reset_default_graph()

x_train = [1, 2, 3, 4, 5]
y_train = [1.1,2.3, 3.2,4.0,5.4]

X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

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

#hypothesis = tf.linalg.matmul(X,W)+ b
hypothesis = tf.matmul(X,W) + b$$$$

• Are you sure the issue is with multplication? Have you tried to add using tensorflow? tensorflow.org/api_docs/python/tf/math/add Sep 17 at 18:24
• yes, I was getting this error: "Shape must be at least rank 2 but is rank 1 for '{{node MatMul}} = BatchMatMulV2[T=DT_FLOAT, adj_x=false, adj_y=false](Placeholder, weight/read)' with input shapes: ?, [1]." Sep 17 at 19:09

The issue in this problem is here:

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


This is returning one random scalar value. It should be a matrix taking the form:

 W = tf.Variable(tf.random_normal([n,m]), name='weight')


Here n and m are integers. It works even if they are both equal to 1.

tf. matmul is a matrix multiplication, at least one of the args must have a shape of size 2. In your case, this code should work:

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


5 because of the size of x_train. Though it would also be possible to get something like:

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

instead. As the result of the multiplication will be added to b, the output size must be compatible with the size of b.