PyTorch入门——实现MNIST分类

import torch
from matplotlib import pyplot as plt
from torch import nn, optim
# from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from tqdm import tqdm
from matplotlib.ticker import MaxNLocator

# 超参数
batch_size = 256  # 批大小
learning_rate = 0.0001  # 学习率
epochs = 20  # 迭代次数
channels = 1  # 图像通道大小

# 数据集下载和预处理
transform = transforms.Compose([transforms.ToTensor(),  # 将图片转换成PyTorch中处理的对象Tensor,并且进行标准化0-1
                                transforms.Normalize([0.5], [0.5])])  # 归一化处理
path = './data/'  # 数据集下载后保存的目录
# 下载训练集和测试集
trainData = datasets.MNIST(path, train=True, transform=transform, download=True)
testData = datasets.MNIST(path, train=False, transform=transform)
# 处理成data loader
trainDataLoader = torch.utils.data.DataLoader(dataset=trainData, batch_size=batch_size, shuffle=True)  # 批量读取并打乱
testDataLoader = torch.utils.data.DataLoader(dataset=testData, batch_size=batch_size)


# 开始构建cnn模型
class cnn(torch.nn.Module):
    def __init__(self):
        super(cnn, self).__init__()
        self.model = torch.nn.Sequential(
            # The size of the picture is 28*28
            torch.nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, stride=1, padding=1),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2, stride=2),

            # The size of the picture is 14*14
            torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(kernel_size=2, stride=2),
            #
            # The size of the picture is 7*7
            torch.nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1),
            torch.nn.ReLU(),
            # torch.nn.MaxPool2d(kernel_size=2, stride=2),

            # The size of the picture is 7*7
            torch.nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1),
            torch.nn.ReLU(),
            # torch.nn.MaxPool2d(kernel_size=2, stride=2),

            torch.nn.Flatten(),
            torch.nn.Linear(in_features=7 * 7 * 256, out_features=512),
            torch.nn.ReLU(),
            torch.nn.Dropout(0.2),  # 抑制过拟合 随机丢掉一些节点
            torch.nn.Linear(in_features=512, out_features=10),
            # torch.nn.Softmax(dim=1) # pytorch的交叉熵函数其实是softmax-log-NLL 所以这里的输出就不需要再softmax了
        )

    def forward(self, input):
        output = self.model(input)
        return output


# 选择模型
model = cnn()
# GPU可用时转到cuda上执行
if torch.cuda.is_available():
    model = model.cuda()

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()  # 选用交叉熵函数作为损失函数
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# optimizer = optim.Adam(model.parameters())

# 训练模型并存储训练时的指标
epoch = 1
history = {'Train Loss': [],
           'Test Loss': [],
           'Train Acc': [],
           'Test Acc': []}
