簡體   English   中英

ValueError: `.fit()` 的輸入應該有 4 級。在 CNN 中有形狀的數組嗎?

[英]ValueError: Input to `.fit()` should have rank 4. Got array with shape in CNN?

我致力於在我的數據集中實現 CNN。

這是我的代碼得到 x 火車和 y 火車與重塑過程

Y_train = train["Label"]
X_train = train.drop(labels = ["Label"],axis = 1) 
X_train.shape -> /*(230, 67500)*/
X_train = np.pad(X_train, ((0,0), (0, (67600-X_train.shape[1]))), 'constant').reshape(-1, 260, 260)
Y_train = to_categorical(Y_train, num_classes = 10)

在我完成一些程序和重塑過程之后,我將 X_train 和 Y_train 分開。 這是下面顯示的代碼。

X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=42)
print("x_train shape",X_train.shape)
print("x_test shape",X_val.shape)
print("y_train shape",Y_train.shape)
print("y_test shape",Y_val.shape)

結果定義如下。

x_train shape (207, 260, 260)
x_test shape (23, 260, 260)
y_train shape (207, 10)
y_test shape (23, 10)

然后我創建 CNN Model。

model = Sequential()

#
model.add(Conv2D(filters = 8, kernel_size = (5,5),padding = 'Same', 
                 activation ='relu', input_shape = (260, 260)))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))

#
model.add(Conv2D(filters = 16, kernel_size = (3,3),padding = 'Same', 
                 activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))

# fully connected
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(10, activation = "softmax"))

然后我使用 ImageGenerator 來使用數據增強

datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # dimesion reduction
        rotation_range=0.5,  # randomly rotate images in the range 5 degrees
        zoom_range = 0.5, # Randomly zoom image 5%
        width_shift_range=0.5,  # randomly shift images horizontally 5%
        height_shift_range=0.5,  # randomly shift images vertically 5%
        horizontal_flip=False,  # randomly flip images
        vertical_flip=False)  # randomly flip images

X_train = np.pad(X_train, ((0,0), (0, (67600-X_train.shape[1]))), 'constant').reshape(-1, 260, 260, 1)

datagen.fit(X_train)

然后它會引發如下所示的錯誤。

ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,2) and requested shape (3,2)

我該如何解決?

我認為問題在於ImageDataGenerator期望圖像具有寬度、高度和顏色通道(最常見的是紅色、綠色和藍色的 3 個通道)。 由於還有一個批量大小,它期望的整體形狀是(batch size, width, height, channels) 您的張量是 260x260,但沒有顏色通道。 它們是灰度圖像嗎?

根據文檔

x:樣本數據。 應該有等級 4。在灰度數據的情況下,通道軸應該有值 1

所以我認為你只需要重塑你的輸入,在最后添加一個額外的維度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM