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.

5-param_initialize.ipynb 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "# 参数初始化\n",
  8. "参数初始化对模型具有较大的影响,不同的初始化方式可能会导致截然不同的结果,所幸的是很多深度学习的先驱们已经帮我们探索了各种各样的初始化方式,所以我们只需要学会如何对模型的参数进行初始化的赋值即可。"
  9. ]
  10. },
  11. {
  12. "cell_type": "markdown",
  13. "metadata": {},
  14. "source": [
  15. "PyTorch 的初始化方式并没有那么显然,如果你使用最原始的方式创建模型,那么你需要定义模型中的所有参数,当然这样你可以非常方便地定义每个变量的初始化方式,但是对于复杂的模型,这并不容易,而且我们推崇使用 Sequential 和 Module 来定义模型,所以这个时候我们就需要知道如何来自定义初始化方式"
  16. ]
  17. },
  18. {
  19. "cell_type": "markdown",
  20. "metadata": {},
  21. "source": [
  22. "## 使用 NumPy 来初始化\n",
  23. "因为 PyTorch 是一个非常灵活的框架,理论上能够对所有的 Tensor 进行操作,所以我们能够通过定义新的 Tensor 来初始化,直接看下面的例子"
  24. ]
  25. },
  26. {
  27. "cell_type": "code",
  28. "execution_count": 1,
  29. "metadata": {},
  30. "outputs": [],
  31. "source": [
  32. "import numpy as np\n",
  33. "import torch\n",
  34. "from torch import nn"
  35. ]
  36. },
  37. {
  38. "cell_type": "code",
  39. "execution_count": 2,
  40. "metadata": {},
  41. "outputs": [],
  42. "source": [
  43. "# 定义一个 Sequential 模型\n",
  44. "net1 = nn.Sequential(\n",
  45. " nn.Linear(30, 40),\n",
  46. " nn.ReLU(),\n",
  47. " nn.Linear(40, 50),\n",
  48. " nn.ReLU(),\n",
  49. " nn.Linear(50, 10)\n",
  50. ")"
  51. ]
  52. },
  53. {
  54. "cell_type": "code",
  55. "execution_count": 3,
  56. "metadata": {},
  57. "outputs": [],
  58. "source": [
  59. "# 访问第一层的参数\n",
  60. "w1 = net1[0].weight\n",
  61. "b1 = net1[0].bias"
  62. ]
  63. },
  64. {
  65. "cell_type": "code",
  66. "execution_count": 4,
  67. "metadata": {},
  68. "outputs": [
  69. {
  70. "name": "stdout",
  71. "output_type": "stream",
  72. "text": [
  73. "Parameter containing:\n",
  74. "tensor([[-0.0784, 0.1559, 0.0451, ..., 0.0432, 0.0325, -0.0626],\n",
  75. " [ 0.0436, 0.0976, 0.1529, ..., -0.1601, -0.1227, -0.0831],\n",
  76. " [ 0.0890, 0.0343, 0.1744, ..., -0.0332, 0.0897, 0.0002],\n",
  77. " ...,\n",
  78. " [-0.1447, -0.0411, -0.0851, ..., 0.0117, 0.1457, 0.0585],\n",
  79. " [ 0.1642, 0.0744, -0.1118, ..., 0.0623, -0.0591, 0.0512],\n",
  80. " [-0.1610, 0.0070, 0.0184, ..., -0.1529, -0.0314, 0.1748]],\n",
  81. " requires_grad=True)\n"
  82. ]
  83. }
  84. ],
  85. "source": [
  86. "print(w1)"
  87. ]
  88. },
  89. {
  90. "cell_type": "markdown",
  91. "metadata": {},
  92. "source": [
  93. "注意,这是一个 Parameter,也就是一个特殊的 Variable,我们可以访问其 `.data`属性得到其中的数据,然后直接定义一个新的 Tensor 对其进行替换,我们可以使用 PyTorch 中的一些随机数据生成的方式,比如 `torch.randn`,如果要使用更多 PyTorch 中没有的随机化方式,可以使用 numpy"
  94. ]
  95. },
  96. {
  97. "cell_type": "code",
  98. "execution_count": 5,
  99. "metadata": {},
  100. "outputs": [],
  101. "source": [
  102. "# 定义一个 Tensor 直接对其进行替换\n",
  103. "net1[0].weight.data = torch.from_numpy(np.random.uniform(3, 5, size=(40, 30)))"
  104. ]
  105. },
  106. {
  107. "cell_type": "code",
  108. "execution_count": 6,
  109. "metadata": {},
  110. "outputs": [
  111. {
  112. "name": "stdout",
  113. "output_type": "stream",
  114. "text": [
  115. "Parameter containing:\n",
  116. "tensor([[3.5493, 3.2984, 4.3041, ..., 4.5181, 3.7561, 4.5633],\n",
  117. " [4.4523, 3.7956, 3.7448, ..., 3.5031, 3.9477, 4.8617],\n",
  118. " [3.5174, 4.1082, 4.6358, ..., 3.5759, 4.5291, 3.9545],\n",
  119. " ...,\n",
  120. " [3.6757, 4.2100, 3.9763, ..., 3.2017, 3.4422, 4.0191],\n",
  121. " [3.0283, 3.8147, 3.1705, ..., 3.9442, 4.1054, 4.9491],\n",
  122. " [3.5879, 3.7237, 4.0656, ..., 3.2279, 3.1818, 4.7489]],\n",
  123. " dtype=torch.float64, requires_grad=True)\n"
  124. ]
  125. }
  126. ],
  127. "source": [
  128. "print(net1[0].weight)"
  129. ]
  130. },
  131. {
  132. "cell_type": "markdown",
  133. "metadata": {},
  134. "source": [
  135. "可以看到这个参数的值已经被改变了,也就是说已经被定义成了我们需要的初始化方式,如果模型中某一层需要我们手动去修改,那么我们可以直接用这种方式去访问,但是更多的时候是模型中相同类型的层都需要初始化成相同的方式,这个时候一种更高效的方式是使用循环去访问,比如"
  136. ]
  137. },
  138. {
  139. "cell_type": "code",
  140. "execution_count": 7,
  141. "metadata": {},
  142. "outputs": [],
  143. "source": [
  144. "for layer in net1:\n",
  145. " if isinstance(layer, nn.Linear): # 判断是否是线性层\n",
  146. " param_shape = layer.weight.shape\n",
  147. " layer.weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape)) \n",
  148. " # 定义为均值为 0,方差为 0.5 的正态分布"
  149. ]
  150. },
  151. {
  152. "cell_type": "markdown",
  153. "metadata": {},
  154. "source": [
  155. "**小练习:一种非常流行的初始化方式叫 Xavier,方法来源于 2010 年的一篇论文 [Understanding the difficulty of training deep feedforward neural networks](http://proceedings.mlr.press/v9/glorot10a.html),其通过数学的推到,证明了这种初始化方式可以使得每一层的输出方差是尽可能相等的,有兴趣的同学可以去看看论文**\n",
  156. "\n",
  157. "我们给出这种初始化的公式\n",
  158. "\n",
  159. "$$\n",
  160. "w\\ \\sim \\ Uniform[- \\frac{\\sqrt{6}}{\\sqrt{n_j + n_{j+1}}}, \\frac{\\sqrt{6}}{\\sqrt{n_j + n_{j+1}}}]\n",
  161. "$$\n",
  162. "\n",
  163. "其中 $n_j$ 和 $n_{j+1}$ 表示该层的输入和输出数目,所以请尝试实现以下这种初始化方式"
  164. ]
  165. },
  166. {
  167. "cell_type": "markdown",
  168. "metadata": {},
  169. "source": [
  170. "对于 Module 的参数初始化,其实也非常简单,如果想对其中的某层进行初始化,可以直接像 Sequential 一样对其 Tensor 进行重新定义,其唯一不同的地方在于,如果要用循环的方式访问,需要介绍两个属性,children 和 modules,下面我们举例来说明"
  171. ]
  172. },
  173. {
  174. "cell_type": "code",
  175. "execution_count": 8,
  176. "metadata": {},
  177. "outputs": [],
  178. "source": [
  179. "class sim_net(nn.Module):\n",
  180. " def __init__(self):\n",
  181. " super(sim_net, self).__init__()\n",
  182. " self.l1 = nn.Sequential(\n",
  183. " nn.Linear(30, 40),\n",
  184. " nn.ReLU()\n",
  185. " )\n",
  186. " \n",
  187. " self.l1[0].weight.data = torch.randn(40, 30) # 直接对某一层初始化\n",
  188. " \n",
  189. " self.l2 = nn.Sequential(\n",
  190. " nn.Linear(40, 50),\n",
  191. " nn.ReLU()\n",
  192. " )\n",
  193. " \n",
  194. " self.l3 = nn.Sequential(\n",
  195. " nn.Linear(50, 10),\n",
  196. " nn.ReLU()\n",
  197. " )\n",
  198. " \n",
  199. " def forward(self, x):\n",
  200. " x = self.l1(x)\n",
  201. " x =self.l2(x)\n",
  202. " x = self.l3(x)\n",
  203. " return x"
  204. ]
  205. },
  206. {
  207. "cell_type": "code",
  208. "execution_count": 9,
  209. "metadata": {},
  210. "outputs": [],
  211. "source": [
  212. "net2 = sim_net()"
  213. ]
  214. },
  215. {
  216. "cell_type": "code",
  217. "execution_count": 10,
  218. "metadata": {},
  219. "outputs": [
  220. {
  221. "name": "stdout",
  222. "output_type": "stream",
  223. "text": [
  224. "Sequential(\n",
  225. " (0): Linear(in_features=30, out_features=40, bias=True)\n",
  226. " (1): ReLU()\n",
  227. ")\n",
  228. "Sequential(\n",
  229. " (0): Linear(in_features=40, out_features=50, bias=True)\n",
  230. " (1): ReLU()\n",
  231. ")\n",
  232. "Sequential(\n",
  233. " (0): Linear(in_features=50, out_features=10, bias=True)\n",
  234. " (1): ReLU()\n",
  235. ")\n"
  236. ]
  237. }
  238. ],
  239. "source": [
  240. "# 访问 children\n",
  241. "for i in net2.children():\n",
  242. " print(i)"
  243. ]
  244. },
  245. {
  246. "cell_type": "code",
  247. "execution_count": 11,
  248. "metadata": {},
  249. "outputs": [
  250. {
  251. "name": "stdout",
  252. "output_type": "stream",
  253. "text": [
  254. "sim_net(\n",
  255. " (l1): Sequential(\n",
  256. " (0): Linear(in_features=30, out_features=40, bias=True)\n",
  257. " (1): ReLU()\n",
  258. " )\n",
  259. " (l2): Sequential(\n",
  260. " (0): Linear(in_features=40, out_features=50, bias=True)\n",
  261. " (1): ReLU()\n",
  262. " )\n",
  263. " (l3): Sequential(\n",
  264. " (0): Linear(in_features=50, out_features=10, bias=True)\n",
  265. " (1): ReLU()\n",
  266. " )\n",
  267. ")\n",
  268. "Sequential(\n",
  269. " (0): Linear(in_features=30, out_features=40, bias=True)\n",
  270. " (1): ReLU()\n",
  271. ")\n",
  272. "Linear(in_features=30, out_features=40, bias=True)\n",
  273. "ReLU()\n",
  274. "Sequential(\n",
  275. " (0): Linear(in_features=40, out_features=50, bias=True)\n",
  276. " (1): ReLU()\n",
  277. ")\n",
  278. "Linear(in_features=40, out_features=50, bias=True)\n",
  279. "ReLU()\n",
  280. "Sequential(\n",
  281. " (0): Linear(in_features=50, out_features=10, bias=True)\n",
  282. " (1): ReLU()\n",
  283. ")\n",
  284. "Linear(in_features=50, out_features=10, bias=True)\n",
  285. "ReLU()\n"
  286. ]
  287. }
  288. ],
  289. "source": [
  290. "# 访问 modules\n",
  291. "for i in net2.modules():\n",
  292. " print(i)"
  293. ]
  294. },
  295. {
  296. "cell_type": "markdown",
  297. "metadata": {},
  298. "source": [
  299. "通过上面的例子,看到区别了吗?\n",
  300. "\n",
  301. "children 只会访问到模型定义中的第一层,因为上面的模型中定义了三个 Sequential,所以只会访问到三个 Sequential,而 modules 会访问到最后的结构,比如上面的例子,modules 不仅访问到了 Sequential,也访问到了 Sequential 里面,这就对我们做初始化非常方便,比如"
  302. ]
  303. },
  304. {
  305. "cell_type": "code",
  306. "execution_count": 12,
  307. "metadata": {},
  308. "outputs": [],
  309. "source": [
  310. "for layer in net2.modules():\n",
  311. " if isinstance(layer, nn.Linear):\n",
  312. " param_shape = layer.weight.shape\n",
  313. " layer.weight.data = torch.from_numpy(np.random.normal(0, 0.5, size=param_shape)) "
  314. ]
  315. },
  316. {
  317. "cell_type": "markdown",
  318. "metadata": {},
  319. "source": [
  320. "这上面实现了和 Sequential 相同的初始化,同样非常简便"
  321. ]
  322. },
  323. {
  324. "cell_type": "markdown",
  325. "metadata": {},
  326. "source": [
  327. "## torch.nn.init\n",
  328. "因为 PyTorch 灵活的特性,我们可以直接对 Tensor 进行操作从而初始化,PyTorch 也提供了初始化的函数帮助我们快速初始化,就是 `torch.nn.init`,其操作层面仍然在 Tensor 上,下面我们举例说明"
  329. ]
  330. },
  331. {
  332. "cell_type": "code",
  333. "execution_count": 13,
  334. "metadata": {},
  335. "outputs": [],
  336. "source": [
  337. "from torch.nn import init"
  338. ]
  339. },
  340. {
  341. "cell_type": "code",
  342. "execution_count": 14,
  343. "metadata": {},
  344. "outputs": [
  345. {
  346. "name": "stdout",
  347. "output_type": "stream",
  348. "text": [
  349. "Parameter containing:\n",
  350. "tensor([[ 0.2725, -0.2262, -0.4229, ..., -0.2451, 0.2344, 0.1583],\n",
  351. " [ 0.1886, 0.3226, -0.5023, ..., -0.2228, 0.5089, -0.6994],\n",
  352. " [-0.4689, 0.2612, 0.3464, ..., -0.0423, -0.2999, -0.5813],\n",
  353. " ...,\n",
  354. " [ 0.4200, 0.2091, -0.3690, ..., 0.4142, 0.1120, 0.0771],\n",
  355. " [ 0.6540, 0.0475, 0.0594, ..., 0.1726, -0.2264, 0.1510],\n",
  356. " [-1.0729, -0.2862, 0.4953, ..., 0.4702, 0.5555, -0.2246]],\n",
  357. " dtype=torch.float64, requires_grad=True)\n"
  358. ]
  359. }
  360. ],
  361. "source": [
  362. "print(net1[0].weight)"
  363. ]
  364. },
  365. {
  366. "cell_type": "code",
  367. "execution_count": 16,
  368. "metadata": {},
  369. "outputs": [
  370. {
  371. "data": {
  372. "text/plain": [
  373. "Parameter containing:\n",
  374. "tensor([[ 0.1173, -0.0864, 0.1008, ..., -0.1053, 0.2642, -0.1045],\n",
  375. " [-0.0244, 0.1722, 0.1330, ..., 0.2443, -0.2385, 0.1613],\n",
  376. " [-0.1767, 0.0678, 0.1282, ..., 0.1033, -0.2423, -0.0864],\n",
  377. " ...,\n",
  378. " [-0.1673, -0.1338, -0.0839, ..., 0.0267, 0.1693, -0.2911],\n",
  379. " [ 0.2146, 0.0194, 0.2873, ..., 0.1486, 0.2775, 0.2740],\n",
  380. " [-0.0400, 0.2231, 0.0800, ..., 0.2804, 0.2121, 0.2764]],\n",
  381. " dtype=torch.float64, requires_grad=True)"
  382. ]
  383. },
  384. "execution_count": 16,
  385. "metadata": {},
  386. "output_type": "execute_result"
  387. }
  388. ],
  389. "source": [
  390. "init.xavier_uniform_(net1[0].weight) # 这就是上面我们讲过的 Xavier 初始化方法,PyTorch 直接内置了其实现"
  391. ]
  392. },
  393. {
  394. "cell_type": "code",
  395. "execution_count": 17,
  396. "metadata": {},
  397. "outputs": [
  398. {
  399. "name": "stdout",
  400. "output_type": "stream",
  401. "text": [
  402. "Parameter containing:\n",
  403. "tensor([[ 0.1173, -0.0864, 0.1008, ..., -0.1053, 0.2642, -0.1045],\n",
  404. " [-0.0244, 0.1722, 0.1330, ..., 0.2443, -0.2385, 0.1613],\n",
  405. " [-0.1767, 0.0678, 0.1282, ..., 0.1033, -0.2423, -0.0864],\n",
  406. " ...,\n",
  407. " [-0.1673, -0.1338, -0.0839, ..., 0.0267, 0.1693, -0.2911],\n",
  408. " [ 0.2146, 0.0194, 0.2873, ..., 0.1486, 0.2775, 0.2740],\n",
  409. " [-0.0400, 0.2231, 0.0800, ..., 0.2804, 0.2121, 0.2764]],\n",
  410. " dtype=torch.float64, requires_grad=True)\n"
  411. ]
  412. }
  413. ],
  414. "source": [
  415. "print(net1[0].weight)"
  416. ]
  417. },
  418. {
  419. "cell_type": "markdown",
  420. "metadata": {},
  421. "source": [
  422. "可以看到参数已经被修改了\n",
  423. "\n",
  424. "`torch.nn.init` 为我们提供了更多的内置初始化方式,避免了我们重复去实现一些相同的操作"
  425. ]
  426. },
  427. {
  428. "cell_type": "markdown",
  429. "metadata": {},
  430. "source": [
  431. "上面讲了两种初始化方式,其实它们的本质都是一样的,就是去修改某一层参数的实际值,而 `torch.nn.init` 提供了更多成熟的深度学习相关的初始化方式,非常方便\n",
  432. "\n",
  433. "下一节课,我们将讲一下目前流行的各种基于梯度的优化算法"
  434. ]
  435. }
  436. ],
  437. "metadata": {
  438. "kernelspec": {
  439. "display_name": "Python 3 (ipykernel)",
  440. "language": "python",
  441. "name": "python3"
  442. },
  443. "language_info": {
  444. "codemirror_mode": {
  445. "name": "ipython",
  446. "version": 3
  447. },
  448. "file_extension": ".py",
  449. "mimetype": "text/x-python",
  450. "name": "python",
  451. "nbconvert_exporter": "python",
  452. "pygments_lexer": "ipython3",
  453. "version": "3.9.7"
  454. }
  455. },
  456. "nbformat": 4,
  457. "nbformat_minor": 2
  458. }

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