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

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

所以我跟随了 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/

相关文章:

tensorflow - 如何获取tensorflow.data.Dataset的行数、列数/维度数?

machine-learning - 构建神经网络 - 将网络作为参数传递在 keras 中不起作用

python - 如何获得与 Flask 一起使用的 is_safe_url() 函数以及它是如何工作的?

python - 如何使用正确的 'Arguments'调用函数

python - tf.data.Dataset + tf.lookup.index_table_from_file 导致 "Table not initialized"错误

python - Tensorflow 使用 python 在 Windows 中将 .pb 文件转换为 .lite 文件

python - Keras 模型的输出张量必须是 Keras `Layer` 的输出(因此保存过去层元数据)

deep-learning - 在 Keras 层中使用 softmax 激活时如何指定轴?

python - 如何解析 json 以获取数组中特定键的所有值?

python - 关于 tkinter 中绑定(bind)标签的基本查询