四天速成!香港科技大学 PyTorch 课件分享

 

前天,香港科技大学计算机系教授 Sung Kim 在 Google Drive 分享了一个 3 天速成的TensorFlow 极简入门教程;接着,他在 GitHub 上又分享了一个 3 至 4 日的速成教程,教大家如何使用 PyTorch 进行机器学习/深度学习。Sung Kim 共享了该教程的代码和 PPT 资源,机器之心对其做了扼要介绍。资源链接请见文中。

 

  • 代码:https://github.com/hunkim/PyTorchZeroToAll

  • PPT:http://bit.ly/PyTorchZeroAll

  • 百度云盘:https://pan.baidu.com/s/1cpoyXw

 

PyTorch 开源于今年一月份,它是使用 GPU 和 CPU 优化的深度学习张量库,也是一个 Python 工具包,为目前最流行的深度学习框架之一;它具有两个高阶功能:

 

 

  • 带有强大的 GPU 加速的张量计算(类似 NumPy)

  • 构建在基于 tape 的 autograd 系统之上的深度神经网络

 

因此必要之时你可以再利用 Python 工具包比如 NumPy、SciPy 和 Cython 扩展 PyTorch。PyTorch 目前处于早期的 beta 版,还有待进一步完善与更新。通常来讲,PyTorch 作为库主要包含以下组件:

 

1. Torch:类似于 NumPy 的张量库,带有强大的 GPU 支持

2. torch.autograd:一个基于 tape 的自动微分库,支持 torch 中的所有的微分张量运算

3. torch.nn:一个专为最大灵活性而设计、与 autograd 深度整合的神经网络库

4. torch.multiprocessing:Python 多运算,但在运算中带有惊人的 torch 张量内存共享。这对数据加载和 Hogwild 训练很有帮助。

5. torch.utils:数据加载器、训练器以及其他便利的实用功能

6. torch.legacy(.nn/.optim):出于后向兼容性原因而从 torch 移植而来的旧代码

 

人们使用 PyTorch 一般出于两个目的:

 

  • 代替 NumPy 从而可以使用强大的 GPU

  • PyTorch 作为深度学习研究平台提供了最大的灵活性与速度

     

 

PyTorch 是由若干个资深工程师和研究者共同发起的社区项目,目前主要的维护人员有 Adam Paszke、Sam Gross、Soumith Chintala 和 Gregory Chanan。

 

PyTorch 课程目录

 

  • 概览

  • 线性模型

  • 梯度下降

  • 反向传播

  • PyTorch 线性回归

  • Logistic 回归

  • 宽&深

  • 数据加载器

  • Softmax 分类器

  • CNN

  • RNN

 

下面是整个课程的概述:

 

线性模型

 

如下为线性模型的基本思想,我们希望能构建一个线性方程拟合现存的数据点。该线性了方程函数将根据数据点与其距离自动调整权重,权重调整的方法即使用优化算法最小化真实数据与预测数据的距离。

以下为该线性模型的实现代码,我们先定义特征 x 与标注 y,然后将预测值与真实值差的平方作为损失函数。随后初始化模型权重并开始前向传播。

 

 
  1. import numpy as np

  2. import matplotlib.pyplot as plt

  3.  

  4. x_data = [1.0, 2.0, 3.0]

  5. y_data = [2.0, 4.0, 6.0]

  6.  

  7.  

  8. # our model forward pass

  9. def forward(x):

  10.    return x * w

  11.  

  12.  

  13. # Loss function

  14. def loss(x, y):

  15.    y_pred = forward(x)

  16.    return (y_pred - y) * (y_pred - y)

  17.  

  18.  

  19. w_list = []

  20. mse_list = []

  21.  

  22. for w in np.arange(0.0, 4.1, 0.1):

  23.    print("w=", w)

  24.    l_sum = 0

  25.    for x_val, y_val in zip(x_data, y_data):

  26.        y_pred_val = forward(x_val)

  27.        l = loss(x_val, y_val)

  28.        l_sum += l

  29.        print("\t", x_val, y_val, y_pred_val, l)

  30.    print("NSE=", l_sum / 3)

  31.    w_list.append(w)

  32.    mse_list.append(l_sum / 3)

  33.  

  34. plt.plot(w_list, mse_list)

  35. plt.ylabel('Loss')

  36. plt.xlabel('w')

  37. plt.show()

  38.  

 

梯度下降

 

梯度下降在最优化中又称之为最速下降算法,以下为该算法的基本概念。我们可以看到,若我们希望最小化的损失函数为凸函数,那么损失函数对各个权重的偏导数将指向该特征的极小值。如下当初始权重处于损失函数递增部分时,那么一阶梯度即损失函数在该点的斜率,且递增函数的斜率为正,那么当前权重减去一个正数将变小,因此权重将沿递增的反方向移动。同理可得当权重处于递减函数的情况。

 

 

 

