【发布时间】:2021-12-06 02:01:40
【问题描述】:
我使用 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()
看起来像: MNIST image of a 9
如果我对我的图像做同样的事情: My Image of a 7 (after being transformed to an array)
【问题讨论】:
-
这是从 Github 仓库中获取的吗?
-
No 第一部分取自 François Chollet 的 Python 深度学习一书。我把它放在这里是因为我认为比较他实现图像的方式和我的方式很有趣。
-
这样的问题很难调试,但希望您能在datascience.stackexchange.com 上找到比这里更多的帮助。
-
我不得不说我绘制了他的数据集的图像,并在矢量化后绘制了我的图像,两者看起来都一样。所以我不明白为什么它不起作用。
-
@Luke 谢谢!我不知道它存在
标签: python numpy tensorflow keras deep-learning