使用Keras Python为LSTM模型整形输入



我们正在使用kaggle数据集:https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results/version/2.它有120年奥运会的数据。我们的目标是在前几届奥运会的数据基础上训练我们的模型,并根据训练的模型预测该国在下一届奥运会上可能获得的奖牌。我们采用年龄、性别、身高、体重、NOC(国家(、运动、项目等属性来预测我们的产出等级(金牌、银牌、铜牌和奖牌(。我们希望使用LSTM来基于前几年的数据而不是120年的整个数据集进行预测。

但在使用LSTM时,我们面临的主要挑战是如何塑造LSTM的输入。LSTM的时间步长和样本量应该是多少?应该如何对数据进行分组,以便将其提供给LSTM。对于每个国家,我们都有不同数量的行,对应于每年的奥运会和所有体育项目的组合。

我们在这一步上被困了好几天。

如果有人能深入了解输入应该如何输入到LSTM,那就太好了。

我们写了这样的代码:

def-lstm_classifier(final_data(:

country_count = len(final_data['NOC'].unique())
year_count = len(final_data['Year'].unique())
values = final_data.values
final_X = values[:, :-1]
final_Y = values[:, -1] 
print(country_count, ' ', year_count)
# reshape - # countries, time series, # attributes
#final_X = final_X.reshape(country_count, year_count, final_X.shape[1])
final_X = final_X.groupby("Country", as_index=True)['Year', 'Sex', 'Age', 'Height', 'Weight', 'NOC', 'Host_Country', 'Sport'].apply(lambda x: x.values.tolist())
final_Y = final_Y.groupby("Country", as_index=True)['Medal' ].apply(lambda x: x.values.tolist())
# define model - 10 hidden nodes
model = Sequential()
model.add(LSTM(10, input_shape = (country_count, final_X.shape[1])))
model.add(Dense(4, activation = 'sigmoid'))
model.compile(optimizer = 'adam', loss = 'mean_squared_error', metrics = ['accuracy'])
# fit network
history = model.fit(final_X, final_Y, epochs = 10, batch_size = 50)
loss, accuracy = model.evaluate(final_X, final_Y)
print(accuracy)

我也处于同样的情况。我想从原始日志数据中进行用户级别的预测。事实上,我不知道正确的解决方案,但我已经学会了一些技巧。

我认为你的状态很好。首先,你必须将2D数据转换为3D,就像Jason Brownlee所做的那样点击这里!

另一个很好的例子点击这里!

他们使用这种方法:

Keras LSTM层期望3维(样本、时间步长、特征(的numpy数组形式的输入,其中样本是训练序列的数量,时间步长是回顾窗口或序列长度,特征是每个时间步长的每个序列的特征数量。

# function to reshape features into (samples, time steps, features) 
def gen_sequence(id_df, seq_length, seq_cols):
""" Only sequences that meet the window-length are considered, no padding is used. This means for testing
we need to drop those which are below the window-length. An alternative would be to pad sequences so that
we can use shorter ones """
data_array = id_df[seq_cols].values
num_elements = data_array.shape[0]
for start, stop in zip(range(0, num_elements-seq_length), range(seq_length, num_elements)):
yield data_array[start:stop, :]

如果您找到了更好的解决方案,请不要犹豫,并与我们分享:-(

最新更新