簡體   English   中英

如何解決此錯誤:矩陣大小不兼容:在[0]:[1,786432],在[1]中:[784,512] [[{{node MatMul}}]]>

[英]How to solve this error: Matrix size-incompatible: In[0]: [1,786432], In[1]: [784,512] [[{{node MatMul}}]]>

我需要為我的學校項目做這個簡單的機器學習代碼,但經過多次改動后我不斷得到無效數組的這個錯誤。 有人可以幫忙嗎? 我現在非常絕望,因為我的提交日期已接近......

這是我的代碼:

import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([

  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

model.fit(x_train, y_train, epochs=1)
model.evaluate(x_test, y_test)
# Part 3 - Making new predictions
import numpy as np
from keras.preprocessing import image
import keras
test_image = image.load_img('Number 8.jpg')
test_image = image.img_to_array(test_image, data_format='channels_first', 
dtype='float32')
test_image = np.expand_dims(test_image, axis=0)
result = model.predict(test_image)
print(np.argmax(result[0]))

正如tomkot已經指出的那樣,它的形狀問題。

MNIST的形狀有[60000,28,28],這也是你訓練模型的形狀。

我用自己的圖片進行了測試,傳遞給預測的形狀是[1,3,1728,2304]。 這可能與您的'Number 8.jpg'大小不同,但正如您所看到的,每張圖片都會以錯誤的形狀發送。

當您將圖片帶入訓練模型的形狀時,您的預測應該可以正常工作。

重塑的一種方法

# load your image
test_image = test_image.resize((28, 28), resample=Image.BICUBIC))
#resize your image
test_image = test_image.resize((28,28), resample=Image.BICUBIC)
#on the prediction call reshape
result = model.predict(test_image.reshape(-1,28,28))

'-1'是另一種表示數組包含多少數據的形式。 你也可以像'.reshape(1,28,28)'那樣寫它。 '-1'只是將它留給python本身來找出正確的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM