Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [2], [2,3]

I'm so news to Tensorflow . I already search for same questions,but i can't understand. there is the code .Hope you can help me.

Code:

import tensorflow as tf

w1 = tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2 = tf.Variable(tf.random_normal([3,3],stddev=1,seed=1))

x = tf.constant([0.7,0.9])

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

sess = tf.Session()

sess.run(w1.initializer)
sess.run(w2.initializer)

print(sess.run(y))
sess.close()
like image 647
馮推宇 Avatar asked May 02 '18 08:05

馮推宇


2 Answers

The shape of constant x is (2,), i.e. a one-dimensional array, and you are trying to multiply it with a two-dimensional array w1 of shape (2, 3), which is not possible for matrix multiplication, as number of columns of first parameter must be equal to number of rows in second parameter. Also, I think tf.matmul only works if both arrays are two-dimensional.

One of the many ways you can change your declaration of x as

x = tf.constant([[0.7], [0.9]])

This will create a two-dimensional constant tensor of shape (2, 1). And, then multiply it as,

a = tf.matmul(tf.transpose(x), w1)

tf.transpose() is used to create transpose of array x with shape (2, 1) to shape (1, 2).

Hope this helps.

like image 119
Ankit Paliwal Avatar answered Nov 08 '22 18:11

Ankit Paliwal


In your case, the rank of variable x is 1. Hence the issue.

Following is the reason you are having this issue.

Please refer the tensorflow API https://www.tensorflow.org/api_docs/python/tf/matmul

tf.matmul(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None)

Args:

a: Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.

b: Tensor with same type and rank as a.

like image 3
solver149 Avatar answered Nov 08 '22 19:11

solver149