簡體   English   中英

keras.model.predict提高ValueError:檢查輸入時出錯

[英]keras.model.predict raise ValueError: Error when checking input

我在MNIST數據集上訓練了基本的神經網絡模型。 這是培訓的代碼:(省略了導入)

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data(path='mnist.npz')
x_train, x_test = x_train/255.0, x_test/255.0

#1st Define the model
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape = (28,28)),     #input layer
    tf.keras.layers.Dense(512, activation=tf.nn.relu),  #main computation layer
    tf.keras.layers.Dropout(0.2),                       #Dropout layer to avoid overfitting
    tf.keras.layers.Dense(10, activation=tf.nn.softmax) #output layer / Softmax is a classifier AF
])

#2nd Compile the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

#3rd Fit the model
model.fit(x_train, y_train, epochs=5)

#4th Save the model
model.save('models/mnistCNN.h5')

#5th Evaluate the model
model.evaluate(x_test, y_test)

我想看看這個模型是如何工作的,我自己的投入,所以我寫了一個劇本預測與幫助這個職位 我的預測代碼是:(省略了導入)

model = load_model('models/mnistCNN.h5')

for i in range(3):
    img = Image.open(str(i+1) + '.png').convert("L")
    img = img.resize((28,28))
    im2arr = np.array(img)
    im2arr = im2arr/255
    im2arr = im2arr.reshape(1, 28, 28, 1)
    y_pred = model.predict(im2arr)
    print('For Image',i+1,'Prediction = ',y_pred)

首先,我不明白這行的目的:

im2arr = im2arr.reshape(1, 28, 28, 1)

如果有人可以闡明為什么需要這條線,那將有很大幫助。

第二,此行將引發以下錯誤:

ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (1, 28, 28, 1)

我在這里想念什么?

第一維用於批次大小。 它是由keras.model內部添加的。 因此,此行僅將其添加到圖像數組。

im2arr = im2arr.reshape(1, 28, 28, 1)

您得到的錯誤是因為用於訓練的mnist dataset的一個示例具有形狀(28,28),因此它是輸入層。 要消除此錯誤,您需要將此行更改為

im2arr = img.reshape((1, 28, 28))

暫無
暫無

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

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