我正在通过卷积神经网络(CNN)研究基于2D RGB像素的图像分类问题 . 我将充分描述我的问题,并提供尽可能多的细节 .
我将我的培训和验证分成如下:
x_trn, x_val, y_trn, y_val = train_test_split(img, msk,test_size=0.2, random_state=42)
其中 img
是 (number_of_image_patches x image_rows x image_columns x number_of_image_channels
的数组 . 所以我在每个 128x128
有200个RGB(即3个通道)图像补丁 . 因此, img
数组是 (200 x 128 x 128 x 3)
.
此外, msk
是一个数组,其中包含将用于训练CNN的每个图像补丁的类标签,其大小为 (200 x 128 x 128)
. 每个 msk
补丁都是带有类标签的 128x128
数组 . 在我的问题中,我有 7 classes
.
由于我的问题是多类分类,我使用 categorical_crossentropy
作为我的损失函数 . 并且 softmax
作为输出结果的激活功能 . 我的完整CNN模型可以找到here .
y_trn
的形状是 (160 x 128 x 128)
, y_val
是 (40 x 128 x 128)
.
现在, categorical_crossentropy
要求 y_trn
和 y_val
变量进行单热编码 . 我这样做如下:
from keras.utils import to_categorical
y_trn= to_categorical(y_trn, num_classes=len(np.unique(y_trn)))
y_val= to_categorical(y_val, num_classes=len(np.unique(y_val)))
应用单热编码后 y_trn
的新形状是 (2621440 x 7)
,因为我有 7 classes
. 2621440
来自 160x128x128
的倍增
之后,我会做以下培训/适合CNN模型:
model = my_CNN_unet()
model_checkpoint = ModelCheckpoint('unet6_test_{epoch:02d}.hdf5')
model.fit(x_trn, y_trn, batch_size=50, epochs=3, verbose=1, shuffle=True,
callbacks=[model_checkpoint], validation_data=(x_val, y_val))
但是我收到以下错误:
ValueError: Error when checking target: expected conv2d_138 to have 4 dimensions, but got array with shape (2621440 , 7)
这意味着我的单热编码显然没有正确应用,因为它期望单热阵列为4D . 我假设 y_trn
的正确大小应该是: (160 x 128 x 128 x 7)
.
我是Python和Keras的新手,不知道如何克服这个错误 . 任何见解都是受欢迎的 .