检查输入时的Keras值错误:预期density_27_input具有5个维度,但数组的形状为(32,150,150,3)

时间:2018-12-17 00:32:45

标签: python machine-learning keras neural-network classification

我最近开始进行机器学习,并开始构建二进制分类模型。但是,我在运行代码时遇到错误:

import numpy as np
import keras
import matplotlib.pyplot as plt
import cv2
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.layers import Input, Dense
base_dir = ("/content/drive/apagdata")
train_dir = os.path.join(base_dir,"train")
test_dir = os.path.join(base_dir,"test")
# This returns a tensor
inputs = Input(shape=(784,))

# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)

# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
          loss='binary_crossentropy',
          metrics=['accuracy'])
train_datagen = ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
    "/content/drive/apagdata/train",
    target_size=(150,150),
    batch_size=32,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    "/content/drive/apagdata/test",
    target_size=(150,150),
    batch_size=32,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=2000,
    epochs=50,
    validation_data=validation_generator,
    validation_steps=800)
model.save_weights('first_try.h5')

我收到以下错误:

ValueError: Error when checking input: expected input_3 to have 2 dimensions, but got an array with shape (32, 150, 150, 3)

1 个答案:

答案 0 :(得分:0)

您的模型输入似乎是形状为(150, 150, 3)的图像(因为您在图像生成器中指定了target_size=(150,150))。因此,模型的输入形状必须相同:

inputs = Input(shape=(150, 150, 3))

由于您可能仅在模型中使用Dense层,因此您需要在输入层之后立即添加Flatten层以展平图像:

x = Flatten()(inputs)

不要忘记将x传递到下一个Dense层。

此外,请注意,您提到您正在构建二进制分类器,并且已在图像生成器中正确设置了class_mode='binary';但是,模型中的最后一层必须是S型分类器,而不是softmax分类器:

predictions = Dense(1, activation='sigmoid')(x)