bp神经网络回归relu函数实例代码
时间: 2023-08-08 22:05:52 浏览: 112
下面是使用Python和PyTorch库实现BP神经网络回归ReLU函数的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from sklearn.datasets import make_regression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# 生成随机数据集
X, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1)
# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(X)
y = scaler.fit_transform(y.reshape(-1, 1)).reshape(-1)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
# 定义神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(2, 2) # 输入层到隐藏层
self.relu = nn.ReLU() # 隐藏层的激活函数
self.fc2 = nn.Linear(2, 1) # 隐藏层到输出层
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# 初始化模型和优化器
net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.01)
criterion = nn.MSELoss()
# 训练模型
for epoch in range(1000):
optimizer.zero_grad() # 清除梯度
outputs = net(torch.FloatTensor(X_train))
loss = criterion(outputs.squeeze(), torch.FloatTensor(y_train))
loss.backward() # 反向传播
optimizer.step() # 更新权重
if epoch % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 1000, loss.item()))
# 测试模型
with torch.no_grad():
outputs = net(torch.FloatTensor(X_test))
loss = criterion(outputs.squeeze(), torch.FloatTensor(y_test))
print('Test Loss: {:.4f}'.format(loss.item()))
# 计算R平方值
y_pred = net(torch.FloatTensor(X_test)).squeeze().detach().numpy()
r2 = 1 - np.sum(np.square(y_test - y_pred)) / np.sum(np.square(y_test - np.mean(y_test)))
print('R2 Score: {:.4f}'.format(r2))
```
注意,这里使用了PyTorch库来实现神经网络模型和优化器,并使用scikit-learn库来生成和处理数据集。在训练模型时,我们使用了MSE损失函数和梯度下降法来更新权重。在测试模型时,我们计算了均方误差和R平方值来评估模型的性能。
阅读全文