• python与深度学习【初步尝试】


    学习资源来自b站,一点点手敲代码初步接触深度学习训练模型。感觉还是很神奇的!!

             将训练资源下载下来并通过训练模型来实现,本篇主要用来记录当时的一些代码和注释,方便后续回顾。

    1. ####################################### net.py ########################################
    2. import torch
    3. from torch import nn
    4. # 定义一个网络模型
    5. class MyLeNet5(nn.Module):
    6. # 初始化网络
    7. # 主要是复现LeNet-5
    8. def __init__(self):
    9. super(MyLeNet5, self).__init__()
    10. # 卷积层c1
    11. self.c1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5, padding=2)
    12. # 单纯单通道 so in=1,输出为6,约定俗成的卷积核是5,padding可以用公式算出来设置为2
    13. # 激活函数
    14. self.Sigmoid = nn.Sigmoid()
    15. # 平均池化(定义一个池化层) !注意! 池化层不改变通道大小,但是会改变特征图片的窗口大小
    16. self.s2 = nn.AvgPool2d(kernel_size=2, stride=2)
    17. # 卷积核为2,步长为2
    18. # 卷积层c3
    19. self.c3 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
    20. # 池化层s4
    21. self.s4 = nn.AvgPool2d(kernel_size=2, stride=2)
    22. # 卷积层c5
    23. self.c5 = nn.Conv2d(in_channels=16, out_channels=120, kernel_size=5)
    24. # 平展层
    25. self.flatten = nn.Flatten()
    26. # 设置线性连接层
    27. self.f6 = nn.Linear(120, 84)
    28. # 输入、输出
    29. self.output = nn.Linear(84, 10)
    30. def forward(self, x):
    31. # 用Sigmoid函数激活
    32. x = self.Sigmoid(self.c1(x))
    33. # 池化层
    34. x = self.s2(x)
    35. # 以此类推
    36. x = self.Sigmoid(self.c3(x))
    37. x = self.s4(x)
    38. x = self.c5(x)
    39. x = self.flatten(x)
    40. x = self.f6(x)
    41. x = self.output(x)
    42. return x
    43. if __name__ == "__main__":
    44. # 随机生成一个 批次1,通道1,大小是28*28 实例化
    45. x = torch.rand([1, 1, 28, 28])
    46. model = MyLeNet5()
    47. y = model(x)
    1. ######################################## test.py ########################################
    2. import torch
    3. from net import MyLeNet5
    4. from torch.autograd import Variable
    5. from torchvision import datasets, transforms
    6. from torchvision.transforms import ToPILImage
    7. # 将数据转化为tensor格式(数据是矩阵格式,要进行转化为tensor格式)
    8. data_transform = transforms.Compose([
    9. transforms.ToTensor()
    10. ])
    11. # 加载训练数据集
    12. train_dataset = datasets.MNIST(root='./data', train=True, transform=data_transform, download=True)
    13. train_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=16, shuffle=True)
    14. # 加载测试数据集
    15. test_dataset = datasets.MNIST(root='./data', train=False, transform=data_transform, download=True)
    16. test_dataloader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=16, shuffle=True)
    17. # 如果有显卡,转到GPU
    18. device = "cuda" if torch.cuda.is_available() else 'cpu'
    19. # 调用net里面定义的模型,将模型数据转到GPU
    20. model = MyLeNet5().to(device)
    21. model.load_state_dict(torch.load("C:/Users/79926/PycharmProjects/pythonProject1/save_model/best_model.pth"))
    22. # 获取结果
    23. classes = [
    24. "0",
    25. "1",
    26. "2",
    27. "3",
    28. "4",
    29. "5",
    30. "6",
    31. "7",
    32. "8",
    33. "9",
    34. ]
    35. # 把tensor转化为图片,方便可视化
    36. show = ToPILImage()
    37. # 进入验证
    38. for i in range(5):
    39. X, y = test_dataset[i][0], test_dataset[i][1]
    40. show(X).show()
    41. # 这里会显示出5张图片
    42. X = Variable(torch.unsqueeze(X, dim=0).float(), requires_grad=False).to(device)
    43. with torch.no_grad():
    44. pred = model(X)
    45. predicted, actual = classes[torch.argmax(pred[0])], classes[y]
    46. print(f'predicted:"{predicted}",actual:"{actual}"')
    1. ######################################## train.py ########################################
    2. import torch
    3. from torch import nn
    4. from net import MyLeNet5
    5. from torch.optim import lr_scheduler
    6. from torchvision import datasets, transforms
    7. import os
    8. # 将数据转化为tensor格式(数据是矩阵格式,要进行转化为tensor格式)
    9. data_transform = transforms.Compose([
    10. transforms.ToTensor()
    11. ])
    12. # 加载训练数据集
    13. train_dataset = datasets.MNIST(root='./data', train=True, transform=data_transform, download=True)
    14. train_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=16, shuffle=True)
    15. # 加载测试数据集
    16. test_dataset = datasets.MNIST(root='./data', train=False, transform=data_transform, download=True)
    17. test_dataloader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=16, shuffle=True)
    18. # 如果有显卡,转到GPU
    19. device = "cuda" if torch.cuda.is_available() else 'cpu'
    20. # 调用net里面定义的模型,将模型数据转到GPU
    21. model = MyLeNet5().to(device)
    22. # 定义一个损失函数(交叉熵损失)
    23. loss_fn = nn.CrossEntropyLoss()
    24. # 定义一个优化器
    25. # (梯度下降)
    26. optimizer = torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.9)
    27. # 学习率每隔10轮变为原来的0.1
    28. lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
    29. # 定义训练函数
    30. def train(dataloader, model, loss_fn, optimizer):
    31. loss, current, n = 0.0, 0.0, 0
    32. for batch, (X, y) in enumerate(dataloader):
    33. # 前向传播
    34. X, y = X.to(device), y.to(device)
    35. output = model(X)
    36. # 损失函数(用来反向传播)
    37. cur_loss = loss_fn(output, y)
    38. _, pred = torch.max(output, axis=1)
    39. # 计算精确度(累加->一轮的)
    40. cur_acc = torch.sum(y == pred) / output.shape[0]
    41. optimizer.zero_grad()
    42. cur_loss.backward()
    43. optimizer.step()
    44. loss += cur_loss.item()
    45. current += cur_acc.item()
    46. n = n + 1
    47. print("train_loss" + str(loss / n))
    48. print("train_acc" + str(current / n))
    49. def val(dataloader, model, loss_fn):
    50. model.eval()
    51. loss, current, n = 0.0, 0.0, 0
    52. with torch.no_grad():
    53. for batch, (X, y) in enumerate(dataloader):
    54. # 前向传播
    55. X, y = X.to(device), y.to(device)
    56. output = model(X)
    57. # 损失函数(用来反向传播)
    58. cur_loss = loss_fn(output, y)
    59. _, pred = torch.max(output, axis=1)
    60. cur_acc = torch.sum(y == pred) / output.shape[0]
    61. loss += cur_loss.item()
    62. current += cur_acc.item()
    63. n = n + 1
    64. print("val_loss" + str(loss / n))
    65. print("val_acc" + str(current / n))
    66. return current/n
    67. # 开始训练
    68. epoch = 50
    69. min_acc = 0
    70. for t in range(epoch):
    71. print(f'epoch{t + 1}\n--------------')
    72. train(train_dataloader, model, loss_fn, optimizer)
    73. a=val(test_dataloader, model, loss_fn)
    74. #保存最好模型权重
    75. if a>min_acc:
    76. folder = 'save_model'
    77. if not os.path.exists(folder):
    78. os.mkdir('save_model')
    79. min_acc = a
    80. print('save best model')
    81. torch.save(model.state_dict(),'save_model/best_model.pth')
    82. print('Done!')

    附:该up主视频资源:(讲的很棒)

    网络模型搭建_哔哩哔哩_bilibili

    训练模型搭建_哔哩哔哩_bilibili

    测试模型搭建_哔哩哔哩_bilibili

  • 相关阅读:
    通用FIFO设计深度8宽度64,verilog仿真,源码和视频
    回放线上流量利器-GoReplay
    DAO:“动态仲裁”能否解决投票冷漠问题?
    手机端布局页面写法
    AIOT数字孪生智慧工地一体化管理平台源码
    某大厂软件测试岗一面笔试题+二面问答题面试经验分享
    c# 多线程创建及线程同步
    MySQL-内置函数
    vim编辑器
    大学毕业五年的经历与思考
  • 原文地址:https://blog.csdn.net/qq_52183449/article/details/132658352