简体   繁体   中英

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}}]]

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 .

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