首页 文章

Keras LSTM在LSTM层之前具有嵌入层

提问于
浏览
0

我正在尝试keras IMDB数据的例子,数据形状是这样的:

x_train形状:(25000,80)

我只是将keras示例的原始代码更改为如下代码:

model = Sequential()
layer1 = Embedding(max_features, 128)
layer2 = LSTM(128, dropout = 0.2, recurrent_dropout = 0.2, return_sequences = True)
layer3 = Dense(1, activation = 'sigmoid')
model.add(layer1)
model.add(layer2)
model.add(layer3)

原始模型将 return_sequences 设置为 False 并将其更改为 True ,并且我遇到了此错误:

期望dense_1有3个维度,但得到形状的数组(25000,1)

但是我打印了模型的结构,发现LSTM层的输出正是一个3D张量:

lstm_1(LSTM):(无,无,128)

2 回答

  • 0

    您需要重塑您的训练阵列,使用以下代码:

    x_train = np.reshape(x_train,(x_train.shape[0],1,x_train.shape[1]))
    

    你的测试数组:

    x_test = np.reshape(x_test,(x_test.shape[0],1,x_test.shape[1]))
    

    仅供参考:np是numpy pacakge .

    LSTM模型的时间步长:https://machinelearningmastery.com/use-timesteps-lstm-networks-time-series-forecasting/

    时间步长:这相当于运行递归神经网络的时间步长 . 如果您希望网络具有60个字符的内存,则此数字应为60 .

  • 0

    我认为在LSTM之后你需要一个TimeDistributed层,其中return_sequences = True

    layer2= LSTM(128, dropout=0.2, 
                 recurrent_dropout=0.2,return_sequences=True)
    layer3= TimeDistributed(Dense(1, activation='sigmoid')))
    

相关问题