简体   繁体   English

如何将RNN与CNN结合?

[英]How to combine RNN with CNN?

I'm trying to combine LSTM with CNN but I got stuck because of an error. 我正在尝试将LSTM与CNN结合使用,但由于出错而卡住了。 Here is the model I'm trying to implement: 这是我要实现的模型:

model=Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(28, 28,3), activation='relu'))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(LSTM(128, return_sequences=True,input_shape=(1,32), activation='relu'))
model.add(LSTM(256))
model.add(Dropout(0.25))
model.add(Dense(37))
model.compile(loss='categorical_crossentropy', optimizer='adam')

and error happens in the first LSTM layer: 在第一个LSTM层中发生错误:

ERROR: Input 0 is incompatible with layer lstm_12: expected ndim=3, found ndim=2

The input of LSTM layer should be a 3D array which represents a sequence or a timeseries (this is what the error is trying to say: expected ndim=3 ). LSTM层的输入应该是一个3D数组,该数组代表一个序列或一个时间序列(这就是错误要说的: expected ndim=3 )。 However, in your model the input of LSTM layer, which is actually the output of the Dense layer before it, is a 2D array (ie found ndim=2 ). 但是,在您的模型中,LSTM层的输入(实际上是之前的Dense层的输出)是2D数组(即found ndim=2 )。 To make it into a 3D array of shape (n_samples, n_timesteps, n_features) , one solution is to use a RepeatVector layer to repeat it as much as the number of timesteps (which you need to specify in your code): 要将其制成3D形状的数组(n_samples, n_timesteps, n_features) ,一种解决方案是使用RepeatVector图层将其重复多少步数(您需要在代码中指定):

model.add(Dense(32, activation='relu'))
model.add(RepeatVector(n_timesteps))
model.add(LSTM(128, return_sequences=True, input_shape=(n_timesteps,32), activation='relu'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM