Pytorch深度学习(1):Pytorch基础和应用

1、PyTorch基础和实战

PyTorch是一个基于Python的科学计算库,它有以下特点:

  • 类似于NumPy,但是它可以使用GPU,Pytorch许多张量计算的操作接口就是仿照Numpy的函数用法
  • 可以用它定义深度学习模型,可以灵活地进行深度学习模型的训练和使用

1.1、Tensor

  • 类似与NumPy的ndarray,唯一的区别是Tensor可以在GPU上加速运算,许多tensor计算的操作接口就是仿照Numpy的函数

tensor的快速初始化方法

import torch
  • 构造一个未初始化的5x3矩阵(里面的值未被给定)
x1 = torch.empty(5,4)
x1
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])
  • 构建一个随机初始化的矩阵
x2 = torch.rand(5,4)
x2
tensor([[0.9938, 0.3032, 0.1955, 0.8428],
        [0.4141, 0.7022, 0.7465, 0.3129],
        [0.4571, 0.7302, 0.6233, 0.7043],
        [0.2116, 0.2056, 0.6655, 0.9858],
        [0.9195, 0.3726, 0.5793, 0.5351]])
  • 构建一个全部为0,类型为long的矩阵
# dtype=torch.long指定数据类型
x3 = torch.zeros(5,3,dtype=torch.long)
x3
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
  • 查看tensor的数据类型
# 使用dtype查看tensor的数据类型
x4 = torch.zeros(5,3).long()
x4.dtype
torch.int64

从数据中直接构建tensor

x5 = torch.tensor([5,3])
x5
tensor([5, 3])
  • 也可以从一个已有的tensor构建一个新的tensor。这些方法会重用原来tensor的特征,例如,数据类型,除非提供新的数据。

  • tensor类的成员方法,并且名称以"_"为结束的,这些方法表示原地操作,即对原张量进行操作,关联的张量和原张量共享内存地址的

x6 = torch.rand(5,5, dtype=torch.double)
x6
tensor([[0.7686, 0.9434, 0.8250, 0.3215, 0.9586],
        [0.4062, 0.7713, 0.0895, 0.2644, 0.8662],
        [0.7114, 0.4103, 0.0479, 0.6845, 0.2827],
        [0.1238, 0.5038, 0.6880, 0.9974, 0.7341],
        [0.4214, 0.2042, 0.9892, 0.3777, 0.3079]], dtype=torch.float64)
# 把x6矩阵原地清零,并把结果返回给x7
x7 = x6.zero_() 
x7
tensor([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]], dtype=torch.float64)
x6
tensor([[0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]], dtype=torch.float64)
  • tensor实际上类似于指向storage的指针
# 修改x6的同时,x7也被修改了,二者在同一个内存地址
x6[1][2] = 2
print(x6)

print(x7)
tensor([[0., 0., 0., 0., 0.],
        [0., 0., 2., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]], dtype=torch.float64)
tensor([[0., 0., 0., 0., 0.],
        [0., 0., 2., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0.]], dtype=torch.float64)
  • 得到tensor的形状
x7.shape
torch.Size([5, 5])

tensor的数学运算操作

y = torch.rand(5,3)
y
tensor([[0.5747, 0.8113, 0.9661],
        [0.3549, 0.3127, 0.6117],
        [0.6659, 0.6179, 0.8058],
        [0.5592, 0.4544, 0.0741],
        [0.7651, 0.3416, 0.7924]])
  • tensor.clone深拷贝
x = y.clone()
x
tensor([[0.5747, 0.8113, 0.9661],
        [0.3549, 0.3127, 0.6117],
        [0.6659, 0.6179, 0.8058],
        [0.5592, 0.4544, 0.0741],
        [0.7651, 0.3416, 0.7924]])
  • 加法
x + y
tensor([[1.1494, 1.6226, 1.9323],
        [0.7098, 0.6254, 1.2235],
        [1.3319, 1.2358, 1.6116],
        [1.1185, 0.9088, 0.1481],
        [1.5302, 0.6831, 1.5849]])
  • 另一种加法的写法
torch.add(x, y)
tensor([[1.1494, 1.6226, 1.9323],
        [0.7098, 0.6254, 1.2235],
        [1.3319, 1.2358, 1.6116],
        [1.1185, 0.9088, 0.1481],
        [1.5302, 0.6831, 1.5849]])
  • 加法:把输出作为一个变量
result = torch.empty(5,3)
torch.add(x, y, out=result)
# result = x + y
result
tensor([[1.1494, 1.6226, 1.9323],
        [0.7098, 0.6254, 1.2235],
        [1.3319, 1.2358, 1.6116],
        [1.1185, 0.9088, 0.1481],
        [1.5302, 0.6831, 1.5849]])

