Keras:检查CNN模型的输入时出错

时间:2020-05-29 14:43:30

标签: python tensorflow keras deep-learning conv-neural-network

我正在尝试为图像分类创建CNN模型,但是输入形状出现错误,我不明白为什么。请参见下面的代码:

http://localhost:3000

现在是我开始设计CNN模型的时候了:

import pandas as pd
from keras_preprocessing.image import ImageDataGenerator
import numpy as np

#CREATING 3 DATAFRAMES FROM 3 .TXT FILES
trainingfile = pd.read_table('data/training.txt', delim_whitespace=True, names=('class', 'image'))
testingfile = pd.read_table('data/testing.txt', delim_whitespace=True, names=('class', 'image'))
validationfile = pd.read_table('data/validation.txt', delim_whitespace=True, names=('class', 'image'))
# CHANGING TYPE OF TARGET ATTRIBUTE
trainingfile = trainingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
testingfile = testingfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])
validationfile = validationfile.replace([0, 1, 2], ['class0', 'class1', 'class2'])

#DATA AUGMENTATION
datagen=ImageDataGenerator()
train_datagen = ImageDataGenerator( 
    rotation_range=5,
    zoom_range=0.1)

#Generating train, test and validation datasets with RGB, Batch = 32.
train=train_datagen.flow_from_dataframe(dataframe=trainingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
test=datagen.flow_from_dataframe(dataframe=testingfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb',batch_size=32)
#No data augmentation to the validation set
validation=datagen.flow_from_dataframe(dataframe=validationfile, directory="data/", x_col="image", y_col="class", class_mode="categorical", target_size=(256,256),color_mode='rgb', batch_size=32)

如您所见,由于RGB,input_shape为32(批),250 x 250图像大小和3个通道。但是,出现以下错误:

from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Activation, Dropout, MaxPooling2D, BatchNormalization
from keras.constraints import maxnorm

#CNN model
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3), activation='relu', input_shape=(32, 250, 250, 3)))

2 个答案:

答案 0 :(得分:1)

卷积层中的input_shape不应包含批次尺寸。这是excerpt from the Keras documentation

在将[Conv2D]用作模型的第一层时,请提供关键字参数input_shape(整数元组,不包括采样轴),例如input_shape=(128, 128, 3)用于data_format="channels_last"中的128x128 RGB图片。

因此,解决方案是更改模型定义,如下所示。 input_shape中还有另一个错误-应该是256x256x3,而不是250x250x3。

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(256, 256, 3)))

您不需要在模型定义中明确指定批次大小,因为它可以变化。

答案 1 :(得分:1)

问题是Conv2D图层的input_shape,您不必设置批处理大小。将input_shape=(32, 250, 250, 3)更改为input_shape=(250, 250, 3)