You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

03-AlexNet.ipynb 5.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "# AlexNet\n",
  8. "\n",
  9. "\n",
  10. "第一个典型的卷积神经网络是 LeNet5 ,但是第一个开启深度学习的网络却是 AlexNet,这个网络在2012年的ImageNet竞赛中取得冠军。这网络提出了深度学习常用的技术:ReLU和Dropout。AlexNet网络结构在整体上类似于LeNet,都是先卷积然后在全连接,但在细节上有很大不同,AlexNet更为复杂,Alexnet模型由5个卷积层和3个池化Pooling层,其中还有3个全连接层构成,共有$6 \\times 10^7$个参数和65000个神经元,最终的输出层是1000通道的Softmax。AlexNet 跟 LeNet 结构类似,但使⽤了更多的卷积层和更⼤的参数空间来拟合⼤规模数据集 ImageNet,它是浅层神经⽹络和深度神经⽹络的分界线。\n"
  11. ]
  12. },
  13. {
  14. "cell_type": "code",
  15. "execution_count": 1,
  16. "metadata": {},
  17. "outputs": [],
  18. "source": [
  19. "import torch.nn as nn\n",
  20. "import torch\n",
  21. "\n",
  22. "class AlexNet(nn.Module):\n",
  23. " def __init__(self, num_classes=1000, init_weights=False): \n",
  24. " super(AlexNet, self).__init__()\n",
  25. " self.features = nn.Sequential( \n",
  26. " nn.Conv2d(1, 96, kernel_size=11, stride=4, padding=2), \n",
  27. " nn.ReLU(inplace=True), #inplace 可以载入更大模型\n",
  28. " nn.MaxPool2d(kernel_size=3, stride=2), \n",
  29. "\n",
  30. " nn.Conv2d(96, 256, kernel_size=5, padding=2),\n",
  31. " nn.ReLU(inplace=True),\n",
  32. " nn.MaxPool2d(kernel_size=3, stride=2),\n",
  33. "\n",
  34. " nn.Conv2d(256, 384, kernel_size=3, padding=1),\n",
  35. " nn.ReLU(inplace=True),\n",
  36. "\n",
  37. " nn.Conv2d(384, 384, kernel_size=3, padding=1),\n",
  38. " nn.ReLU(inplace=True),\n",
  39. "\n",
  40. " nn.Conv2d(384, 256, kernel_size=3, padding=1),\n",
  41. " nn.ReLU(inplace=True),\n",
  42. " nn.MaxPool2d(kernel_size=3, stride=2),\n",
  43. " )\n",
  44. " self.classifier = nn.Sequential(\n",
  45. " nn.Dropout(p=0.5),\n",
  46. " nn.Linear(256*6*6, 4096), #全链接\n",
  47. " nn.ReLU(inplace=True),\n",
  48. " nn.Dropout(p=0.5),\n",
  49. " nn.Linear(4096, 4096),\n",
  50. " nn.ReLU(inplace=True),\n",
  51. " nn.Linear(4096, num_classes),\n",
  52. " )\n",
  53. " if init_weights:\n",
  54. " self._initialize_weights()\n",
  55. "\n",
  56. " def forward(self, x):\n",
  57. " x = self.features(x)\n",
  58. " x = torch.flatten(x, start_dim=1) #展平或者view()\n",
  59. " x = self.classifier(x)\n",
  60. " return x\n",
  61. "\n",
  62. " def _initialize_weights(self):\n",
  63. " for m in self.modules():\n",
  64. " if isinstance(m, nn.Conv2d):\n",
  65. " #何教授方法\n",
  66. " nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') \n",
  67. " if m.bias is not None:\n",
  68. " nn.init.constant_(m.bias, 0)\n",
  69. " elif isinstance(m, nn.Linear):\n",
  70. " #正态分布赋值\n",
  71. " nn.init.normal_(m.weight, 0, 0.01) \n",
  72. " nn.init.constant_(m.bias, 0)"
  73. ]
  74. },
  75. {
  76. "cell_type": "code",
  77. "execution_count": 2,
  78. "metadata": {},
  79. "outputs": [],
  80. "source": [
  81. "from torchvision.datasets import CIFAR10\n",
  82. "from torch.utils.data import DataLoader\n",
  83. "from torchvision import transforms as tfs\n",
  84. "from utils import train\n",
  85. "\n",
  86. "\n",
  87. "# 数据转换\n",
  88. "def data_tf(x):\n",
  89. " im_aug = tfs.Compose([\n",
  90. " tfs.Resize(227),\n",
  91. " tfs.ToTensor(),\n",
  92. " tfs.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n",
  93. " ])\n",
  94. " x = im_aug(x)\n",
  95. " return x\n",
  96. " \n",
  97. "train_set = CIFAR10('../../data', train=True, transform=data_tf)\n",
  98. "train_data = torch.utils.data.DataLoader(train_set, batch_size=64, shuffle=True)\n",
  99. "test_set = CIFAR10('../../data', train=False, transform=data_tf)\n",
  100. "test_data = torch.utils.data.DataLoader(test_set, batch_size=128, shuffle=False)"
  101. ]
  102. },
  103. {
  104. "cell_type": "code",
  105. "execution_count": null,
  106. "metadata": {},
  107. "outputs": [],
  108. "source": [
  109. "net = AlexNet(num_classes=10)\n",
  110. "optimizer = torch.optim.Adam(net.parameters(), lr=1e-3)\n",
  111. "criterion = nn.CrossEntropyLoss()\n",
  112. "\n",
  113. "res = train(net, train_data, test_data, 20, optimizer, criterion, use_cuda=False)"
  114. ]
  115. },
  116. {
  117. "cell_type": "code",
  118. "execution_count": null,
  119. "metadata": {},
  120. "outputs": [],
  121. "source": [
  122. "import matplotlib.pyplot as plt\n",
  123. "%matplotlib inline\n",
  124. "\n",
  125. "plt.plot(res[0], label='train')\n",
  126. "plt.plot(res[2], label='valid')\n",
  127. "plt.xlabel('epoch')\n",
  128. "plt.ylabel('Loss')\n",
  129. "plt.legend(loc='best')\n",
  130. "plt.savefig('fig-res-alexnet-train-validate-loss.pdf')\n",
  131. "plt.show()\n",
  132. "\n",
  133. "plt.plot(res[1], label='train')\n",
  134. "plt.plot(res[3], label='valid')\n",
  135. "plt.xlabel('epoch')\n",
  136. "plt.ylabel('Acc')\n",
  137. "plt.legend(loc='best')\n",
  138. "plt.savefig('fig-res-alexnet-train-validate-acc.pdf')\n",
  139. "plt.show()"
  140. ]
  141. }
  142. ],
  143. "metadata": {
  144. "kernelspec": {
  145. "display_name": "Python 3",
  146. "language": "python",
  147. "name": "python3"
  148. },
  149. "language_info": {
  150. "codemirror_mode": {
  151. "name": "ipython",
  152. "version": 3
  153. },
  154. "file_extension": ".py",
  155. "mimetype": "text/x-python",
  156. "name": "python",
  157. "nbconvert_exporter": "python",
  158. "pygments_lexer": "ipython3",
  159. "version": "3.7.9"
  160. }
  161. },
  162. "nbformat": 4,
  163. "nbformat_minor": 2
  164. }

机器学习越来越多应用到飞行器、机器人等领域,其目的是利用计算机实现类似人类的智能,从而实现装备的智能化与无人化。本课程旨在引导学生掌握机器学习的基本知识、典型方法与技术,通过具体的应用案例激发学生对该学科的兴趣,鼓励学生能够从人工智能的角度来分析、解决飞行器、机器人所面临的问题和挑战。本课程主要内容包括Python编程基础,机器学习模型,无监督学习、监督学习、深度学习基础知识与实现,并学习如何利用机器学习解决实际问题,从而全面提升自我的《综合能力》。