我在本地图像上使用 model.predict() 时遇到此错误。它接受了形状 (224,224,3) 的训练,我将输入图像的大小调整为 (224,224,3) 仍然显示错误。测试阵列中具有相同形状的图像被预测没有任何问题。我是新手,有人能告诉我错误吗。
#imports
data_dir = "/content/gdrive/MyDrive/mask_detector"
import pathlib
data_dir = pathlib.Path(data_dir)
mask_data_dict = {'mask' : list(data_dir.glob('Mask/*')),'non_mask' : list(data_dir.glob('Non_Mask/*'))}
mask_labels_dict = {'mask' : 0,'non_mask' : 1}
X,y = [], []
for mask_name,images in mask_data_dict.items():
for image in images:
img_array = cv2.imread(str(image))
img_array_resized = cv2.resize(img_array,(224,224))
X.append(img_array_resized)
y.append(mask_labels_dict[mask_name])
X = np.array(X)
y = np.array(y)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state= 0)
X_test_scaled = X_test/255
X_train_scaled = X_train/255
X_test = X_test.astype('float32')
X_train = X_train.astype('float32')
y_train_categorical = keras.utils.to_categorical(y_train, num_classes = 2, dtype = 'float32')
y_test_categorical = keras.utils.to_categorical(y_test, num_classes = 2, dtype = 'float32')
model = keras.Sequential([
keras.layers.Conv2D(16,(3,3), padding='same',activation = 'relu',input_shape=(224,224,3)),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(32,(3,3), padding='same',activation = 'relu'),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(64,(3,3), padding='same',activation = 'relu'),
keras.layers.Flatten(),
keras.layers.Dense(128, activation = 'relu'),
keras.layers.Dense(2, activation = 'sigmoid')])
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
model.fit(X_train_scaled, y_train_categorical, epochs = 5)
def prediction(image):
pred_array = cv2.imread(image)
pred_array = np.array(pred_array)
pred_array_resized = cv2.resize(pred_array,(224,224,))
pred_array_scaled = np.array(pred_array_resized)/255
model.predict(pred_array_scaled)
prediction("example.jpeg") #shape
#ValueError: Input 0 of layer sequential_4 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (32, 224, 3)
classes = ["mask","non-mask"]
cv2_imshow(X_test[9])
classes[np.argmax(model.predict(X_test_scaled)[9])] #this works fine
答案 0 :(得分:1)
模型需要 4-dim 数组,因此在预测之前,添加此行以将 dim 扩展为 NHWC 之类。
pred_array_scaled = np.expand_dims(pred_array_scaled, axis=0)