试图在Keras中建立神经网络,但遇到一个问题,我的致密层和激活层之一之间形状不匹配。我是否缺少明显的东西?使用Tensorflow后端

print(x_train.shape)
print(y_train.shape)
(1509, 476, 4)
(1509,)


那么我的模型如下:

###Setup Keras to create a bidirectional convolutional recurrent NN based on DanQ NN
###See https://github.com/uci-cbcl/DanQ
model = Sequential()

model.add(Conv1D(filters=320,
                 kernel_size=26,
                 padding="valid",
                 activation="relu",
                 strides=1,
                 input_shape=(476, 4)
                ))

model.add(MaxPooling1D(pool_size=13, strides=13))

model.add(Dropout(0.2))

model.add(keras.layers.wrappers.Bidirectional(LSTM(320, return_sequences=True, input_shape=(None, 320))))

model.add(Flatten())

model.add(Dense(input_dim=34*640, units=925))
model.add(Activation('relu'))

model.add(Dense(input_dim=925, units=919))
model.add(Activation('sigmoid'))

print('compiling model')
model.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode="binary")

print('running at most 60 epochs')

model.fit(x_train, y_train.T, batch_size=100, epochs=60, shuffle=True, verbose=2, validation_split=0.1)

tresults = model.evaluate(x_test, y_test, verbose=2)

print(tresults)

print(model.output_shape)


但我收到以下错误:

ValueError: Error when checking target: expected activation_48 to have shape (None, 919) but got array with shape (1509, 1)


该错误似乎源于使用S型激活的第二激活层的输入。例如。:

model.add(Dense(input_dim=925, units=919))
model.add(Activation('sigmoid'))


为什么会出现不匹配?

最佳答案

如@ djk47463的注释中所述,您的输出现在每个样本具有919个值,因为这是网络最后一层的单位数。要更正此问题,请将最后一层的单位设置为1,或添加输出尺寸为1的新最终层。

关于python - Keras:密集层和激活层之间的形状不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45109643/

10-12 22:22
查看更多