簡體   English   中英

為什么 keras 神經網絡對所有不同的圖像預測相同的數字?

[英]Why does keras neural network predicts the same number for all different images?

我正在嘗試使用 tensorflow 的 keras 神經網絡來識別手寫數字。 但是我知道為什么當我調用predict()時,它會為所有輸入圖像返回相同的結果。

這是代碼:

  ### Train dataset ###
  mnist = tf.keras.datasets.mnist
  (x_train, y_train), (x_test, y_test) = mnist.load_data()
  x_train = x_train/255
  x_test = x_test/255

  model = tf.keras.models.Sequential()
  model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
  model.add(tf.keras.layers.Dense(units=128,activation=tf.nn.relu))
  model.add(tf.keras.layers.Dense(units=10,activation=tf.nn.softmax))

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

  model.fit(x_train, y_train, epochs=5)

結果如下所示:

Epoch 1/5
1875/1875 [==============================] - 2s 672us/step - loss: 0.2620 - accuracy: 0.9248
Epoch 2/5
1875/1875 [==============================] - 1s 567us/step - loss: 0.1148 - accuracy: 0.9658
Epoch 3/5
1875/1875 [==============================] - 1s 559us/step - loss: 0.0784 - accuracy: 0.9764
Epoch 4/5
1875/1875 [==============================] - 1s 564us/step - loss: 0.0596 - accuracy: 0.9817
Epoch 5/5
1875/1875 [==============================] - 1s 567us/step - loss: 0.0462 - accuracy: 0.9859

然后使用圖像進行測試的代碼如下:

  img = cv.imread('path/to/1.png')
  img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  img = cv.resize(img,(28,28))
  img = np.array([img])
    
  if cv.countNonZero((255-image)) == 0:
     print('')
  img = np.invert(img)
    
  plt.imshow(img[0])
  plt.show()
    
  prediction = model.predict(img)
  result = np.argmax(prediction)
  print(prediction)
  print(f'Result: {result}')

結果是:

輸入數字 1

plt顯示: PLT 顯示 1

[[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]]
Result: 3

輸入數字 2

顯示PLT 顯示 2

[[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]]
Result: 3

與您在訓練集上所做的一樣,在推理時間內標准化您的數據

img = np.array([img]) / 255

檢查此答案(推理)以獲取更多詳細信息。


根據您的第三條評論,這里有一些細節。

def input_prepare(img):            
    img = cv2.resize(img, (28, 28))   
    img = cv2.bitwise_not(img)   

    img = tf.cast(tf.divide(img, 255) , tf.float64)              
    img = tf.expand_dims(img, axis=0)   
    return img 

img = cv2.imread('/content/1.png')
orig = img.copy() # save for plotting later on 

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scaling 
img = input_prepare(img)

plt.imshow(tf.reshape(img, shape=[28, 28]))

在此處輸入圖像描述

plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))
plt.title(np.argmax(model.predict(img)))
plt.show()

在此處輸入圖像描述

它按預期工作。 但是由於調整圖像大小,數字會損壞並丟失其空間信息。 對於 model 來說這似乎沒問題,但如果情況變得更糟,那么 model 將預測錯誤。 一個案例

在此處輸入圖像描述

model 對此預測錯誤。

plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))
plt.title(np.argmax(model.predict(img)))
plt.show()

在此處輸入圖像描述

為了解決這個問題,我們可以應用cv2.erode在調整大小后添加一些像素,例如

def input_prepare(img):            
    img = cv2.resize(img, (28, 28))   
    img = cv2.erode(img, np.ones((2, 2)))
    img = cv2.bitwise_not(img)   

    img = tf.cast(tf.divide(img, 255) , tf.float64)              
    img = tf.expand_dims(img, axis=0)   
    return img 

在此處輸入圖像描述

也許不是最好的方法,但現在 model 會更好地理解。

plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))
plt.title(np.argmax(model.predict(img)))
plt.show()

在此處輸入圖像描述

暫無
暫無

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

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