用python写一个LSTM寿命预测模型
时间: 2024-05-07 16:22:02 浏览: 47
好的,以下是Python代码示例:
```
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 读取数据
data = pd.read_csv('life_expectancy_data.csv')
data = data.dropna()
# 准备数据
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# 将数据分为训练集和测试集
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
# 准备 LSTM 输入
X_train = np.array(X_train).reshape((X_train.shape[0], 1, X_train.shape[1]))
X_test = np.array(X_test).reshape((X_test.shape[0], 1, X_test.shape[1]))
# 定义 LSTM 模型
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(1, X.shape[1])))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
# 训练 LSTM 模型
model.fit(X_train, y_train, epochs=50, batch_size=72, validation_data=(X_test, y_test), verbose=2, shuffle=False)
# 预测测试集
y_pred = model.predict(X_test)
# 输出模型得分
score = model.evaluate(X_test, y_test, verbose=0)
print('LSTM 模型得分: %.2f' % score)
# 预测单个观测值
new_observation = [[70, 0.2, 0.4, 60, 1]]
new_observation = np.array(new_observation).reshape((new_observation.shape[0], 1, new_observation.shape[1]))
prediction = model.predict(new_observation)
print('预测寿命:', prediction[0][0])
```
请确保在使用模型前,已经准备好了相关的数据集,并且对数据做过预处理和特征工程。另外,该模型只能作为参考,具体的模型和参数调整需要视实验结果和应用场景而定。
阅读全文