• pytorch-10.卷积神经网络


    示例:

    1. import torch
    2. in_channels, out_channels = 5,10
    3. width , height = 100,100
    4. kernel_size = 3
    5. batch_size = 1
    6. input = torch.randn(batch_size,in_channels,width,height)
    7. conv_layer = torch.nn.Conv2d(in_channels,out_channels,kernel_size=kernel_size)
    8. output = conv_layer(input)
    9. print(input.shape)
    10. print(output.shape)
    11. print(conv_layer.weight.shape)

     


    padding示例:

    如padding=1表示输入时,图像外面再补一圈0像素点

    1. import torch
    2. input = [
    3. 3,4,5,6,7,
    4. 2,4,6,8,2,
    5. 1,6,7,8,4,
    6. 9,7,4,6,2,
    7. 3,7,5,4,1
    8. ]
    9. input = torch.Tensor(input).view(1,1,5,5) #1,1,5,5 batch,channel,W,H
    10. conv_layer = torch.nn.Conv2d(1,1,kernel_size=3,padding=1,bias=False) #padding=1图像外面再补一圈0像素点
    11. kernel = torch.Tensor([1,2,3,4,5,6,7,8,9]).view(1,1,3,3) #1,1,3,3 output_channel, input_channel,W,H
    12. conv_layer.weight.data = kernel.data
    13. output = conv_layer(input)
    14. print(output)

     


    stride 步长示例:

    1. #步长
    2. import torch
    3. input = [
    4. 3,4,5,6,7,
    5. 2,4,6,8,2,
    6. 1,6,7,8,4,
    7. 9,7,4,6,2,
    8. 3,7,5,4,1
    9. ]
    10. input = torch.Tensor(input).view(1,1,5,5) #1,1,5,5 batch,channel,W,H
    11. conv_layer = torch.nn.Conv2d(1,1,kernel_size=3,stride=2,bias=False) #padding=1图像外面再补一圈0像素点
    12. kernel = torch.Tensor([1,2,3,4,5,6,7,8,9]).view(1,1,3,3) #1,1,3,3 output_channel, input_channel,W,H
    13. conv_layer.weight.data = kernel.data
    14. output = conv_layer(input)
    15. print(output)


     MaxPooling

    1. # MaxPooling
    2. import torch
    3. input = [
    4. 3,4,5,6,
    5. 2,4,6,8,
    6. 1,6,7,8,
    7. 9,7,4,6
    8. ]
    9. input = torch.Tensor(input).view(1,1,4,4)
    10. maxpooling_layer = torch.nn.MaxPool2d(kernel_size=2) #kernel_size=2默认步长为2
    11. output = maxpooling_layer(input)
    12. print(output)
    13. input2 = [
    14. 3,4,5,6,7,8,
    15. 2,4,6,8,5,6,
    16. 1,6,7,8,3,9,
    17. 9,7,4,6,5,5,
    18. 6,2,8,4,7,6,
    19. 8,7,8,3,9,8
    20. ]
    21. input2 = torch.Tensor(input2).view(1,1,6,6)
    22. maxpooling_layer = torch.nn.MaxPool2d(kernel_size=3)
    23. output2 = maxpooling_layer(input2)
    24. print(output2)


     

     用GPU跑的代码:

    1. import torch
    2. from torchvision import transforms
    3. from torchvision import datasets
    4. from torch.utils.data import DataLoader
    5. import torch.nn.functional as F
    6. import torch.optim as optim
    7. batch_size = 64
    8. transform = transforms.Compose([
    9. transforms.ToTensor(),
    10. transforms.Normalize((0.1307),(0.3081))
    11. ])
    12. train_dataset = datasets.MNIST(root='../dataset/mnist/',train=True,download=True,transform=transform)
    13. train_loader = DataLoader(train_dataset,shuffle = True,batch_size=batch_size)
    14. test_dataset = datasets.MNIST(root='../dataset/mnist/',train=False,download=True,transform=transform)
    15. test_loader = DataLoader(train_dataset,shuffle = False,batch_size=batch_size)
    16. class Net(torch.nn.Module):
    17. def __init__(self):
    18. super(Net, self).__init__()
    19. self.conv1 = torch.nn.Conv2d(1,10,kernel_size=5)
    20. self.conv2 = torch.nn.Conv2d(10,20,kernel_size=5) # input_channel , output_channel
    21. self.pooling = torch.nn.MaxPool2d(2)
    22. self.fc = torch.nn.Linear(320,10)
    23. def forward(self,x):
    24. batch_size = x.size(0)
    25. x = F.relu(self.pooling(self.conv1(x)))
    26. x = F.relu(self.pooling(self.conv2(x)))
    27. x = x.view(batch_size,-1)
    28. x = self.fc(x)
    29. return x #最后一层不做激活,不进行非线性变换
    30. model = Net()
    31. device = torch.device("cuda:0"if torch.cuda.is_available() else "cpu")
    32. model.to(device)
    33. criterion = torch.nn.CrossEntropyLoss()
    34. optimizer = optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
    35. def train(epoch):
    36. running_loss = 0.0
    37. for batch_idx,data in enumerate(train_loader,0):
    38. inputs, target = data
    39. inputs, target = inputs.to(device),target.to(device) #送到GPU
    40. optimizer.zero_grad()
    41. #forward + backward + update
    42. outputs = model(inputs)
    43. loss = criterion(outputs,target)
    44. loss.backward()
    45. optimizer.step()
    46. running_loss +=loss.item()
    47. if batch_idx % 300 ==299:
    48. print('[%d,%5d]loss:%.3f'%(epoch+1,batch_idx+1,running_loss/300))
    49. running_loss = 0
    50. def test():
    51. correct = 0
    52. total = 0
    53. with torch.no_grad():
    54. for data in test_loader:
    55. images,labels = data
    56. images, labels = images.to(device), labels.to(device) # 送到GPU
    57. outputs = model(images)
    58. _,predicted = torch.max(outputs.data,dim=1) #dim=1维度1,行是第0个维度,列是第1个维度
    59. total +=labels.size(0)
    60. correct +=(predicted==labels).sum().item()
    61. print('Accuracy on test set:%d %%'%(100*correct/total) )
    62. if __name__ == '__main__':
    63. for epoch in range(10):
    64. train(epoch)
    65. test()

    结果:

    [1,  300]loss:0.568
    [1,  600]loss:0.186
    [1,  900]loss:0.138
    Accuracy on test set:96 %
    [2,  300]loss:0.108
    [2,  600]loss:0.101
    [2,  900]loss:0.091
    Accuracy on test set:97 %
    [3,  300]loss:0.076
    [3,  600]loss:0.077
    [3,  900]loss:0.073
    Accuracy on test set:97 %
    [4,  300]loss:0.065
    [4,  600]loss:0.061
    [4,  900]loss:0.062
    Accuracy on test set:98 %
    [5,  300]loss:0.056
    [5,  600]loss:0.055
    [5,  900]loss:0.052
    Accuracy on test set:98 %
    [6,  300]loss:0.049
    [6,  600]loss:0.053
    [6,  900]loss:0.047
    Accuracy on test set:98 %
    [7,  300]loss:0.046
    [7,  600]loss:0.044
    [7,  900]loss:0.044
    Accuracy on test set:98 %
    [8,  300]loss:0.043
    [8,  600]loss:0.041
    [8,  900]loss:0.042
    Accuracy on test set:98 %
    [9,  300]loss:0.038
    [9,  600]loss:0.037
    [9,  900]loss:0.037
    Accuracy on test set:99 %
    [10,  300]loss:0.033
    [10,  600]loss:0.039
    [10,  900]loss:0.033
    Accuracy on test set:99 %

    Process finished with exit code 0
     

  • 相关阅读:
    MyBatisPlus创建新的Mapper.xml映射文件而不使用框架自带的?
    spring boot configuration annotation processor notconfigured解决方法
    【卷积神经网络:Inception模型】
    GCP认证考试之BigQuery专题
    【数据库系统概论】实验五 SQL数据库安全控制
    性能学习笔记--k8s下mysql的连接数分析和调优
    Kettle(二):连接SQL Server数据库
    算法设计与分析复习知识
    CVPR2022车道线检测SOTA工作CLRNet在Tusimple数据集测试demo,助力自动驾驶早日落地
    35岁危机来临前,程序员如何未雨绸缪?
  • 原文地址:https://blog.csdn.net/m0_65188455/article/details/126198680