我有一个包含大约 14560 个维度为 400 的字向量的数据框。我已将每个向量 reshape 为 20*20 并使用 1 个 channel 来应用 CNN,因此维度已变为 (14560,20,20,1)
。当我尝试拟合 CNN 模型时,它会抛出错误。
代码:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers import BatchNormalization
from keras.utils import np_utils
from keras import backend as K
model_cnn=Sequential()
model_cnn.add(Convolution2D(filters = 16, kernel_size = (3, 3),
activation='relu',input_shape = (20, 20,1)))
model_cnn.compile(loss='categorical_crossentropy', optimizer = 'adadelta',
metrics=["accuracy"])
model_cnn.fit(x_tr_,y_tr_,validation_data=(x_te_,y_te))
错误:
Error when checking target: expected conv2d_6 to have 4 dimensions, but got array with shape (14560, 1). When I reshape train data to (14560,1,20,20) still it gives error as model receives input =(1,20,20) and required is (20,20,1).
我该如何修复它?
最佳答案
问题
问题不仅仅在于 x_tr
形状,正如另一个答案中正确指出的那样,它应该是 (-1,20,20,1)
。这也是网络架构本身。如果您执行model_cnn.summary()
,您将看到以下内容:
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 18, 18, 16) 160
=================================================================
Total params: 160
Trainable params: 160
Non-trainable params: 0
模型的输出排名为 4:(batch_size, 18, 18, 16)
。当标签为 (batch_size, 1)
时,它无法计算损失。
解决方案
正确的架构必须将卷积输出张量 (batch_size, 18, 18, 16)
reshape 为 (batch_size, 1)
。有很多方法可以做到这一点,这里是一种:
model_cnn = Sequential()
model_cnn.add(Convolution2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=(20, 20, 1)))
model_cnn.add(MaxPool2D(pool_size=18))
model_cnn.add(Flatten())
model_cnn.add(Dense(units=1))
model_cnn.compile(loss='sparse_categorical_crossentropy', optimizer='adadelta', metrics=["accuracy"])
总结:
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 18, 18, 16) 160
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 1, 1, 16) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 16) 0
_________________________________________________________________
dense_1 (Dense) (None, 1) 17
=================================================================
Total params: 177
Trainable params: 177
Non-trainable params: 0
请注意,我添加了最大池化以将 18x18
特征映射减少为 1x1
,然后展平图层以将张量压缩为 (无,16)
最后是密集层输出单个值。另请注意损失函数:它是 sparse_categorical_crossentropy
。如果您希望进行分类交叉熵,则必须进行 one-hot 编码,并且输出的不是单个数字,而是类别上的概率分布:(无,类)
。
顺便说一句,还要检查您的验证数组是否具有有效的形状。
关于machine-learning - 词向量上的 CNN 会引发输入维度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49835610/