【发布时间】: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