BP神经网络做多分类预测 代码
时间: 2023-08-03 17:02:36 浏览: 90
以下是使用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)
# 加载数据集
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,))
# 转换数据格式
train_dataset = TensorDataset(train_data, train_labels)
val_dataset = TensorDataset(val_data, val_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)
# 训练模型
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))
```
这段代码中,我们定义了一个BP神经网络模型`BPNet`,并使用交叉熵损失函数`nn.CrossEntropyLoss()`作为损失函数。在训练过程中,我们使用随机梯度下降`optim.SGD()`作为优化器进行参数更新。我们还定义了训练函数`train()`和验证函数`validate()`,分别用于训练模型和验证模型。最后,我们使用Pytorch的`DataLoader`将数据集转换为批量数据,并进行模型训练。
阅读全文