keras中卷积神经网络的输出形状误差

2024-04-19 20:56:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究一个简单的卷积神经网络模型,但输出似乎与我想要的形状不匹配。你知道吗


from keras.layers import Input, Conv2D, MaxPooling2D, Reshape, Flatten, Dense, Dropout, Activation
from keras.models import Sequential
from keras.layers.convolutional import *
from keras.layers.pooling import *
from keras.optimizers import Adam
from keras.optimizers import rmsprop
from keras.metrics import categorical_crossentropy

model_CL = Sequential([
    Dense(64, activation = 'relu', input_shape = (200, 4, 1)),
    Conv2D(64, kernel_size = (3, 3), activation = 'relu', padding = 'same'),
    MaxPooling2D(pool_size = (2, 2), strides = 2, padding = 'valid'),
    Dropout(rate=0.3),
    Conv2D(64, kernel_size = (5, 5), activation = 'relu', padding = 'same'),
    Flatten(),
    Dense(2, activation = 'softmax')
])




model_CL.compile(loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'], optimizer = 'Adam')
model_CL.summary()


from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint

es_CL = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=5)
mc_CL = ModelCheckpoint('best_model_CL.h5', monitor='val_acc', mode='max', verbose=1, save_best_only=True)

epochs = 50
hist_CL = model_CL.fit(CL_train_input, CL_train_label, validation_data=(CL_validation_input, CL_validation_label), batch_size=32, epochs=epochs, verbose=0, callbacks=[es_CL, mc_CL])

所以我的输入大小似乎不是问题。 我的训练集输入形状是(13630,200,4,1),其中13630是数据数,而我的训练标签如下。(13630, 2) 我所期望的模型输出形状是(2,),但它似乎期望(1,)作为输出大小。你知道吗

所以我的错误是这样的。你知道吗

检查目标时出错:预期密集的\u 28具有形状(1,),但获得了形状为(2,)的数组

仅供参考

型号:“顺序\u 14”


层(类型)输出形状参数#

稠密\u 27(稠密)(无,200,4,64)128


conv2d_27(conv2d)(无,200,4,64)36928


最大池2d\u 14(最大池(None,100,2,64)0


辍学\u 14(辍学)(无、100、2、64)0


conv2d_28(conv2d)(无,100,2,64)102464


展平\u 13(展平)(无,12800)0


稠密\u 28(稠密)(无,2)25602

总参数:165122 可培训参数:165122 不可训练参数:0

这是我的模型的摘要。我不太清楚它为什么期待(1,)。你知道吗


Tags: from模型import参数sizemodelcllayers
1条回答
网友
1楼 · 发布于 2024-04-19 20:56:44

这里的问题是,你把2作为输出,而你在输入层只给出1。 这是你能做的

  • 在输出层中,这个Dense(2, activation = 'softmax')您可以将第一个参数更改为1,这意味着您将为一个二进制问题获取一个输出。就像这样Dense(1, activation = 'softmax')。你知道吗
  • 您可以做的另一件事是,您可以选择一个不同的损失函数,例如binary\u crossentorpy,然后您可以使用keras-utils函数to_categorical()转换标签。 CL_train_labels = to_categorical(CL_train_labels) 我希望这能起作用。你知道吗

相关问题 更多 >