所以我跟随了 this有关创建顺序神经网络并为其提供 MNIST 数据集以进行预测的视频。
我还有一个 flask 网络服务器,我试图通过它传递从 Canvas 绘图应用程序获得的图像,将其大小调整为 20x20,因为这是 MNIST 图像的尺寸,将其转换为灰度然后使用 numpy 进入一个数组,最后将它提供给我的模型并让它做出预测。然后我会将其传递回网页。
但是我得到了错误:
Error when checking input: expected sequential_1_input to have 3 dimensions, but got array with shape (20, 20)
如何使数组成为 3 维数组?
模型:
model = kr.models.Sequential() # Create a new sequential neural network
model.add(kr.layers.Flatten()) # Input layer
model.add(kr.layers.Dense(128, activation="relu")) # 128 neurons and the 'basic' activation function.
model.add(kr.layers.Dense(128, activation="relu"))
model.add(kr.layers.Dense(10, activation="softmax"))
# Open the image from the request as originalImage
originalImage = Image.open("theImage.png")
# Resize it
resizedImage = ImageOps.fit(originalImage, dim, Image.ANTIALIAS)
# Confirm the dimensions of the resized image
w1, h1 = resizedImage.size
print(w1, h1)
# Save it locally
resizedImage.save("resizedImage.png", quality=100, optimize=True)
# Convert to grayscale and then convert that to an array
grayscaleImage = ImageOps.grayscale(resizedImage)
grayscaleArray = np.array(grayscaleImage)
print(grayscaleArray.reshape(20, 20, 1))
setPrediction = model.predict(grayscaleArray)
getPrediction = np.array(setPrediction[0])
predictedNumber = str(np.argmax(getPrediction))
print(predictedNumber)
最佳答案
问题是 reshape
没有到位。
你应该这样做:
grayscaleArray = grayscaleArray.reshape(20, 20, 1)
关于python - 将数组传递给顺序神经网络模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032694/