'TensorFlow official documentation tutorial error ''numpy.ndarray' object has no attribute 'get_shape'

I was trying to run the exact code on the TensorFlow tutorial here.

When I get to line:

predictions = model(x_train[:1]).numpy()

I get the error:

'numpy.ndarray' object has no attribute 'get_shape'

I saw here that someone had a similar issue, so I changed the line to:

predictions = model(tf.convert_to_tensor(x_train[:1])).numpy()

And I get the error:

Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'

Could someone tell me the correct code that should be in the tutorial? Or is it an issue on my side?

One thing that is strange is it runs if I run the code in the colab notebook provided, but if I download the jupyter notebook to run locally, that's when I get the error. So I'm wondering if I have a different/wrong version of TensorFlow?

My packages:

tensorflow                1.13.1            
tensorflow-base           1.13.1            
tensorflow-estimator      1.13.0                       
python                    3.7.6                 


Solution 1:[1]

The tutorial you are referencing is in Tensorflow 2.x (where Eager mode is by default). In Eager mode you can access a tensor with .numpy() method to get numpy value of the tensor.

In your local, you have TensorFlow 1.13.1 which runs the model in graph mode. You can access the numpy value of the graph tensor (not eager tensor) by running a session and evaluating the tensor. Here is one tutorial on TF1.x with mnist data. Overall, in TF1.x, you need to create a graph, create placeholders, then run a Session, feed the data to placeholders, and train the model, then predict.

Other alternative is to install Tensorflow 2.x by running "pip3 install tensorflow==2.1`. After installing, you can run the example without any issue.

Solution 2:[2]

The reason of your first question is that your model() accept tensor type parameters not numpy. And model(x) called x.get_shape().
In x.get_shape(), x must be tensor. So, your need transform numpy to tensor. You can use tf.convert_to_tensor(x) or tf.constant(x)


The second error message is Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'. The message means that in a x b a type is float64 and b type is float32. They are different type variables, so they can't be multiplied. You can try use tf.cast(a,tf.float32) to change the type of a or change b. But in your code, you should use x_train[:1].dtype to check the type of x_train[:1]. If it is float32 you can try use x_train[:1].astype(np.float64) to transform it or vice versa. Or use tf.constant(x_train[:1],dtype=tf.float64)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2