【问题标题】:Input 0 of layer sequential is incompatible with the layer层序的输入0与层不兼容
【发布时间】:2020-11-14 01:58:58
【问题描述】:

我创建了一个模型,然后将其加载到另一个脚本中并尝试从中执行预测,但是我不明白为什么传递给函数的形状不正确。

这就是模型的创建方式:

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")

这就是我试图做出预测的方式:

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)

打印测试图像的形状时,输出为:(400, 400, 3)

通过测试图像进​​行预测时,我还尝试使用 numpy 操作 reshape。但是错误总是:

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

【问题讨论】:

    标签: python numpy tensorflow machine-learning keras


    【解决方案1】:

    为您的输入添加额外维度 [n_items,400,400,3]

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 2021-07-04
      • 2021-05-31
      • 2022-06-21
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多