建立lstm多步预测模型,并根据PM10、SO2 、NO2 、CO、温度、压强等因素,预测PM2.5浓度python代码
时间: 2023-10-20 17:23:36 浏览: 90
Python实现基于LSTM型来预测污染物浓度
以下是建立LSTM多步预测模型并根据多个因素预测PM2.5浓度的Python代码:
```python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 读取数据
df = pd.read_csv('data.csv', encoding='utf-8')
# 数据预处理
df = df.dropna()
df = df.drop(['year', 'month', 'day', 'hour'], axis=1)
df = df[['PM2.5', 'PM10', 'SO2', 'NO2', 'CO', 'TEMP', 'PRES']]
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
# 定义函数
def create_dataset(dataset, look_back=1, look_forward=1):
X, Y = [], []
for i in range(len(dataset)-look_back-look_forward+1):
X.append(dataset[i:(i+look_back), :])
Y.append(dataset[(i+look_back):(i+look_back+look_forward), 0])
return np.array(X), np.array(Y)
# 构建训练集和测试集
train_size = int(len(scaled_data) * 0.7)
test_size = len(scaled_data) - train_size
train, test = scaled_data[0:train_size,:], scaled_data[train_size:len(scaled_data),:]
# 创建输入和输出数据集
look_back = 12
look_forward = 1
trainX, trainY = create_dataset(train, look_back, look_forward)
testX, testY = create_dataset(test, look_back, look_forward)
# 构建LSTM模型
model = Sequential()
model.add(LSTM(50, input_shape=(look_back, 7)))
model.add(Dense(look_forward))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# 预测PM2.5浓度
testPredict = model.predict(testX)
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform(testY)
# 输出结果
for i in range(len(testY)):
print("真实值:%.2f 预测值:%.2f" % (testY[i], testPredict[i]))
```
其中,`data.csv`是包含多个因素和PM2.5浓度的数据文件,本代码使用了`MinMaxScaler`来进行数据归一化处理,建立了一个包含一个LSTM层和一个全连接层的模型,使用`mean_squared_error`作为损失函数,使用`adam`作为优化器进行训练。最后输出每个测试样本的真实值和预测值。
阅读全文