我的数据为一个excle,excle中有两列,分别为RS数据和LS数据 使用10个RS和LS数据预测接下来一个的LS数据,训练集为70%,验证集为15%,测试集为15% 最后要反归一化打印评价指标和预测图片 我们使用基于pytorch的BP神经网络代码
时间: 2024-03-17 07:46:20 浏览: 54
好的,基于您的需求,以下是一个基于 PyTorch 的 BP 神经网络代码,用于预测下一个 LS 数据。
首先,我们需要将 Excel 中的数据读入到 Pandas DataFrame 中:
```
import pandas as pd
# 读取 Excel 中的数据
df = pd.read_excel('data.xlsx', usecols=[0, 1], names=['RS', 'LS'])
```
接下来,我们需要将数据集划分为训练集、验证集和测试集,并进行归一化处理:
```
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# 划分数据集
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size=0.15, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=0.1765, random_state=42)
# 归一化处理
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
X_test = scaler.transform(X_test)
y_train = scaler.fit_transform(y_train.reshape(-1, 1)).ravel()
y_val = scaler.transform(y_val.reshape(-1, 1)).ravel()
y_test = scaler.transform(y_test.reshape(-1, 1)).ravel()
```
然后,我们可以使用 PyTorch 构建 BP 神经网络模型:
```
import torch
import torch.nn as nn
# 定义 BP 神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.Linear(64, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 实例化模型
net = Net()
```
接着,我们需要定义损失函数和优化器:
```
import torch.optim as optim
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
```
接下来,我们可以开始训练模型:
```
# 定义训练参数
EPOCHS = 1000
BATCH_SIZE = 32
# 训练模型
for epoch in range(EPOCHS):
running_loss = 0.0
for i in range(0, len(X_train), BATCH_SIZE):
inputs = torch.Tensor(X_train[i:i+BATCH_SIZE])
labels = torch.Tensor(y_train[i:i+BATCH_SIZE])
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels.unsqueeze(1))
loss.backward()
optimizer.step()
running_loss += loss.item()
if epoch % 100 == 99:
print('Epoch %d loss: %.6f' % (epoch+1, running_loss/len(X_train)))
```
训练完成后,我们可以对模型进行评估和预测:
```
import numpy as np
from sklearn.metrics import r2_score, mean_squared_error
# 对验证集进行预测
y_val_pred = scaler.inverse_transform(net(torch.Tensor(X_val)).detach().numpy().reshape(-1, 1)).ravel()
# 计算 R2 分数和均方误差
r2 = r2_score(y_val, y_val_pred)
mse = mean_squared_error(y_val, y_val_pred)
print('R2 score on validation set: %.6f' % r2)
print('MSE on validation set: %.6f' % mse)
```
最后,我们可以对测试集进行预测,并进行反归一化处理,以便打印评价指标和预测图片:
```
import matplotlib.pyplot as plt
# 对测试集进行预测
y_test_pred = scaler.inverse_transform(net(torch.Tensor(X_test)).detach().numpy().reshape(-1, 1)).ravel()
# 反归一化处理
X_test = scaler.inverse_transform(X_test)
y_test = scaler.inverse_transform(y_test.reshape(-1, 1)).ravel()
y_test_pred = scaler.inverse_transform(y_test_pred.reshape(-1, 1)).ravel()
# 打印评价指标
r2 = r2_score(y_test, y_test_pred)
mse = mean_squared_error(y_test, y_test_pred)
print('R2 score on test set: %.6f' % r2)
print('MSE on test set: %.6f' % mse)
# 绘制预测图像
plt.plot(X_test[:, 0], y_test, label='true')
plt.plot(X_test[:, 0], y_test_pred, label='predicted')
plt.legend()
plt.show()
```
希望这个代码可以帮助到您!
阅读全文