Chris Yuh
Chris Yuh

Reputation: 77

Tensorflow InvalidArgumentError Matrix size incompatible

When I start the simple neural net I got an error. By the way, the code should output the first number of the test array.

There have been other errors(there was one having to do with the data's dtype).

import tensorflow as tf
import numpy as np
from tensorflow import keras

data = np.array([[0, 1, 1], [0, 0, 1], [1, 1, 1]])
labels = np.array([0, 0, 1])
data.dtype = float
print(data.dtype)
model = keras.Sequential([
keras.layers.Dense(3, activation=tf.nn.relu),
keras.layers.Dense(2, activation=tf.nn.softmax)])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels)
prediction = model.predict([0, 1, 0])
print(prediction)

I get this error:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [3,1], In[1]: [3,3]
     [[{{node sequential/dense/Relu}}]]

Upvotes: 1

Views: 3514

Answers (1)

Anubhav Singh
Anubhav Singh

Reputation: 8699

You are getting above error because of below line:

prediction = model.predict([0, 1, 0])

You are passing a list which should be a numpy array and of shape Nx3, where N is basically batch size and can be 1, 2, etc. In this case, it will be 1.

In order to make it correct, change it to

prediction = model.predict(np.expand_dims(np.array([0, 1, 0], dtype=np.float32), 0))

or

prediction = model.predict(np.array([[0, 1, 0]], dtype=np.float32))

And, change data.dtype = float to data.dtype = np.float32.

Upvotes: 1

Related Questions