如下我们手动实现了简单的梯度下降算法。前面还是先定义模型、损失函数,因为我们已知损失函数的结构,那么就可以手动对其求导以确定梯度函数的结构。得出了权重梯度的表达式后可以将其代入权重更新的循环语句以定义训练。

 

 
  1. x_data = [1.0, 2.0, 3.0]

  2. y_data = [2.0, 4.0, 6.0]

  3.  

  4. w = 1.0  # any random value

  5.  

  6.  

  7. # our model forward pass

  8. def forward(x):

  9.    return x * w

  10.  

  11.  

  12. # Loss function

  13. def loss(x, y):

  14.    y_pred = forward(x)

  15.    return (y_pred - y) * (y_pred - y)

  16.  

  17.  

  18. # compute gradient

  19. def gradient(x, y):  # d_loss/d_w

  20.    return 2 * x * (x * w - y)

  21.  

  22. # Before training

  23. print("predict (before training)",  4, forward(4))

  24.  

  25. # Training loop

  26. for epoch in range(10):

  27.    for x_val, y_val in zip(x_data, y_data):

  28.        grad = gradient(x_val, y_val)

  29.        w = w - 0.01 * grad

  30.        print("\tgrad: ", x_val, y_val, grad)

  31.        l = loss(x_val, y_val)

  32.  

  33.    print("progress:", epoch, l)

  34.  

  35. # After training

  36. print("predict (after training)",  4, forward(4))

  37.  

 

反向传播

 

下图展示了反向传播算法的链式求导法则与过程。对于反向传播来说,给定权重下,我们先要计算前向传播的结果,然后计算该结果与真实值的距离或误差。随后将该误差沿误差产生的路径反向传播以更新权重,在这个过程中误差会根据求导的链式法则进行分配。

 

 

 

 

以下代码实现了反向传播算法,我们可以看到在 PyTorch 中反向传播的语句为「loss(x_val, y_val).backward()」,即将损失函数沿反向传播。

 

 
  1. import torch

  2. from torch import nn

  3. from torch.autograd import Variable

  4.  

  5.  

  6. x_data = [1.0, 2.0, 3.0]

  7. y_data = [2.0, 4.0, 6.0]

  8.  

  9. w = Variable(torch.Tensor([1.0]),  requires_grad=True)  # Any random value

  10.  

  11. # our model forward pass

  12.  

  13.  

  14. def forward(x):

  15.    return x * w

  16.  

  17. # Loss function

  18.  

  19.  

  20. def loss(x, y):

  21.    y_pred = forward(x)

  22.    return (y_pred - y) * (y_pred - y)

  23.  

  24. # Before training

  25. print("predict (before training)",  4, forward(4).data[0])

  26.  

  27. # Training loop

  28. for epoch in range(10):

  29.    for x_val, y_val in zip(x_data, y_data):

  30.        l = loss(x_val, y_val)

  31.        l.backward()

  32.        print("\tgrad: ", x_val, y_val, w.grad.data[0])

  33.        w.data = w.data - 0.01 * w.grad.data

  34.  

  35.        # Manually zero the gradients after updating weights

  36.        w.grad.data.zero_()

  37.  

  38.    print("progress:", epoch, l.data[0])

  39.  

  40. # After training

  41. print("predict (after training)",  4, forward(4).data[0])

  42.  

 

PyTorch 线性回归

 

定义数据:

 

 
  1. import torch

  2. from torch.autograd import Variable

  3.  

  4. x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))

  5. y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]]))

  6.  

 

定义模型,在 PyTorch 中,我们可以使用高级 API 来定义相关的模型或层级。如下定义了「torch.nn.Linear(1, 1)」,即一个输入变量和一个输出变量。

 

 
  1. class Model(torch.nn.Module):

  2.  

  3.    def __init__(self):

  4.        """

  5.        In the constructor we instantiate two nn.Linear module

  6.        """

  7.        super(Model, self).__init__()

  8.        self.linear = torch.nn.Linear(1, 1)  # One in and one out

  9.  

  10.    def forward(self, x):

  11.        """

  12.        In the forward function we accept a Variable of input data and we must return

  13.        a Variable of output data. We can use Modules defined in the constructor as

  14.        well as arbitrary operators on Variables.

  15.        """

  16.        y_pred = self.linear(x)

  17.        return y_pred

  18.  

 

构建损失函数和优化器,构建损失函数也可以直接使用「torch.nn.MSELoss(size_average=False)」调用均方根误差函数。优化器可以使用「torch.optim.SGD()」提到用随机梯度下降,其中我们需要提供优化的目标和学习率等参数。

 

 

 
  1. # Construct our loss function and an Optimizer. The call to model.parameters()

  2. # in the SGD constructor will contain the learnable parameters of the two

  3. # nn.Linear modules which are members of the model.

  4. criterion = torch.nn.MSELoss(size_average=False)

  5. optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

  6.  

 

训练模型,执行前向传播计算损失函数,并优化参数:

 

 
  1. # Training loop

  2. for epoch in range(500):

  3.        # Forward pass: Compute predicted y by passing x to the model

  4.    y_pred = model(x_data)

  5.  

  6.    # Compute and print loss

  7.    loss = criterion(y_pred, y_data)

  8.    print(epoch, loss.data[0])

  9.  

  10.    # Zero gradients, perform a backward pass, and update the weights.

  11.    optimizer.zero_grad()

  12.    loss.backward()

  13.    optimizer.step()

  14.  

 