tensor的切片操作

x = torch.randn(3,4)
print(x)
print(x[1:, 1:])
tensor([[ 0.1211, -0.7149, -0.0410,  0.6181],
        [ 1.4964, -0.3963,  0.2543,  0.2318],
        [ 0.3049,  0.6255,  0.2932, -0.5743]])
tensor([[-0.3963,  0.2543,  0.2318],
        [ 0.6255,  0.2932, -0.5743]])
  • Resizing: 可以重新调整reshape一个tensor,可以使用torch.view
x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,8)
z
tensor([[ 3.1040, -0.7736, -0.9052,  1.4215, -0.4246, -0.9579, -0.6282,  0.5106],
        [ 1.1836, -2.4153, -1.1516,  0.1279, -0.6164,  1.0598,  0.5147,  1.7398]])
  • 如果只有一个元素的tensor,使用.item()方法可以把里面的value变成Python数值,只能在tensor为单个元素时才能使用
x = torch.randn(1)
x
tensor([0.7695])
x.item()
0.769545316696167
  • transpose转置操作
# 维度0和维度1互换
print(z)
z.transpose(dim0  = 1,dim1 = 0)
tensor([[ 3.1040, -0.7736, -0.9052,  1.4215, -0.4246, -0.9579, -0.6282,  0.5106],
        [ 1.1836, -2.4153, -1.1516,  0.1279, -0.6164,  1.0598,  0.5147,  1.7398]])





tensor([[ 3.1040,  1.1836],
        [-0.7736, -2.4153],
        [-0.9052, -1.1516],
        [ 1.4215,  0.1279],
        [-0.4246, -0.6164],
        [-0.9579,  1.0598],
        [-0.6282,  0.5147],
        [ 0.5106,  1.7398]])

更多阅读

各种Tensor operations, 包括transposing, indexing, slicing,
mathematical operations, linear algebra, random numbers在
官方文档

1.2、tensor和numpy数组转换

  • 直接使用.numpy()和.from_numpty()进行二者转换
a = torch.ones(5)
a
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
b
array([1., 1., 1., 1., 1.], dtype=float32)
  • 转换后二者共享内存地址
b[1] = 2
b
array([1., 2., 1., 1., 1.], dtype=float32)
a
tensor([1., 2., 1., 1., 1.])

把NumPy ndarray转成Torch Tensor

c = torch.from_numpy(b)
c
tensor([1., 2., 1., 1., 1.])
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
[2. 2. 2. 2. 2.]
b
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

所有CPU上的Tensor都支持转成numpy或者从numpy转成Tensor。

1.3、CUDA Tensors-GPU运算

  • 使用.to方法,Tensor可以被移动到别的device上

  • 判断是否可以支持CUDA的GPU

torch.cuda.is_available()

True
if torch.cuda.is_available():
    device = torch.device("cuda")
    y = torch.ones_like(x, device=device)
    x = x.to(device)
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))

tensor([1.7695], device='cuda:0')
tensor([1.7695], dtype=torch.float64)
# GPU上的tensor不能直接转换为numpy.array
y.to("cpu").data.numpy()
y.cpu().data.numpy()
array([1.], dtype=float32)

1.4、初步:用numpy实现两层神经网络

  • 假设一个全连接带ReLU的神经网络,只有一个隐藏层,没有bias。

  • 用来从x预测y,使用L2 Loss。

  • o u t 1 = W 1 X out1 = W_1X out1=W1X

  • o u t 2 = m a x ( 0 , o u t 1 ) out2 = max(0, out1) out2=max(0,out1)

  • y h a t = W 2 o u t 2 y_{hat} = W_2out2 yhat=W2out2

这一实现完全使用numpy来计算前向传播,loss,还有反向传播

  • forward pass
  • loss
  • backward pass

numpy的ndarray是一个普通的n维array。它没有任何关于深度学习或者梯度(gradient)的知识,也不知道计算图(computation graph),只是一种用来计算数学运算的数据结构

# *************首先定义参数************

# 输入64个数据,数据为1000维,隐层100个神经元,输出10维

N, D_in, H, D_out = 64,1000,100,10

# 随机创建训练数据
x = np.random.randn(N,D_in)
y = np.random.randn(N,D_out)


w1 = np.random.randn(D_in, H)
w2 = np.random.randn(H,D_out)


# 学习率非常重要,需要慎重选择
learning_rate = 1e-6

