[英]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)
I am getting this error on using model.predict() on local images.在本地图像上使用 model.predict() 时出现此错误。 It is trained on shape (224,224,3) and I've resized the input image to (224,224,3) still it shows error.
它在形状 (224,224,3) 上进行了训练,我已将输入图像的大小调整为 (224,224,3) 仍然显示错误。 The images with same sshape in test array are getting predicted without any issues.
测试数组中具有相同 sshape 的图像可以毫无问题地得到预测。 I am new to this, can someone please tell the mistake.
我是新手,有人可以告诉错误。
#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
Model needs 4-dim array, so before predicting, add this line to expand dim to NHWC like. Model 需要 4-dim 数组,所以在预测之前,添加这条线来扩展 dim 到 NHWC 之类的。
pred_array_scaled = np.expand_dims(pred_array_scaled, axis=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.