for epoch in range(1, epochs+1):
    processBar = tqdm(trainDataLoader, unit='step')
    model.train(True)
    train_loss, train_correct = 0, 0
    for step, (train_imgs, labels) in enumerate(processBar):

        if torch.cuda.is_available():  # GPU可用
            train_imgs = train_imgs.cuda()
            labels = labels.cuda()
        model.zero_grad()  # 梯度清零
        outputs = model(train_imgs)  # 输入训练集
        loss = criterion(outputs, labels)  # 计算损失函数
        predictions = torch.argmax(outputs, dim=1)  # 得到预测值
        correct = torch.sum(predictions == labels)
        accuracy = correct / labels.shape[0]  # 计算这一批次的正确率
        loss.backward()  # 反向传播
        optimizer.step()  # 更新优化器参数
        processBar.set_description("[%d/%d] Loss: %.4f, Acc: %.4f" %  # 可视化训练进度条设置
                                   (epoch, epochs, loss.item(), accuracy.item()))

        # 记录下训练的指标
        train_loss = train_loss + loss
        train_correct = train_correct + correct

        # 当所有训练数据都进行了一次训练后,在验证集进行验证
        if step == len(processBar) - 1:
            tst_correct, totalLoss = 0, 0
            model.train(False)  # 开始测试
            model.eval()  # 固定模型的参数并在测试阶段不计算梯度
            with torch.no_grad():
                for test_imgs, test_labels in testDataLoader:
                    if torch.cuda.is_available():
                        test_imgs = test_imgs.cuda()
                        test_labels = test_labels.cuda()
                    tst_outputs = model(test_imgs)
                    tst_loss = criterion(tst_outputs, test_labels)
                    predictions = torch.argmax(tst_outputs, dim=1)

                    totalLoss += tst_loss
                    tst_correct += torch.sum(predictions == test_labels)

                train_accuracy = train_correct / len(trainDataLoader.dataset)
                train_loss = train_loss / len(trainDataLoader)  # 累加loss后除以步数即为平均loss值

                test_accuracy = tst_correct / len(testDataLoader.dataset)  # 累加正确数除以样本数即为验证集正确率
                test_loss = totalLoss / len(testDataLoader)  # 累加loss后除以步数即为平均loss值

                history['Train Loss'].append(train_loss.item())  # 记录loss和acc
                history['Train Acc'].append(train_accuracy.item())
                history['Test Loss'].append(test_loss.item())
                history['Test Acc'].append(test_accuracy.item())

                processBar.set_description("[%d/%d] Loss: %.4f, Acc: %.4f, Test Loss: %.4f, Test Acc: %.4f" %
                                           (epoch, epochs, train_loss.item(), train_accuracy.item(), test_loss.item(),
                                            test_accuracy.item()))
    processBar.close()

# 对测试Loss进行可视化
plt.plot(history['Test Loss'], color='red', label='Test Loss')
plt.plot(history['Train Loss'], label='Train Loss')
plt.legend(loc='best')
plt.grid(True)
plt.xlabel('Epoch')
plt.xlim([0, epoch])
plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))
plt.ylabel('Loss')
plt.title('Train and Test LOSS')
plt.legend(loc='upper right')
plt.savefig('LOSS')
plt.show()

# 对测试准确率进行可视化
plt.plot(history['Test Acc'], color='red', label='Test Acc')
plt.plot(history['Train Acc'], label='Train Acc')
plt.legend(loc='best')
plt.grid(True)
plt.xlabel('Epoch')
plt.xlim([0, epoch])
plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))
plt.ylabel('Accuracy')
plt.title('Train and Test ACC')
plt.legend(loc='lower right')
plt.savefig('ACC')
plt.show()

