lstm_9层的输入0与该层不兼容:预期ndim = 3,找到的ndim = 4。收到完整的图形:[无,300,300,1]

时间:2020-05-15 10:15:14

标签: python keras

该代码在图像数据集上执行,在执行以下代码时,我遇到了值错误。请帮助我找出如何解决此错误。

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, LSTM
import pickle
import numpy as np

X = np.array(pickle.load(open("X.pickle","rb")))
Y = np.array(pickle.load(open("Y.pickle","rb")))

#scaling our image data
X = X/255.0

model = Sequential()
print(X.shape)
print(Y.shape)
#model.add(Conv2D(64 ,(3,3), input_shape = X.shape[1:]))
model.add(Conv2D(64 ,(3,3), input_shape = X.shape[1:]))
# print(X.shape)
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))
print(X.shape)
print(Y.shape)

model.add(Conv2D(128 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))
print(X.shape)
print(Y.shape)

model.add(Conv2D(256 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))
print(X.shape)
print(Y.shape)

model.add(Conv2D(512 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))
print(X.shape)
print(Y.shape)

model.add(Flatten())
print(X.shape)
print(Y.shape)

model = Sequential()
model.add(LSTM(128, input_shape=(X.shape[1:]), activation='relu', return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(10, activation='softmax'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)


model.compile(loss='binary_crossentropy', optimizer=opt,
             metrics=['accuracy'])

model.fit(X, Y, batch_size=32, epochs = 2, validation_split=0.1)

上面的代码产生以下输出。我一次又一次地打印形状,只是为了看到生成的矩阵。 (90,300,300,1) (90,) (90,300,300,1) (90,) (90,300,300,1) (90,) (90,300,300,1) (90,) (90,300,300,1) (90,) (90,300,300,1) (90,)

根据代码中的错误,在第一个LSTM中,图像的输入尺寸需要非常小的变化。您能对同一代码进行更改吗?

1 个答案:

答案 0 :(得分:1)

model = Sequential()

model.add(Conv2D(64 ,(3,3), input_shape = (300,300,1)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(128 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(256 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Conv2D(512 ,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size = (2,2)))

model.add(Reshape((16, 16*512)))
model.add(LSTM(128, activation='relu', return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(10, activation='softmax'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)


model.compile(loss='binary_crossentropy', optimizer=opt,
             metrics=['accuracy'])

model.summary()