PyTorchCNN

    1. # 用pytorch简单的构建两层卷积网络
    2. # 对手写字进行识别
    3. import torch
    4. import torchvision
    5. # 参数函数,类似激活函数
    6. import torch.nn.functional as F
    7. # standard datasets
    8. import torchvision.datasets as datasets
    9. # 可以对数据集进行转换
    10. import torchvision.transforms as transforms
    11. from torch import optim # 参数优化
    12. from torch import nn # 所有神经网络模块
    13. # Gives easier dataset managment by creating mini batches etc
    14. from torch.utils.data import DataLoader
    15. # for nice progress bar!
    16. from tqdm import tqdm
    17. #--------------------------------------------------------------------
    18. class CNN(nn.Module):
    19. def __init__(self, in_channels=1, num_classes=10):
    20. super(CNN, self).__init__()
    21. self.conv1 = nn.Conv1d(in_channels=in_channels,
    22. out_channels=8,
    23. kernel_size=(3,3),
    24. stride=(1,1),
    25. padding=(1,1))
    26. self.pool = nn.MaxPool2d(kernel_size=(2,2),stride=(2,2))
    27. self.conv2 = nn.Conv2d(in_channels=8,
    28. out_channels=16,
    29. kernel_size=(3,3),
    30. stride=(1,1),
    31. padding=(1,1))
    32. self.fc = nn.Linear(16*7*7, num_classes)
    33. def forward(self, x):
    34. x = F.relu(self.conv1(x))
    35. x = self.pool(x)
    36. x = F.relu(self.conv2(x))
    37. x = self.pool(x)
    38. x = x.reshape(x.shape[0],-1)
    39. x = self.fc(x)
    40. return x
    41. #--------------------------------------------------------------------
    42. # Set device cuda for GPU if it's available otherwise run on the CPU
    43. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    44. # 参数设置
    45. in_channels = 1
    46. num_classes = 10
    47. learning_rate = 0.001
    48. batch_size = 64
    49. num_epochs = 3
    50. # Load Training and Test data
    51. train_dataset = datasets.MNIST(root='dataset/',train=True,transform=transforms.ToTensor(),download=True)
    52. test_dataset = datasets.MNIST(root='dataset/',train=False,transform=transforms.ToTensor(),download=True)
    53. train_loader = DataLoader(dataset=train_dataset,shuffle=True,batch_size=batch_size)
    54. test_loader = DataLoader(dataset=test_dataset,shuffle=True,batch_size=batch_size)
    55. #--------------------------------------------------------------------
    56. # 初始化网络
    57. model = CNN(in_channels=in_channels,num_classes=num_classes).to(device)
    58. # loss and optimizer
    59. criterion= nn.CrossEntropyLoss()
    60. optimizer = optim.Adam(model.parameters(),lr=learning_rate)
    61. # 训练网络
    62. for epoch in range(num_epochs):
    63. for batch_idxm,(data,targets) in enumerate(tqdm(train_loader)):
    64. data = data.to(device)
    65. targets = targets.to(device)
    66. # forward
    67. outputs = model(data)
    68. # 计算损失
    69. loss = criterion(outputs,targets)
    70. # 向后传播
    71. loss.backward()
    72. # 梯度归0
    73. optimizer.zero_grad()
    74. # 梯度优化
    75. optimizer.step()
    76. #--------------------------------------------------------------------
    77. # Check accuracy on training & test to see how good our model
    78. def check_accuracy(loader, model):
    79. num_correct = 0
    80. num_samples = 0
    81. model.eval()
    82. with torch.no_grad():
    83. for x, y in loader:
    84. x = x.to(device=device)
    85. y = y.to(device=device)
    86. outputs = model(x)
    87. _, indexes = outputs.max(1)
    88. num_correct += (indexes == y).sum()
    89. num_samples += indexes.size(0) # batch_size
    90. model.train()
    91. return num_correct/num_samples
    92. #--------------------------------------------------------------------
    93. print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}")
    94. print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")
    95. # Accuracy on training set: 9.62
    96. # Accuracy on test set: 9.59