【问题标题】:how to reshape input image array from 1d to 3d如何将输入图像数组从 1d 重塑为 3d
【发布时间】:2020-05-04 17:54:59
【问题描述】:

我已经构建了如下的图像分类器:

import tensorflow as tf
from tensorflow.keras.applications.mobilenet import preprocess_input

image_width, image_height = 224, 224
input_shape = (image_width, image_height, 3)
self.model = tf.keras.Sequential()
        pretrained_layer = tf.keras.applications.mobilenet.MobileNet(
            weights="imagenet", include_top=False, input_shape=self.input_shape
        )
self.model.add(pretrained_layer)
self.model.add(tf.keras.layers.GlobalAveragePooling2D())
self.model.add(tf.keras.layers.Dense(256, activation="relu"))
self.model.add(tf.keras.layers.Dropout(0.5))
self.model.add(tf.keras.layers.Dense(128, activation="relu"))
self.model.add(tf.keras.layers.Dropout(0.2))
self.model.add(tf.keras.layers.Dense(len(DATA_LABELS), activation="sigmoid"))

self.model.compile(
            optimizer=tf.keras.optimizers.Adam(0.0005),
            loss="binary_crossentropy",
            metrics=["accuracy"],
        )

我还有一个预测函数,期望输入为 numpy 数组

def predict(self, image):
    """Predict the labels for a single screenshot
       image -- The numpy array of the image to classify
    """
    img = np.expand_dims(image, axis=0)
    img = preprocess_input(img)

    prediction = self.model.predict(img, batch_size=1)

现在我得到一个 1d numpy 数组 (23280,) 的图像,当我将它提供给预测模型时,我得到如下错误:

prediction = model.predict(np.asarray(bytearray(ss_read)))  # np.asarray(bytearray(ss_read)) is 1d numpy array (23280,)
ValueError: Error when checking input: expected mobilenet_1.00_224_input to have 4 dimensions, but got array with shape (1, 23280)

那么,我怎样才能重塑这个 numpy 数组并使其为预测器做好准备?我想我可以做类似np.reshape(np.asarray(bytearray(ss_read)), (image_width, image_height, 3)) 的事情,但是在这种情况下,reshape 后的数据总量并不完全相同(224 * 224 * 3 = 150528 > 23280)。我应该这样做而不是np.reshape(np.asarray(bytearray(ss_read)), (image_width, -1, 3))吗?

【问题讨论】:

  • 是 (23280,) 图像吗?太小了,不能用手机网

标签: python numpy tensorflow keras neural-network


【解决方案1】:

假设你的图像是 3D 的,你会得到 width * height = 23280/3 = 7760

因此,您只有一些宽度-高度对的可能性,即:

[(95, 82), (190, 41), (205, 38), (410, 19), (779, 10), (1558, 5), (3895, 2)]
[(82, 95), (41, 190), (38, 205), (19, 410), (10, 779), (5, 1558), (2, 3895)]

都不是224 x 224

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2017-10-15
    • 2020-04-22
    • 1970-01-01
    • 2017-12-03
    • 2018-03-18
    • 2021-10-28
    • 2020-08-17
    • 2017-06-17
    相关资源
    最近更新 更多