添加LSTM层但获取所需的位置参数:“单位”错误

时间:2019-03-28 21:32:37

标签: python tensorflow keras recurrent-neural-network

我正在尝试运行我的第一个机器学习模型。但是我收到下面的错误。

  

return_sequences = True))   TypeError: init ()缺少1个必需的位置参数:'units'

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, LSTM, Dropout

model = Sequential()

model.add(LSTM(input_dim=1,
           output_dim=50,
           return_sequences=True))

model.add(Dropout(0.2))

model.add(LSTM(100, return_sequences=False))
model.add(Dropout(0.2))

model.add(Dense(output_dim=1))
model.add(Activation('linear'))

start = time.time()

model.compile(loss="mse", optimizer="rmsprop")

因为它说缺少参数单位,所以我也尝试了下面的行,

model.add(LSTM(100,
           input_dim=1,
           output_dim=50,
           return_sequences=True))

然后收到此错误消息,但我不明白为什么我第一次尝试时就没有出现这种错误。我想念什么?

  

TypeError :(“关键字参数无法理解:”,“ input_dim”)

1 个答案:

答案 0 :(得分:1)

unitsLSTM的第一个参数,代表该层输出数据的最后一个维度。它显示第一个错误,因为您的代码首次尝试中没有unitsunits满足该条件,以便在第二次尝试中显示第二个错误。

在这种情况下,应使用input_shape参数指定第一层输入的形状。您的第一个LSTMinput_shape应该有两个数据(timestepfeaturebatch_size默认不需要填写),因为LSTM需要三个尺寸输入。假设您的时间步为10,则应将代码更改为以下代码。

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, LSTM, Dropout,Activation

model = Sequential()
model.add(LSTM(units=100,input_shape=(10,1),return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(100, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.add(Activation('linear'))
model.compile(loss="mse", optimizer="rmsprop")
print(model.summary())

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm (LSTM)                  (None, 10, 100)           40800     
_________________________________________________________________
dropout (Dropout)            (None, 10, 100)           0         
_________________________________________________________________
lstm_1 (LSTM)                (None, 100)               80400     
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense (Dense)                (None, 1)                 101       
_________________________________________________________________
activation (Activation)      (None, 1)                 0         
=================================================================
Total params: 121,301
Trainable params: 121,301
Non-trainable params: 0
_________________________________________________________________