BP神经网络做多分类问题,并利用测试集进行测试得到准确率 代码
时间: 2024-03-17 07:42:06 浏览: 51
基于BP神经网络的数据集训练和测试
以下是使用Python和Pytorch实现BP神经网络进行多分类预测并测试准确率的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# 定义BP神经网络模型
class BPNet(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(BPNet, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义训练函数
def train(model, optimizer, criterion, train_loader):
model.train()
train_loss = 0.0
for data, label in train_loader:
optimizer.zero_grad()
output = model(data)
loss = criterion(output, label)
loss.backward()
optimizer.step()
train_loss += loss.item() * data.size(0)
return train_loss / len(train_loader.dataset)
# 定义验证函数
def validate(model, criterion, val_loader):
model.eval()
val_loss = 0.0
with torch.no_grad():
for data, label in val_loader:
output = model(data)
loss = criterion(output, label)
val_loss += loss.item() * data.size(0)
return val_loss / len(val_loader.dataset)
# 定义测试函数
def test(model, test_loader):
model.eval()
num_correct = 0
with torch.no_grad():
for data, label in test_loader:
output = model(data)
pred = torch.argmax(output, dim=1)
num_correct += torch.sum(pred == label).item()
return num_correct / len(test_loader.dataset)
# 加载数据集
train_data = torch.randn(1000, 10)
train_labels = torch.randint(low=0, high=5, size=(1000,))
val_data = torch.randn(500, 10)
val_labels = torch.randint(low=0, high=5, size=(500,))
test_data = torch.randn(500, 10)
test_labels = torch.randint(low=0, high=5, size=(500,))
# 转换数据格式
train_dataset = TensorDataset(train_data, train_labels)
val_dataset = TensorDataset(val_data, val_labels)
test_dataset = TensorDataset(test_data, test_labels)
# 定义超参数
input_dim = 10
hidden_dim = 20
output_dim = 5
lr = 0.01
num_epochs = 20
batch_size = 32
# 初始化模型和优化器
model = BPNet(input_dim, hidden_dim, output_dim)
optimizer = optim.SGD(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
# 加载数据
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 训练模型
for epoch in range(num_epochs):
train_loss = train(model, optimizer, criterion, train_loader)
val_loss = validate(model, criterion, val_loader)
print('Epoch: {}/{}, Train Loss: {:.4f}, Val Loss: {:.4f}'.format(epoch+1, num_epochs, train_loss, val_loss))
# 测试模型
test_acc = test(model, test_loader)
print('Test Accuracy: {:.2f}%'.format(test_acc * 100))
```
这段代码中,我们在训练模型后使用测试集来评估模型的分类准确率。我们定义了一个`test()`函数来计算模型在测试集上的分类准确率。在该函数中,我们首先使用`torch.argmax()`函数来得到模型输出的预测标签,然后使用`torch.sum()`函数和`==`运算符来计算预测正确的样本数量。最后,我们除以测试集的总样本数来得到模型在测试集上的分类准确率。
阅读全文