for iter in range(500):
    # 第一步,进行前向传播
    out1 = x.dot(w1) # N * H 
    out1_relu = np.maximum(out1,0) # N * H
    y_pred = out1_relu.dot(w2) # N * D_out
    
    # 第二步,计算loss
    loss = np.square(y_pred - y).sum()
    print(iter,loss)
    
    # 第三步,反向传播,求梯度
    # loss -> y_pred
    # y_pred -> w2 , y_pred->  out1_relu
    # out1_relu -> out1
    # out1 -> w1
    
    grad_y_pred = 2.0 * (y_pred - y) # N * D_out
    grad_w2 = out1_relu.T.dot(grad_y_pred)  # 矩阵乘法,需要转置
    grad_out1_relu = grad_y_pred.dot(w2.T) # N * D_out -- D_out*H
    
    # relu的求导
    grad_out1 = grad_out1_relu.copy()
    grad_out1[out1 < 0 ] = 0
    
    grad_w1  = x.T.dot(grad_out1)  # D_in*N ---  N*H
    
    # 第四步,w1和w2的梯度更新
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2
    

    

## 1.5、使用PyTorch: Tensors实现两层神经网络

- 使用PyTorch tensors来创建前向神经网络,计算损失,以及反向传播。

- PyTorch Tensor很像一个numpy的ndarray。但是它和numpy ndarray最大的区别是,PyTorch Tensor可以在CPU或者GPU上运算。如果想要在GPU上运算,就需要把Tensor换成cuda类型。


