请提供用BP神经网络进行多步预测的程序示例,6个输入特征,预测180个时间步后的温度值,可视化输出
时间: 2024-03-19 07:45:23 浏览: 107
基于BP神经网络的时间序列预测-matlab程序
好的,以下是一个用BP神经网络进行多步预测的程序示例,其中有6个输入特征,预测180个时间步后的温度值,并可视化输出:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import torch
import torch.nn as nn
# 读取数据
dataset = pd.read_csv('data.csv')
data = dataset.iloc[:, 1:].values
# 归一化
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size, :]
test_data = data[train_size:, :]
# 定义函数生成数据
def generate_data(data, n_steps_in, n_steps_out):
X, y = [], []
for i in range(len(data)-n_steps_in-n_steps_out+1):
x = data[i:(i+n_steps_in), :]
y.append(data[(i+n_steps_in):(i+n_steps_in+n_steps_out), 0])
X.append(x)
return np.array(X), np.array(y)
# 准备数据
n_steps_in = 10
n_steps_out = 180
X_train, y_train = generate_data(train_data, n_steps_in, n_steps_out)
X_test, y_test = generate_data(test_data, n_steps_in, n_steps_out)
X_train = torch.from_numpy(X_train).float()
y_train = torch.from_numpy(y_train).float()
X_test = torch.from_numpy(X_test).float()
y_test = torch.from_numpy(y_test).float()
# 定义BP神经网络模型
class BPNet(nn.Module):
def __init__(self):
super(BPNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Linear(n_steps_in*6, 128),
nn.ReLU()
)
self.layer2 = nn.Sequential(
nn.Linear(128, 64),
nn.ReLU()
)
self.layer3 = nn.Linear(64, n_steps_out)
def forward(self, x):
x = x.view(x.size(0), -1)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
return x
# 定义模型和优化器
model = BPNet()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 100
train_loss = []
test_loss = []
for epoch in range(num_epochs):
# 训练集
model.train()
optimizer.zero_grad()
output = model(X_train)
loss = criterion(output, y_train)
loss.backward()
optimizer.step()
train_loss.append(loss.item())
# 测试集
model.eval()
with torch.no_grad():
output = model(X_test)
loss = criterion(output, y_test)
test_loss.append(loss.item())
if epoch % 10 == 0:
print('Epoch [{}/{}], Train Loss: {:.4f}, Test Loss: {:.4f}'.format(epoch+1, num_epochs, train_loss[-1], test_loss[-1]))
# 预测
model.eval()
with torch.no_grad():
x_input = X_test[0, :, :].unsqueeze(0)
preds = []
for i in range(n_steps_out):
output = model(x_input)
preds.append(output.item())
x_input = torch.cat((x_input[:, 1:, :], output.unsqueeze(0)), dim=1)
preds = np.array(preds).reshape(-1, 1)
preds = scaler.inverse_transform(np.concatenate((preds, np.zeros((len(preds), 5))), axis=1))[:, 0]
# 可视化
plt.plot(y_test[0, :], label='True')
plt.plot(preds, label='Predicted')
plt.legend()
plt.show()
```
在这个示例中,我们首先读取数据并进行归一化处理。然后,我们将数据划分为训练集和测试集,并使用`generate_data`函数将其转换为输入和输出序列。我们定义了一个`BPNet`类作为模型,它有三个全连接层,并使用均方误差作为损失函数和Adam优化器进行训练。最后,我们使用训练好的模型对测试集进行预测,并将预测结果反归一化,然后可视化预测结果和真实值。
阅读全文