动手学深度学习(一)——基本介绍

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是学习李沐直播课程的笔记。视频及内容的具体地址可参考:https://zhuanlan.zhihu.com/p/29125290

第一课:从上手到多类分类

课程首先介绍了深度学习的很多应用:例如增强学习、物体识别、语音识别、机器翻译、推荐系统、广告点击预测等。

课程目的:通过动手实现来理解深度学习,跟工业界应用相比,主要只是数据规模和模型复杂度的区别。

深度学习的轮子很多,例如Caffe,TensorFlow,mxnet,PyTorch,CNTK等。它们之间的主要区别在于:1.便利的开发;2.方便的部署。

Figure 1

mxnet之上的一个package是Gluon,主要目的是一次解决开发和部署。课程主要分为以下三个部分:

Figure 2

1. 环境配置

我的配置环境是Mac,Linux平台类似。

mxnet安装命令如下,前提是已经安装好了Anaconda,Anaconda的安装可以参考官网:

1
pip install mxnet

测试mxnet:

1
2
3
>>> import mxnet
>>> print mxnet.__version__
0.11.0

然后安装notedown,运行Jupyter并加载notedown插件:

1
2
pip install https://github.com/mli/notedown/tarball/master
jupyter notebook --NotebookApp.contents_manager_class='notedown.NotedownContentsManager'

通过ExecutionTime插件来对每个cell的运行计时,国内使用豆瓣源。

1
2
3
pip install jupyter_contrib_nbextensions -i https://pypi.douban.com/simple
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime

2. NDArray

NDArray是MXNet储存和变换数据的主要工具,它与numpy非常类似。NDArray提供了CPU和GPU的异步计算,还提供了自动求导。NDArray的基本用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from mxnet import ndarray as nd

# 创建矩阵
nd.zeros((3, 4))
x = nd.ones((3, 4))
nd.array([[1,2],[2,3]])
y = nd.random_normal(0, 1, shape=(3, 4))

# 查看矩阵大小
y.shape

# 查看矩阵元素个数
y.size

# 矩阵加法
x + y

# 矩阵乘法
x * y

# 指数运算
nd.exp(y)

# 矩阵乘法
nd.dot(x, y.T)

# 广播操作
a = nd.arange(3).reshape((3,1))
b = nd.arange(2).reshape((1,2))
print('a:', a)
print('b:', b)
print('a+b:', a+b)

# NDArray与Numpy的转换
import numpy as np
x = np.ones((2,3))
y = nd.array(x) # numpy -> mxnet
z = y.asnumpy() # mxnet -> numpy
print([z, y])

NDArray的自动求导:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import mxnet.ndarray as nd
import mxnet.autograd as ag


# 定义矩阵
x = nd.array([[1, 2], [3, 4]])

# 添加自动求导
x.attach_grad()


# 记录x的变化
with ag.record():
y = x * 2
z = y * x

# 求导
z.backward()

# 判断导数是否相等
x.grad == 4*x
如果有收获,可以请我喝杯咖啡!