Is there a way to fix the dense layer shape when adding conv2d layer with lstm?

安稳与你 提交于 2019-12-08 05:09:47

问题


I am trying to fit my data into a conv2d+lstm layers but I got an error in the last dense layer

i already tried to reshape but it gives me the same error .. and because I am new in python I couldn't understand how to fix my error My model is about combining cnn with lstm layer and i have 2892 training images and 1896 testing images with total 4788 images each image with size 128*128

And here is the final model summary

Here some of my code

cnn_model = Sequential()

cnn_model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128,128,3)))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))

cnn_model.add(Conv2D(32, (3, 3), activation='relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))

cnn_model.add(Conv2D(64, (3, 3), activation='relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))

cnn_model.add(Conv2D(128, (3, 3), activation='relu'))
cnn_model.add(MaxPooling2D(pool_size=(2, 2)))
cnn_model.add(Flatten())

model = Sequential()
model.add(cnn_model)
model.add(Reshape((4608, 1)))
model.add(LSTM(16, return_sequences=True, dropout=0.5))
model.add(Dense(3, activation='softmax'))
model.compile(optimizer='adadelta', loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
X_data = np.array(X_data)
X_datatest = np.array(X_datatest)
X_data= X_data.astype('float32') / 255.
X_datatest = X_datatest.astype('float32') / 255.

hist=model.fit(X_data, X_data,epochs=15,batch_size=128,verbose = 2,validation_data=(X_datatest, X_datatest))

The error I expected to be in the dense layer as its outputs the following error

Traceback (most recent call last): File "C:\Users\bdyssm\Desktop\Master\LSTMCNN2.py", line 212, in hist=model.fit(X_data, X_data,epochs=15,batch_size=128,verbose = 2,validation_data=(X_datatest, X_datatest)) File "C:\Users\bdyssm\AppData\Local\Programs\Python\Python35\lib\site-packages\keras\engine\training.py", line 952, in fit batch_size=batch_size) File "C:\Users\bdyssm\AppData\Local\Programs\Python\Python35\lib\site-packages\keras\engine\training.py", line 789, in _standardize_user_data exception_prefix='target') File "C:\Users\bdyssm\AppData\Local\Programs\Python\Python35\lib\site-packages\keras\engine\training_utils.py", line 128, in standardize_input_data 'with shape ' + str(data_shape))

ValueError: Error when checking target: expected dense_1 to have 3 dimensions, but got array withshape (2892, 128, 128, 3)

and this is the cnn_model summary

来源:https://stackoverflow.com/questions/55328025/is-there-a-way-to-fix-the-dense-layer-shape-when-adding-conv2d-layer-with-lstm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!