```python
import torch

dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU


N, D_in, H, D_out = 64, 1000, 100, 10

# 创建随机训练数据
# 设置运算设备和数据类型
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)


# 随机初始化权重
w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out, device=device, dtype=dtype)

learning_rate = 1e-6

for iter1 in range(500):
    # 第一步,进行前向传播
    h = x.mm(w1) # torch的矩阵乘法
    h_relu = h.clamp(min = 0) # relu实现
    y_pred = h_relu.mm(w2)
    
    # 第二步,计算loss,item()取出单个tensor的数值
    loss = (y_pred - y).pow(2).sum().item()
    print(iter1, loss)
    
    # 第三步,反向传播,求梯度
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.t().mm(grad_y_pred)
    grad_h_relu = grad_y_pred.mm(w2.t())
    grad_h = grad_h_relu.clone()
    grad_h[h < 0] = 0
    grad_w1 = x.t().mm(grad_h)
    
    # 第四步,更新梯度
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2    

1.6、Pytorch自动求导:autograd

  • 简单的autograd
# requires_grad=True 表示需要对该变量求导数
x = torch.tensor(1., requires_grad=True)
w = torch.tensor(2., requires_grad=True)
b = torch.tensor(3., requires_grad=True)

y = w*x + b # y = 2*1+3


y.backward()

# dy / dw = x
print(w.grad)
print(x.grad)
print(b.grad)

tensor(1.)
tensor(2.)
tensor(1.)

1.7、PyTorch: Tensor和autograd

  • PyTorch的一个重要功能就是autograd,也就是说只要定义了forward pass(前向神经网络),计算了loss之后,PyTorch可以自动求导计算模型所有参数的梯度。

  • PyTorch的Tensor表示计算图中的一个节点。如果x是一个Tensor并且x.requires_grad=True那么x.grad是另一个储存着x当前梯度(相对于一个scalar,常常是loss)的向量。

N, D_in, H, D_out = 64, 1000, 100, 10

# 随机创建一些训练数据

"""
torch.randn(*size, *, out=None, dtype=None, 
layout=torch.strided, device=None, requires_grad=False) 

1、默认是requires_grad=False,即不需要求梯度

2、需要求梯度的就给requires_grad=True,不需要的就不给

"""
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

w1 = torch.randn(D_in, H, requires_grad=True)
w2 = torch.randn(H, D_out, requires_grad=True)

learning_rate = 1e-6
for it in range(500):
    # Forward pass
    y_pred = x.mm(w1).clamp(min=0).mm(w2)
    
    # compute loss
    loss = (y_pred - y).pow(2).sum() # computation graph
    print(it, loss.item())
    
    # Backward pass
    loss.backward()
    
    # update weights of w1 and w2
    # 不会记录w1.grad和w2.grad,较少内存
    with torch.no_grad():
        w1 -= learning_rate * w1.grad
        w2 -= learning_rate * w2.grad
        
        # 每次更新完梯度后需要清零,否则会叠加
        w1.grad.zero_()
        w2.grad.zero_()

1.8、PyTorch: torch.nn模块

  • 使用PyTorch中nn这个库来构建网络。
  • 用PyTorch autograd来构建计算图和计算gradients,
  • 然后PyTorch会帮我们自动计算gradient。

import torch.nn as nn

N, D_in, H, D_out = 64, 1000, 100, 10

"""
1、先给定训练数据
2、再创建模型
3、然后初始化权重,定义损失函数
4、开始for循环进行训练,四步曲


"""

# 随机创建一些训练数据
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

# 创建网络模型
# torch.nn.Sequential为序列容器,可以按照次序添加网络层进去
model = torch.nn.Sequential(
    # 线性层
    torch.nn.Linear(D_in, H, bias=False), # w_1 * x + b_1
    # relu
    torch.nn.ReLU(),
    # 线性层
    torch.nn.Linear(H, D_out, bias=False),
)

# 初始化参数
torch.nn.init.normal_(model[0].weight)
torch.nn.init.normal_(model[2].weight)

# 可以在gpu上运算
# model = model.cuda()

# 定义损失函数
loss_fn = nn.MSELoss(reduction='sum')

learning_rate = 1e-6
for it in range(500):
    # 第一步,Forward pass
    y_pred = model(x) # model.forward() 
    
    # 第二步,compute loss
    loss = loss_fn(y_pred, y) # computation graph
    print(it, loss.item())
    
    # 第三步,Backward pass
    loss.backward()
    
    # 第四步,update weights of w1 and w2
    with torch.no_grad():
        for param in model.parameters(): # param (tensor, grad)
            param -= learning_rate * param.grad
            
    model.zero_grad()
model[0].weight
Parameter containing:
tensor([[-0.5147, -0.3406,  0.2967,  ...,  0.6383, -0.9019, -0.2847],
        [ 1.4304,  0.2835, -0.9104,  ...,  0.3258,  1.0744, -1.0855],
        [-0.1072, -0.9136,  0.6432,  ...,  1.5699,  1.7886, -1.0637],
        ...,
        [-0.6680,  0.2900, -0.3160,  ...,  0.3613,  0.3540, -0.6331],
        [ 0.1452,  0.6974, -0.4412,  ...,  1.9744, -0.1892, -0.2466],
        [-0.2614,  0.5740,  1.6926,  ..., -0.0586,  1.6907,  0.0369]],
       requires_grad=True)

1.9、PyTorch: optim-优化算法

  • 不再手动更新模型的weights,而是使用optim这个包来帮助我们更新参数。
  • optim这个package提供了各种不同的模型优化方法,包括SGD+momentum, RMSProp, Adam等等。
import torch.nn as nn

N, D_in, H, D_out = 64, 1000, 100, 10

# 随机创建一些训练数据
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H, bias=False), # w_1 * x + b_1
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out, bias=False),
)

torch.nn.init.normal_(model[0].weight)
torch.nn.init.normal_(model[2].weight)

# model = model.cuda()

loss_fn = nn.MSELoss(reduction='sum')
# learning_rate = 1e-4
# optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# 定义一个优化器
learning_rate = 1e-6
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

for it in range(500):
    # Forward pass
    y_pred = model(x) # model.forward() 
    
    # compute loss
    loss = loss_fn(y_pred, y) # computation graph
    print(it, loss.item())

    optimizer.zero_grad()
    # Backward pass
    loss.backward()
    
    # update model parameters
    optimizer.step()

1.10、PyTorch: 自定义 nn Modules

  • 可以定义一个模型,这个模型继承自nn.Module类。
  • 如果需要定义一个比Sequential模型更加复杂的模型,就需要定义nn.Module模型。
import torch.nn as nn

N, D_in, H, D_out = 64, 1000, 100, 10

# 随机创建一些训练数据
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)

class TwoLayerNet(torch.nn.Module):
    def __init__(self, D_in, H, D_out):
        
        # 使用
        super(TwoLayerNet, self).__init__()
        
        # define the model architecture
        self.linear1 = torch.nn.Linear(D_in, H, bias=False)
        self.linear2 = torch.nn.Linear(H, D_out, bias=False)
    
    def forward(self, x):
        y_pred = self.linear2(self.linear1(x).clamp(min=0))
        return y_pred

model = TwoLayerNet(D_in, H, D_out)
loss_fn = nn.MSELoss(reduction='sum')
learning_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

for it in range(500):
    # Forward pass
    y_pred = model(x) # model.forward() 
    
    # compute loss
    loss = loss_fn(y_pred, y) # computation graph
    print(it, loss.item())

    optimizer.zero_grad()
    # Backward pass
    loss.backward()
    
    # update model parameters
    optimizer.step()

2、Pytorch进行深度学习具体步骤

  • 1、定义输入输出数据和参数

  • 2、定义模型

  • 3、定义loss

  • 4、定义优化器

  • 5、进入训练过程

最后四步曲

  • 前向传播
  • 计算损失函数
  • 反向传播,计算梯度
  • 优化模型参数,更新参数
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值