簡體   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