简体   繁体   中英

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

The shape of constant x is (2,) , ie 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.

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.

The shape of x is (2,) does not match the shape (2,3) of w1 .

You should change

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

to

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

now the shape of x is (1,2) and works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM