pytorch实现cnn手写数字识别并计算查准率,查全率以及ALU的代码
时间: 2023-06-18 20:06:22 浏览: 32
以下是使用PyTorch实现CNN手写数字识别并计算查准率、查全率和ALU的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
# 设置超参数
num_epochs = 10
num_classes = 10
batch_size = 100
learning_rate = 0.001
# 加载数据集并进行预处理
train_dataset = datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
# 创建数据加载器
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
# 定义CNN模型
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(7*7*32, num_classes)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
# 实例化CNN模型
model = CNN()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# 训练模型
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 前向传播
outputs = model(images)
loss = criterion(outputs, labels)
# 反向传播并优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每训练100个batch就输出一次信息
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('准确率: {} %'.format(100 * correct / total))
# 计算查准率、查全率和ALU
with torch.no_grad():
TP, TN, FP, FN = 0, 0, 0, 0
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
for i in range(len(labels)):
if labels[i] == predicted[i]:
if labels[i] == 1:
TP += 1
else:
TN += 1
else:
if labels[i] == 1:
FN += 1
else:
FP += 1
precision = TP / (TP + FP)
recall = TP / (TP + FN)
ALU = (TN + TP) / (TN + TP + FP + FN)
print('查准率: {:.4f}, 查全率: {:.4f}, ALU: {:.4f}'.format(precision, recall, ALU))
```
在以上代码中,我们首先加载MNIST数据集并进行预处理。然后,我们定义了一个CNN模型,并且实例化了该模型。接着,我们定义了损失函数和优化器,并在训练过程中使用它们。最后,我们测试了模型的准确率,并计算了查准率、查全率和ALU。
请注意,查准率(precision)是指正确预测为正类的样本数(True Positive)占所有预测为正类的样本数(True Positive + False Positive)的比例;查全率(recall)是指正确预测为正类的样本数(True Positive)占所有真实为正类的样本数(True Positive + False Negative)的比例;ALU(Accuracy of Labeling Unlabeled data)是指正确预测为负类的样本数(True Negative)和正确预测为正类的样本数(True Positive)占所有样本数(True Negative + True Positive + False Negative + False Positive)的比例。
相关推荐


















