繁体   English   中英

Keras:检查cnn model的输入时出错

[英]Keras: Error when checking input of cnn model

我正在尝试创建一个用于图像分类的 CNN model,但是,输入形状出现错误,我不明白为什么。 请看下面的代码:

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)

现在是我开始设计 CNN model 的时候:

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

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

ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5

卷积层中的input_shape不应包含批量维度。 是 Keras 文档的摘录

当使用 [Conv2D] 作为 model 中的第一层时,提供关键字参数input_shape (整数元组,不包括样本轴),例如input_shape=(128, 128, 3)用于data_format="channels_last"中的 128x128 RGB 图片data_format="channels_last"

因此,解决方案是更改您的 model 定义,如下所示。 您在input_shape中出现了另一个错误——它应该是 256x256x3,而不是 250x250x3。

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

您不需要在 model 定义中明确指定批量大小,因为它可能会有所不同。

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

暂无
暂无

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

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