首页 > 解决方案 > 在构建 CNN 时出现错误消息“无法将输入数组从形状 (19,761,3) 广播到形状 (19,761,1227,3)”

问题描述

我正在研究一个图像分类问题,我必须处理 19 个通道的输入图像。我成功地使用了普通的 3 通道或灰度图像,但是当我将代码和模型更改为在 19 通道输入上进行训练时出现以下错误。

无法将输入数组从形状 (19,761,3) 广播到形状 (19,761,1227,3)

这是我的代码

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K


# dimensions of our images.
img_width, img_height = 761, 1227

train_data_dir = '/home/spectrograms/train'
validation_data_dir = '/home/spectrograms/test'
nb_train_samples = 814
nb_validation_samples = 134
epochs = 50
batch_size = 32



if K.image_data_format() == 'channels_first':
    input_shape = (19, img_width, img_height)
else:
    input_shape = (img_width, img_height,19)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(19, img_width, img_height), border_mode='same'))
model.add(Activation('relu'))
model.add(Conv2D(32, kernel_size=(3, 3), border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3), border_mode='same'))
model.add(Dropout(0.25))

model.add(Conv2D(64, kernel_size=(3, 3), border_mode='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, kernel_size=(3, 3), border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3), border_mode='same'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(32, activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.summary()

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0,
    zoom_range=0,
    horizontal_flip=False)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(19,img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(19,img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save_weights('/home/rahul/Roshan/CNN/Saved_models_13/custom/CNN_model.h5')

标签: tensorflowkerasdeep-learningneural-networkconv-neural-network

解决方案


推荐阅读