编写代码:用minist数据集实现bp神经网络的单分类的模型
时间: 2024-05-13 13:13:50 浏览: 111
注:本代码使用Python语言,基于PyTorch框架实现。
首先,需要准备好minist数据集。我们使用PyTorch自带的torchvision库,可以方便地下载和处理minist数据集。
```python
import torch
import torchvision
import torchvision.transforms as transforms
# 定义数据预处理方法
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])
# 下载并加载minist数据集
trainset = torchvision.datasets.MNIST(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,
shuffle=True, num_workers=2)
testset = torchvision.datasets.MNIST(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64,
shuffle=False, num_workers=2)
```
接下来,我们定义一个简单的bp神经网络模型。该模型有一个输入层、一个隐藏层和一个输出层,每层使用sigmoid激活函数。
```python
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = torch.nn.Linear(28*28, 128)
self.fc2 = torch.nn.Linear(128, 10)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = x.view(-1, 28*28)
x = self.sigmoid(self.fc1(x))
x = self.fc2(x)
return x
```
然后,我们定义损失函数和优化器。在这里,我们选择交叉熵损失函数和随机梯度下降优化器。
```python
net = Net()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
```
最后,我们开始训练模型。在每个epoch中,我们用训练集的数据来更新模型参数,并用测试集的数据来评估模型的准确率。训练过程中,我们还记录了每个epoch的损失和准确率,并输出最终的测试集准确率。
```python
for epoch in range(10):
running_loss = 0.0
correct = 0
total = 0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Epoch %d loss: %.3f accuracy: %.3f' %
(epoch + 1, running_loss / len(trainloader), correct / total))
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
inputs, labels = data
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Test accuracy: %.3f' % (correct / total))
```
阅读全文