In this tutorial, we will disucss and fix the tf.matmul() ValueError: Shape must be rank 2 but is rank 3 for ‘MatMul’ (op: ‘MatMul’) in tensorflow.
Look at code below:
import tensorflow as tf import numpy as np t3 = tf.Variable(np.array([[200, 4, 5], [20, 5, 70],[2, 3, 5], [5, 5, 7]]), dtype = tf.float32) w = tf.Variable(tf.random_uniform([3,3], -0.01, 0.01)) t3 = tf.reshape(t3, [2,2,3]) wx = tf.matmul(t3, w)
Here the shape of \(t3\) is [2, 2, 3], the rank is 3
The shape of \(w\) is [3, 3], the rank is 2.
How about \(wx\)?
We will test this code in different tensorflow.
TensorFlow = 1.10.0
init = tf.global_variables_initializer() init_local = tf.local_variables_initializer() with tf.Session() as sess: sess.run([init, init_local]) print(sess.run([wx]))
Run this code, you will get error.
However, we run this code in tensorflow 1.14.0
TensorFlow = 1.14.0
Run code above, we will get the result:
[[[ 0.371 -1.872 0.757] [-0.379 -0.345 -0.372]] [[-0.046 -0.024 -0.043] [-0.066 -0.052 -0.057]]]
There is no error in tensorflow 1.14.0, which means if you plan to avoid this error, you can update your tensorflow version.
Check your current tensorflow version:
Print TensorFlow Version for Beginners – TensorFlow Tutorial
Update or Install specific tensorflow version:
Conda Install Specific TensorFLow Version: A Completed Guide – TensorFlow Tutorial