torch.save(model, './model.pth')

 

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: PyTorch是一个基于Python的科学计算库,它可以作为一种深度学习框架来使用。而CNN(卷积神经网络)是一种常用的深度学习模型,用于图像识别和分类等任务。 要使用PyTorch和CNN来实现MNIST分类,可以按照以下步骤进行: 1. 导入必要的库和数据集:首先需要导入PyTorchMNIST数据集。 2. 定义模型:使用PyTorch定义一个CNN模型,包括卷积层、池化层、全连接层等。 3. 训练模型:使用训练集对模型进行训练,并调整模型参数以提高准确率。 4. 测试模型:使用测试集对训练好的模型进行测试,评估模型的准确率。 5. 保存模型:将训练好的模型保存下来,以便后续使用。 总之,使用PyTorch和CNN实现MNIST分类是一种常见的深度学习任务,需要对深度学习模型和PyTorch框架有一定的了解。 ### 回答2: PyTorch是一个开源的机器学习框架,可以用来构建神经网络模型进行训练和推理。而CNN(卷积神经网络)是一种常用于图像分类任务的深度学习模型。 首先,我们可以使用PyTorch库来加载MNIST数据集,该数据集包含手写数字的图片以及对应的标签。接着,我们可以使用CNN模型来训练和测试这些数据。 在PyTorch中,我们可以使用torchvision库来加载MNIST数据集。通过以下代码,可以将训练集和测试集分别存储在train_set和test_set中: ```python import torchvision.datasets as datasets train_set = datasets.MNIST(root='./data', train=True, download=True) test_set = datasets.MNIST(root='./data', train=False, download=True) ``` 接下来,我们可以定义CNN模型。一个典型的CNN模型包含若干卷积层、池化层和全连接层。在PyTorch中,我们可以使用`torch.nn`来构建网络模型。 下面是一个简单的例子,定义了一个包含两个卷积层和一个全连接层的CNN模型: ```python import torch.nn as nn class CNNModel(nn.Module): def __init__(self): super(CNNModel, self).__init__() self.conv1 = nn.Conv2d(1, 16, kernel_size=5) self.conv2 = nn.Conv2d(16, 32, kernel_size=5) self.fc = nn.Linear(32*4*4, 10) def forward(self, x): x = nn.functional.relu(self.conv1(x)) x = nn.functional.max_pool2d(x, 2) x = nn.functional.relu(self.conv2(x)) x = nn.functional.max_pool2d(x, 2) x = x.view(-1, 32*4*4) x = self.fc(x) return x model = CNNModel() ``` 接下来,我们需要定义损失函数和优化器,用于训练模型。在这里,我们使用交叉熵损失函数和随机梯度下降(SGD)优化器: ```python import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) ``` 然后,我们可以开始训练模型。对于每个训练样本,我们将图片输入到模型中进行前向传播,计算预测值。然后,我们计算损失,并通过反向传播更新模型的权重。 ```python num_epochs = 10 for epoch in range(num_epochs): running_loss = 0.0 for i, (images, labels) in enumerate(train_set): optimizer.zero_grad() outputs = model(images.unsqueeze(0)) loss = criterion(outputs, labels.unsqueeze(0)) loss.backward() optimizer.step() running_loss += loss.item() if (i+1) % 100 == 0: print(f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/{len(train_set)}], Loss: {running_loss/100:.4f}') running_loss = 0.0 ``` 最后,我们可以使用测试集来评估模型的性能。对于测试集中的每个样本,我们将图片输入到模型中进行前向传播,并与标签进行比较,计算准确率。 ```python correct = 0 total = 0 with torch.no_grad(): for images, labels in test_set: outputs = model(images.unsqueeze(0)) _, predicted = torch.max(outputs.data, 1) total += 1 correct += (predicted == labels).sum().item() accuracy = correct / total print(f'Accuracy on test set: {accuracy:.2%}') ``` 以上就是使用PyTorch和CNN实现MNIST数字分类任务的简单示例。通过加载数据集、定义模型、训练和测试模型,我们可以使用PyTorch来构建和训练自己的深度学习模型。 ### 回答3: PyTorch是一个开源的深度学习框架,而CNN(卷积神经网络)是一种深度学习网络模型。下面是关于如何使用PyTorch和CNN来实现MNIST分类任务的简要说明。 1. 导入所需的库和模块: ``` import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms ``` 2. 数据预处理: ``` transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) train_data = datasets.MNIST(root='data', train=True, download=True, transform=transform) test_data = datasets.MNIST(root='data', train=False, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=False) ``` 3. 定义CNN模型: ``` class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1) self.fc1 = nn.Linear(32 * 7 * 7, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2, 2) x = x.view(-1, 32 * 7 * 7) x = F.relu(self.fc1(x)) x = self.fc2(x) return x model = CNN() ``` 4. 定义损失函数和优化器: ``` criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) ``` 5. 训练模型: ``` n_epochs = 10 for epoch in range(n_epochs): for images, labels in train_loader: optimizer.zero_grad() output = model(images) loss = criterion(output, labels) loss.backward() optimizer.step() print('Epoch: {} Loss: {:.4f}'.format(epoch+1, loss.item())) ``` 6. 评估模型: ``` model.eval() correct = 0 total = 0 with torch.no_grad(): for images, labels in test_loader: output = model(images) _, predicted = torch.max(output.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy on the test set: {:.2f}%'.format(100 * correct / total)) ``` 通过上述步骤,我们可以使用PyTorch和CNN成功实现MNIST数据集的分类任务。通过训练和评估模型,我们可以得到准确率作为分类性能的评估指标。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值