首页 > 其他分享 >pytorch cnn 手写数字识别

pytorch cnn 手写数字识别

时间:2023-03-19 23:57:41浏览次数:47  
标签:args default self torch test pytorch train cnn 手写

结果

 

 

 

训练好的模型呢

训练过程中,不断变化

 

 

 

官网:

  是https://github.com/pytorch/examples/blob/main/mnist/main.py

  

 

   test改个名字

如何使用训练好的模型,来识别我手写的

from __future__ import print_function
  import argparse
  import torch
  import torch.nn as nn
  import torch.nn.functional as F
  import torch.optim as optim
  from torchvision import datasets, transforms
  from torch.optim.lr_scheduler import StepLR
   
   
  class Net(nn.Module):
  def __init__(self):
  super(Net, self).__init__()
  self.conv1 = nn.Conv2d(1, 32, 3, 1)
  self.conv2 = nn.Conv2d(32, 64, 3, 1)
  self.dropout1 = nn.Dropout(0.25)
  self.dropout2 = nn.Dropout(0.5)
  self.fc1 = nn.Linear(9216, 128)
  self.fc2 = nn.Linear(128, 10)
   
  def forward(self, x):
  x = self.conv1(x)
  x = F.relu(x)
  x = self.conv2(x)
  x = F.relu(x)
  x = F.max_pool2d(x, 2)
  x = self.dropout1(x)
  x = torch.flatten(x, 1)
  x = self.fc1(x)
  x = F.relu(x)
  x = self.dropout2(x)
  x = self.fc2(x)
  output = F.log_softmax(x, dim=1)
  return output
   
   
  def train(args, model, device, train_loader, optimizer, epoch):
  model.train()
  for batch_idx, (data, target) in enumerate(train_loader):
  data, target = data.to(device), target.to(device)
  optimizer.zero_grad()
  output = model(data)
  loss = F.nll_loss(output, target)
  loss.backward()
  optimizer.step()
  if batch_idx % args.log_interval == 0:
  print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
  epoch, batch_idx * len(data), len(train_loader.dataset),
  100. * batch_idx / len(train_loader), loss.item()))
  if args.dry_run:
  break
   
   
  def test(model, device, test_loader):
  model.eval()
  test_loss = 0
  correct = 0
  with torch.no_grad():
  for data, target in test_loader:
  data, target = data.to(device), target.to(device)
  output = model(data)
  test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
  pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
  correct += pred.eq(target.view_as(pred)).sum().item()
   
  test_loss /= len(test_loader.dataset)
   
  print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
  test_loss, correct, len(test_loader.dataset),
  100. * correct / len(test_loader.dataset)))
   
   
  def main():
  # Training settings
  parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
  parser.add_argument('--batch-size', type=int, default=64, metavar='N',
  help='input batch size for training (default: 64)')
  parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
  help='input batch size for testing (default: 1000)')
  parser.add_argument('--epochs', type=int, default=14, metavar='N',
  help='number of epochs to train (default: 14)')
  parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
  help='learning rate (default: 1.0)')
  parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
  help='Learning rate step gamma (default: 0.7)')
  parser.add_argument('--no-cuda', action='store_true', default=False,
  help='disables CUDA training')
  parser.add_argument('--no-mps', action='store_true', default=False,
  help='disables macOS GPU training')
  parser.add_argument('--dry-run', action='store_true', default=False,
  help='quickly check a single pass')
  parser.add_argument('--seed', type=int, default=1, metavar='S',
  help='random seed (default: 1)')
  parser.add_argument('--log-interval', type=int, default=10, metavar='N',
  help='how many batches to wait before logging training status')
  parser.add_argument('--save-model', action='store_true', default=False,
  help='For Saving the current Model')
  args = parser.parse_args()
  use_cuda = not args.no_cuda and torch.cuda.is_available()
  use_mps = not args.no_mps and torch.backends.mps.is_available()
   
  torch.manual_seed(args.seed)
   
  if use_cuda:
  device = torch.device("cuda")
  elif use_mps:
  device = torch.device("mps")
  else:
  device = torch.device("cpu")
   
  train_kwargs = {'batch_size': args.batch_size}
  test_kwargs = {'batch_size': args.test_batch_size}
  if use_cuda:
  cuda_kwargs = {'num_workers': 1,
  'pin_memory': True,
  'shuffle': True}
  train_kwargs.update(cuda_kwargs)
  test_kwargs.update(cuda_kwargs)
   
  transform=transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
  ])
  dataset1 = datasets.MNIST('../data', train=True, download=True,
  transform=transform)
  dataset2 = datasets.MNIST('../data', train=False,
  transform=transform)
  train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
  test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
   
  model = Net().to(device)
  optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
   
  scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
  for epoch in range(1, args.epochs + 1):
  train(args, model, device, train_loader, optimizer, epoch)
  test(model, device, test_loader)
  scheduler.step()
   
  if args.save_model:
  torch.save(model.state_dict(), "mnist_cnn.pt")
   
   
  if __name__ == '__main__':
  main()

