简体   繁体   English

层序的输入0与层不兼容

[英]Input 0 of layer sequential is incompatible with the layer

I created a model and then loaded it in another script and try to perform a prediction from it however I can not understand why the shape being passed to the function is incorrect.我创建了一个 model,然后将其加载到另一个脚本中并尝试从中执行预测,但是我不明白为什么传递给 function 的形状不正确。

This is how the model is created:这就是 model 的创建方式:

batch_size = 1232
epochs = 5
IMG_HEIGHT = 400
IMG_WIDTH = 400

model1 = np.load("training_data.npy", allow_pickle=True)
model2 = np.load("training_data_1.npy", allow_pickle=True)

data = np.asarray(np.concatenate((model1, model2), axis=0))  # 1232
train_data = data[:-100]
X_train = np.asarray(np.array([i[0] for i in train_data]))
Y_train = np.asarray([i[1] for i in train_data])

validation_data = data[-100:]

X_val = np.asarray(np.array([i[0] for i in validation_data]))
Y_val = np.asarray([i[1] for i in validation_data])

model = Sequential([
    Conv2D(16, 3, padding='same', activation='relu',
           input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)),
    MaxPooling2D(),
    Conv2D(32, 3, padding='same', activation='relu'),
    MaxPooling2D(),
    Conv2D(64, 3, padding='same', activation='relu'),
    MaxPooling2D(),
    Flatten(),
    Dense(512, activation='relu'),
    Dense(1)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(X_train, Y_train, steps_per_epoch=batch_size, epochs=epochs,
                    validation_data=(X_val, Y_val), validation_steps=batch_size)

model.save("test")

And this is how I'm trying to make a prediction:这就是我试图做出预测的方式:

batch_size = 1232
epochs = 5
IMG_HEIGHT = 400
IMG_WIDTH = 400

model = tf.keras.models.load_model('test')

test_1 = cv2.imread('./Data/Images/test_no.jpg')
test_1 = cv2.resize(test_1, (IMG_HEIGHT, IMG_WIDTH))


prediction = model.predict([test_1])[0]
print(prediction)

When printing the shape of the test image the output is: (400, 400, 3)打印测试图像的形状时,output 为:(400, 400, 3)

I also tried using the numpy operation reshape when passing the test image to predict.我还尝试在通过测试图像进行预测时使用 numpy 操作 reshape 进行预测。 However the error is always:但是错误总是:

ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [None, 400, 3]

Add extra dimension to your input as [n_items,400,400,3]为您的输入添加额外维度 [n_items,400,400,3]

import tensorflow as tf
X_train = tf.expand_dims(X_train, axis =-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM