【发布时间】:2020-08-16 12:40:58
【问题描述】:
我正在使用手写数字的 mnist 数据集,并试图预测我写的数字。问题是我的数字是 (28,28,3) 的形状,而我的神经网络的预期形状是 (28,28,1)。如何转换?
我的代码:
import tensorflow as to
from tensorflow import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import cv2
data = mnist.load_data()
(x_train, y_train), (x_test, y_test) = data
classes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
x_train = x_train / 255
x_test = x_test / 255
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(28,28)))
model.add(keras.layers.Dense(128, activation='relu'))
model.add(keras.layers.Dense(10, activation='softmax'))
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
model.fit(x_train, y_train, epochs=7)
test_loss, test_acc = model.evaluate(x_test, y_test)
print('\nTest Loss:', test_loss)
print('Test accuracy:', test_acc)
img = Image.open("7.jpg").convert('L')
img_array = cv2.imread('7.jpg')
new_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
new_array = cv2.resize(new_array, (28,28))
print(new_array.shape)
print(x_test[0].shape)
plt.imshow(new_array, cmap='gray')
plt.show()
predictions = model.predict(new_array)
plt.grid(False)
plt.imshow(new_array, cmap='gray')
plt.title("Prediction: " + classes[np.argmax(predictions)])
plt.show()
【问题讨论】:
-
您想将色彩空间缩小为黑白?
-
如果您想将颜色深度从 24 位(3 通道)降低到 8 位(1 通道),请使用
cvtColor将图像转换为灰度。如果您想进一步将信息减少到黑白(1 通道)阈值灰度输出。 -
使用 cvtColor 后,它说:预期 flatten_input 有 3 个维度,但得到的数组形状为 (28, 28)
-
如果没有任何代码,很难猜出错误出在哪里。我的猜测是您给
cvtColor提供了一个坏垫子和/或提供了错误的转换代码。 -
刚刚添加了我的代码。感谢您的帮助????????
标签: python numpy opencv machine-learning mnist