将数组传递给顺序神经网络模型

时间:2019-11-25 13:13:52

标签: python tensorflow keras neural-network python-imaging-library

因此,我跟随this视频一起创建了顺序神经网络,并为其提供了MNIST数据集以进行预测。

我也有一个Flask Web服务器,我正尝试通过它传递从画布绘制应用程序获得的图像,将其调整为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)

1 个答案:

答案 0 :(得分:3)

问题是reshape不到位。 您应该这样做:

grayscaleArray = grayscaleArray.reshape(20, 20, 1)