标签:args,default,self,torch,test,pytorch,train,cnn,手写
From: https://www.cnblogs.com/mxleader/p/17234887.html

相关文章

  • RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:784, u
    ​ 发现报错:RuntimeError:NCCLerrorin:/pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:784,unhandledsystemerror​编辑想在linux上跑跑mmclassification......
  • 【2023-Pytorch-检测教程】手把手教你使用YOLOV5做电线绝缘子缺陷检测
    随着社会和经济的持续发展,电力系统的投资与建设也日益加速。在电力系统中,输电线路作为电能传输的载体,是最为关键的环节之一。而绝缘子作为输电环节中的重要设备,在支撑固定导......
  • Pytorch安装
    Pytorch安装1.Anaconda的下载和安装Anaconda的官网在官网进行下载,一路next(可以修改安装路径,默认安装在C盘),安装完成后可以在菜单看到新增了一些文件打开这个Anaconda......
  • Promise原理、方法及手写
    Promise原理、方法及手写ES6Promise对象:Promise对象-ECMAScript6入门(ruanyifeng.com)Promise/A+链接:Promises/A+(promisesaplus.com)什么是Promise?Promise是异......
  • 深度学习10. CNN经典网络 LeNet-5
    深度学习10.CNN经典网络LeNet-5​​一、LeNet-5简介​​​​二、网络详解​​​​1.输入图像​​​​2.卷积层C1​​​​3.池化层S2​​​​4.卷积层C3​​​​5.......
  • PyTorch学习笔记 8. 实现线性回归模型
    PyTorch学习笔记8.实现线性回归模型​​一、回归的概念​​​​1.概念​​​​2.目标​​​​3.应用​​​​4.训练线性回归的步骤​​​​二、数据集​​​​1.构......
  • 深度学习6. 多层感知机及PyTorch实现
    深度学习6.多层感知机及PyTorch实现​​一、概念​​​​1.MLP​​​​2.前向传播​​​​3.反向传播​​​​4.评估模式与训练模式​​​​二、模型定义​​​​1.加......
  • 人工智能-Pytorch案例实战(2)-CNN 的stride和zero-padding
    CNN的stridestride:是filter滑动图像的步长例如:stride=1,对于一个7*7的灰白图片,通过一个3*3大小的filter,输出下一个图片的大小为5*5(如何计算呢?公式呢?)(W-F+2P/......
  • 人工智能-Pytorch案例实战(1)-CNN Convolution Layer
    ConvolutionLayer左侧图示:一张彩色的图片,有三个部分组成(长度width宽度high深度depth),例如:32*32*3表示一彩色图片长度和宽度分别是32,32右侧图示:在CNN中,filter是一个......
  • 图像处理(1):PyTorch垃圾分类 数据预处理
    基于深度学习框架PyTorchtransforms方法进行数据的预处理产品和技术负责人,专注于NLP、图像、推荐系统整个过程主要包括:缩放、裁剪、归一化、标准化几个基本步骤。图像归一......