建立一个5输入,1输出,70%训练集,30%测试集的bp神经网络的pytorch代码
时间: 2024-10-11 07:06:30 浏览: 22
算法基础基于pytorch的BP神经网络算法代码+数据集
要在PyTorch中建立一个有5个输入、1个输出,使用70%数据作为训练集,30%数据作为测试集的BP(Backpropagation,反向传播)神经网络,你可以按照以下步骤编写代码:
```python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
# 定义网络结构
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(5, 16) # 输入层到隐藏层
self.fc2 = nn.Linear(16, 8) # 隐藏层到另一隐藏层
self.fc_out = nn.Linear(8, 1) # 输出层
def forward(self, x):
x = torch.relu(self.fc1(x)) # 使用ReLU激活函数
x = torch.relu(self.fc2(x))
return self.fc_out(x)
# 创建数据集假设你已经有了`data`, `labels`变量
data = ... # 输入特征数据
labels = ... # 目标标签数据
# 划分数据集
train_size = int(len(data) * 0.7)
test_size = len(data) - train_size
train_data, test_data = random_split(data, [train_size, test_size])
# 数据加载器
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
test_loader = DataLoader(test_data, batch_size=32, shuffle=False)
# 初始化模型并设置损失函数和优化器
model = Net()
criterion = nn.MSELoss() if you want to use mean squared error else nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 使用SGD优化器
# 训练过程
num_epochs = 10 # 根据需求调整迭代次数
for epoch in range(num_epochs):
for inputs, targets in train_loader:
optimizer.zero_grad() # 梯度清零
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward() # 反向传播
optimizer.step() # 更新权重
# 测试过程
model.eval() # 设置模型为评估模式
with torch.no_grad():
correct = 0
total = 0
for inputs, targets in test_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += targets.size(0)
correct += (predicted == targets).sum().item()
accuracy = 100 * correct / total
print(f"Accuracy on the test set: {accuracy}%")
阅读全文