我用 MNIST 資料集訓練了一個密集神經網路,以便對 28x28 的數字影像進行分類。現在我試圖讓它與我自己的樣本一起作業(我在油漆中繪制了“7”的影像并將其轉換為陣列)但結果非常糟糕。
from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
from tensorflow.keras import models
from tensorflow.keras import layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10, activation='softmax'))
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype('float32') / 255
from tensorflow.keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images,train_labels,epochs=20,batch_size=512,validation_split=0.2)
print(network.evaluate(test_images,test_labels))
#-DEMO-----------------------------------------------------------------
from PIL import Image
import PIL.ImageOps
import os
direccio = 'C:/Users/marcc/OneDrive/Escritorio'
os.chdir(direccio)
myImage = Image.open("Image.PNG").convert('L')
myImage = PIL.ImageOps.invert(myImage)
myImage = myImage.resize((28,28))
myImage.show()
#transforming my image into an array (THE PROBLEM MUST BE HERE)
import numpy as np
myImage_array = np.array(myImage)
myImage_array = myImage_array.reshape((28*28))
myImage_array = myImage_array.astype('float32') / 255
myImage_array=myImage_array.reshape(1,784)
print(myImage_array.shape)
print(network.predict(myImage_array))
DEMO 之前的代碼由 Fran?ois Chollet 制作。我只做了最后一部分是我自己的形象的實作。
我用七的影像測驗后得到的結果是:
[[6.9165975e-03 3.0256975e-03 4.9591944e-01 4.8350231e-03 5.6093242e-03
8.6059235e-03 4.5295963e-01 8.3720963e-04 2.1008164e-02 2.8301307e-04]]
如您所見,結果非常糟糕(第七個位置的概率應該最高)
如果我使用代碼繪制 MNIST 的影像:
digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)
plt.show()
它看起來像: 一個 9 的 MNIST 影像
如果我對我的影像做同樣的事情: 我的 7 影像(轉換為陣列后)
uj5u.com熱心網友回復:
您得到的結果是您的樣本屬于每個類別的概率分布。如果你看到結果
[[6.9165975e-03 3.0256975e-03 4.9591944e-01 4.8350231e-03 5.6093242e-03
8.6059235e-03 4.5295963e-01 8.3720963e-04 2.1008164e-02 2.8301307e-04]]
你看到你的樣本有 10 個概率屬于第二類(沒有 2)等的第一類(沒有 1)等等
如果您仔細查看您的輸出,您會發現最高的概率位于第 7 位,因此模型將您的樣本分類為數字 7
如果你希望你的輸出是班級的數量,你可以嘗試這樣的事情
CATEGORIES = ["1","2","3","4","5","6","7","8","9","0"]
prediction = model.predict('your_sample')
max = (prediction.max(0))
result = (np.where(prediction == max))
print(CATEGORIES[result])
uj5u.com熱心網友回復:
一切正常,我遇到的問題是,在我的區域 7 通常使用另一行書寫(我真的認為它更擴展)。因為我使用的是密集網路,它不會解釋數字的形狀,而是解釋像素的配置,所以在這個簡單的模型中對數字的書寫方式稍作修改可能會產生非常糟糕的后果。
7 正常書寫
正如 Αpostolos-Valiakos 所說,我真的不得不嘗試不同的數字。但我真的認為這是我的影像如何轉換為陣列的問題。感謝大家的幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/324600.html