Logistic 回归

 

以下展示了 Logistic 回归的基本要素和对应代码。Logistic 回归的构建由以下三种函数组成:Sigmoid 函数、目标函数以及损失函数。下图分别给出了三种函数的对应代码。其中 Sigmoid 函数将线性模型演变为 Logistic 回归模型,而损失函数负责创建标准以测量目标与输出之间的二值交叉熵。

 

 

 

Softmax 分类

 

以下展示了 Softmax 分类的基本概念,其中最重要的是在最后一层使用了 Softmax 函数。我们可以使用 Softmax 函数将输出值转化为和为 1 的类别概率。

 

 

 

加载数据集与导入数据加载器:

 

 
  1. # MNIST Dataset

  2. train_dataset = datasets.MNIST(root='./data/',

  3.                               train=True,

  4.                               transform=transforms.ToTensor(),

  5.                               download=True)

  6.  

  7. test_dataset = datasets.MNIST(root='./data/',

  8.                              train=False,

  9.                              transform=transforms.ToTensor())

  10.  

  11. # Data Loader (Input Pipeline)

  12. train_loader = torch.utils.data.DataLoader(dataset=train_dataset,

  13.                                           batch_size=batch_size,

  14.                                           shuffle=True)

  15.  

  16. test_loader = torch.utils.data.DataLoader(dataset=test_dataset,

  17.                                          batch_size=batch_size,

  18.                                          shuffle=False)

  19.  

 

定义模型的架构,并选择优化器。如下我们可以了解该 Softmax 分类模型在前面使用了五个全连接层,并在最后一层使用了 Softmax 函数。例如先使用「l1 = nn.Linear(784, 520)」定义全连接的输入结点数与输出结点数,784 为 MNIST 的像素点数,再使用「F.relu(self.l1(x))」定义该全连接的激活函数为 ReLU。

 

 
  1. class Net(nn.Module):

  2.  

  3.    def __init__(self):

  4.        super(Net, self).__init__()

  5.        self.l1 = nn.Linear(784, 520)

  6.        self.l2 = nn.Linear(520, 320)

  7.        self.l3 = nn.Linear(320, 240)

  8.        self.l4 = nn.Linear(240, 120)

  9.        self.l5 = nn.Linear(120, 10)

  10.  

  11.    def forward(self, x):

  12.        x = x.view(-1, 784)  # Flatten the data (n, 1, 28, 28)-> (n, 784)

  13.        x = F.relu(self.l1(x))

  14.        x = F.relu(self.l2(x))

  15.        x = F.relu(self.l3(x))

  16.        x = F.relu(self.l4(x))

  17.        x = F.relu(self.l5(x))

  18.        return F.log_softmax(x)

  19.  

  20. model = Net()

  21.  

  22. optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

  23.  

 

CNN

 

下图展示了一个简单的卷积神经网络,它由输入层、卷积层 1、池化层 1、卷积层 2、池化层 2、全连接层组成。其中卷积层 1、2 是二维的,其输入通道为 1,输出通道为 10,卷积核大小为 5。其中池化层采用的是最大池化运算。

 

 

 

以下是上图简单卷积神经网络的加载数据:

 

 
  1. # MNIST Dataset

  2. train_dataset = datasets.MNIST(root='./data/',

  3.                               train=True,

  4.                               transform=transforms.ToTensor(),

  5.                               download=True)

  6.  

  7. test_dataset = datasets.MNIST(root='./data/',

  8.                              train=False,

  9.                              transform=transforms.ToTensor())

  10.  

  11. # Data Loader (Input Pipeline)

  12. train_loader = torch.utils.data.DataLoader(dataset=train_dataset,

  13.                                           batch_size=batch_size,

  14.                                           shuffle=True)

  15.  

  16. test_loader = torch.utils.data.DataLoader(dataset=test_dataset,

  17.                                          batch_size=batch_size,

  18.                                          shuffle=False)

  19.  

 

以下代码定义了上图卷积神经网络的架构,并定义了优化器。我们同样可以使用高级 API 添加卷积层,例如「nn.Conv2d(1, 10, kernel_size=5)」可以添加卷积核为 5 的卷积层。此外,在卷积层与全连接层之间,我们需要压平张量,这里使用的是「x.view(in_size, -1)」。

 

 
  1. class Net(nn.Module):

  2.  

  3.    def __init__(self):

  4.        super(Net, self).__init__()

  5.        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)

  6.        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)

  7.        self.mp = nn.MaxPool2d(2)

  8.        self.fc = nn.Linear(320, 10)

  9.  

  10.    def forward(self, x):

  11.        in_size = x.size(0)

  12.        x = F.relu(self.mp(self.conv1(x)))

  13.        x = F.relu(self.mp(self.conv2(x)))

  14.        x = x.view(in_size, -1)  # flatten the tensor

  15.        x = self.fc(x)

  16.        return F.log_softmax(x)

  17.  

  18.  

  19. model = Net()

  20.  

  21. optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值