dl----pytorch基础知识

0.torch安装

1.确定显卡为英伟达系列的显卡
2.确定当前显卡可以安装哪些版本的显卡驱动,并选择合适的显卡驱动进行安装
3.根据当前的显卡驱动确定显卡最高支持哪个版本的CUDA,然后安装低于该版本号的cuda版本
4.根据当前的cuda版本安装合适的torch版本
5.根据当前的torch版本选择合适的mmcv版本
[pytorch官网](https://pytorch.org/get-started/previous-versions/)
[torch下载](https://download.pytorch.org/whl/torch_stable.html)

1.torch的基础单位tensor
torch.function torch.save/torch.sum(a,b) tensor.function tensor.view/a.sum(b) a.add(b) # 加法的结果返回新的tensor a.add_(b) # 加法的结果存在a中

2.创建tensor的操作

import torch
a = torch.tensor(2)  # 创建维度为2乘3的张量
a.tolist() # 张量转换为列表,实际类型不变
a.size() # 返回a的大小,等价于a.shape()
a.numel() # 统计元素个数,等价于a.nelement()
torch.ones()/zeros()/eye()/arange(s,e,step)/linspace(s,e,step)/rand()/randn()/normal(mean,std)/uniform(from,tor)/randperm(m)

3.调整tensor

# view 调整形状,必须得保证调整前后元素个数一致,不会修改原tensor的形状和数据
a = torch.arange(0,6)
b = a.view(2,3)
c = a.view(-1,3)

# resize() 调整size的方法,但是它相比较view,可以修改tensor的尺寸,如果尺寸超过了原尺寸,则会自动分配新的内存,反之,则会保留老数据
b = a.resize_(1,3) # tensor([[0,1,2]])
b = a.resize_(3,3) # tensor([[0,1,2],[3,4,5],[0,0,0]])
b = a.resize_(2,3) # tensor([[0,1,2],[3,4,5]])

# 添加/压缩维度 unsqueeze()/squeeze()
b.unsqueeze(1)  # 在第一维上增加1维
b.squeeze(1)    # 压缩第一维上维度为1的维度
b.squeeze()     # 把所有维度为“1”的压缩

4. 索引操作

index_select(input,dim,index)   # 在指定维度dim上选取,例如选取某些行、某些列
masked_select(inpu,mask)        # a[a>1]等价于a.masked_select(a>1)
non_zero(input)                 # 获取非0元素的下标
gather(input,dim,index)         # 根据index,在dim维度上选取数据,输出的size与index一样

5.Tensor数据类型
数据类型 CPU tensor GPU tensor
32bit浮点 torch.FloatTensor torch.cuda.FloatTensor
64bit浮点 torch.DoubleTensor torch.cuda.DoubleTensor
16bit半精度浮点 torch.HalfTensor torch.cuda.HalfTensor
8bit无符号整型(0~255) torch.ByteTensor torch.cuda.ByteTensor
8bit有符号整型(-128~127) torch.CharTensor torch.cuda.CharTensor
16bit有符号整型 torch.ShortTensor torch.cuda.ShortTensor
32bit有符号整型 torch.IntTensor torch.cuda.IntTensor
64bit有符号整型 torch.LongTensor torch.cuda.LongTensor

6.数据类型转换

import torch
torch.set_default_tensor_type('torch.DoubleTensor')
d = a.new(2,3)
a.new??
torch.set_default_tensor_type('torch.FloatTensor')
a.cuda()  # 张量转化为cuda
a.cpu() 

7.逐元素操作

mul/abs/sqrt/exp/fmod/log/pow
cos/sin/asin/atan2/cosh
ceil/round/floor/trunc
clamp(input,min,max)
sigmod/tanh/leaky

8.归并操作

mean/sum/median/mode
norm/dist
std/var
cunsum/cumprod
cat(tensor1,tensor2,dim)

9.比较

gt/lt/le/eq/ne
topk
sort
max/min

10.线性代数运算

trace	#对角线元素之和(矩阵的迹)
diag	#对角线元素
triu/tril	#矩阵的上三角/下三角,可指定偏移量
mv/mm/bmm	#矩阵和向量的乘法/矩阵的乘法/两个batch内的矩阵进行批矩阵乘法
addmm	#两个矩阵进行乘法操作的结果与另一向量相加
addmv	#将矩阵和向量的结果与另一向量相加
addbmm	#将两个batch内的矩阵进行批矩阵乘法操作并累加,其结果与另一矩阵相加
baddbmm	#将两个batch内的矩阵进行批矩阵乘法操作,其结果与另一batch内的矩阵相加
eig	#计算方阵的特征值和特征向量
t	#转置
dot/cross	#内积/外积
inverse	#求逆矩阵
svd	#奇异值分解

11.torch – numpy

a = np.ones([2,3],dtype=np.float32)
b = torch.from_numpy(a)  # ndarray -> tensor
b = torch.Tensor(a) # ndarray -> tensor
c = b.numpy() # tensor -> ndarray

12.广播法则
torch当前支持自动广播法则,推荐手动广播
unsqueeze或view:为数据某一维的形状补1
expand或expand_as:重复数组,实现当输入的数组的某个维度的长度为1时,计算时沿此维度复制扩充成一样的形

a = t.ones(3, 2)
b = t.zeros(2, 3, 1)
c = a + b
c = a.unsqueeze(0).expand(2,3,2) + b.expand(2,3,2) 

自动广播法则:
a是二维,b是三维,所在现在较小的a前面补1(等价于a.unsqueeze(0),a的形状变成(0,2,3))
由于a和b在第一维和第三维的形状不一样,利用广播法则,两个形状都变成了(2,3,2)

13.Tensor内部存储结构
tensor的数据存储结构如上图所示,它分为信息区(Tensor)和存储区(Storage),信息区主要保存tensor的形状、数据类型等信息;而真正的数据则保存成连续数组存放在存储区。

一个tensor有着一个与之对应的storage,storage是在data之上封装的接口,便于使用。不同的tensor的头信息一般不同,但却有可能使用相同的storage。

a = t.Tensor([0, 1, 2, 3, 4, 5])
b = a.view(2, 3)
id(a.storage()), id(b.storage()), id(a.storage()) == id(b.storage())
b.stride(), e.stride()
e.is_contiguous()

从上可见大多数操作并不会修改tensor的数据,只是修改tensor的头信息,这种做法减少了内存的占用,并且更加节省了时间。但是有时候这种操作会导致tensor不连续,此时可以通过contiguous方法让其连续,但是这种方法会复制数据到新的内存空间,不再和原来的数据共享内存。

14.Tensor的持久化和向量化作
tensor在加载数据的时可以把gpu tensor映射到cpu上或者其他gpu上

# 保存模型
if torch.cuda.is_available():
    a = a.cuda(1)  # 把a转为gpu1上的tensor
    torch.save(a, 'a.pkl')

# 加载模型
# 加载为b,存储于gpu1上(因为保存时tensor就在gpu1上)
b = torch.load('a.pkl')
# 加载为c,存储于cpu
c = torch.load('a.pkl', map_location=lambda storage, loc: storage)
# 加载为d,存储于gpu0上
d = torch.load('a.pkl', map_location={'cuda:1': 'cuda:0'})

# 向量化计算是一种特殊的并行计算方法,通常是对不同的数据执行同样的一个或一批指令。由于Python原生的for循环效率低下,因此可以尽可能的使用向量化的数值计算。
def for_loop_add(x, y):
    result = []
    for i, j in zip(x, y):
        result.append(i + j)
    return torch.Tensor(result)


x = torch.zeros(100)
y = torch.ones(100)

%timeit -n 100 for_loop_add(x,y)
%timeit -n 100 x+y

torch.function都有一个参数out,可以将其产生的结果保存在out指定的tensor之中
torch.set_num_threads可以设置torch进行cpu多线程并行计算时所占用的线程数,用来限制torch所占用的cpu数目
torch.set_printoptions可以用来设置打印tensor时的数值精度和格式

15.autograd
autograd 模块的核心数据结构是 Variable,它是对 tensor 的封装,并且会记录 tensor 的操作记录用来构建计算图
autograd.Variable data grad grad_fn
data:保存 variable 所包含的 tensor
grad:保存 data 对应的梯度,grad 也是 variable,而非 tensor,它与 data 形状一致
grad_fn:指向一个 Function,记录 variable 的操作历史,即它是什么操作的输出,用来构建计算图。如果某一变量是用户创建的,则它为叶子节点,对应的 grad_fn 为 None
Variable 的构造函数需要传入 tensor,也有两个可选的参数:requires_grad(bool):是否需要对该 Variable 求导
volatile(bool):设置为 True,构建在该 Variable 之上的图都不会求导

import torch
from torch.autograd import Variable
def f(x):
    y = x ** 2 ** torch.exp(x)
    return y

def grad_f(x):
    dx = 2 * x * torch.exp(x) + x** 2 * torch.exp(x)
    return dx

x = Variable(torch.randn(3,4), requires_grad = True)
y = f(x)
print(y)
y_grad_variables = torch.ones(y.size())
y.backward(y_grad_variables)
print(x.grad)
print(grad_f(x))

'''
tensor([[0.0717, 0.0169,    nan, 0.2574],
        [   nan,    nan, 0.3621,    nan],
        [0.4463, 0.3690,    nan, 0.0568]], grad_fn=<PowBackward1>)
tensor([[0.3216, 0.1756,    nan, 0.9869],
        [   nan,    nan, 1.5500,    nan],
        [2.0760, 1.5910,    nan, 0.2862]])
tensor([[ 1.3601,  0.4214, -0.4199,  4.0454],
        [-0.2477, -0.3550,  5.0707, -0.4168],
        [ 5.7171,  5.1289, -0.0637,  1.1073]], grad_fn=<AddBackward0>)
'''
x = Variable(torch.ones(1))
b = Variable(torch.rand(1), requires_grad=True)
w = Variable(torch.rand(1), requires_grad=True)
y = w * x  # 等价于 y=w.mul(x)
z = y + b 
print(x.requires_grad, b.requires_grad, w.requires_grad, y.requires_grad, z.requires_grad)
print(x.is_leaf, b.is_leaf, w.is_leaf, y.is_leaf, z.is_leaf)
print(z.grad_fn)
print(z.grad_fn.next_functions)
print(z.grad_fn.next_functions[0][0] == y.grad_fn)

反向传播过程中非叶子节点的导数计算完之后将会被清空,可以通过以下三种方法查看这边变量的梯度:1.使用retain_grad保存梯度;2.使用 autograd.grad 函数;3.使用 hook

16.autograd实现线性回归

import torch
from torch.autograd import Variable
%matplotlib inline
from matplotlib import pyplot as plt
from Ipython import display

torch.manual_seed(1000)

def get_fake_data(batch_size=8):
    x = torch.rand(batch_size, 1) * 20
    y = x * 2 +(1 + t.randn(batch_size, 1)) * 3
    return x,y

x,y = get_fake_data()
plt.scatter(x.squeeze().numpy, y.squeeze().numpy())
plt.show()


# 随机初始化参数
w = Variable(torch.rand(1, 1), requires_grad=True)
b = Variable(torch.zeros(1, 1), requires_grad=True)

lr = 0.001  # 学习率

for i in range(8000):
    x, y = get_fake_data()
    x, y = V(x), V(y)

    # forwad:计算 loss
    y_pred = x.mm(w) + b.expand_as(y)
    loss = 0.5 * (y_pred - y)**2
    loss = loss.sum()

    # backward:自动计算梯度
    loss.backward()

    # 更新参数
    w.data.sub_(lr * w.grad.data)
    b.data.sub_(lr * b.grad.data)

    # 梯度清零,不清零则会进行叠加,影响下一次梯度计算
    w.grad.data.zero_()
    b.grad.data.zero_()

    if i % 1000 == 0:
        # 画图
        display.clear_output(wait=True)
        x = t.arange(0, 20, dtype=t.float).view(-1, 1)
        y = x.mm(w.data) + b.data.expand_as(x)
        plt.plot(x.numpy(), y.numpy(), color='red')  # 预测效果

        x2, y2 = get_fake_data(batch_size=20)
        plt.scatter(x2.numpy(), y2.numpy(), color='blue')  # 真实数据

        plt.xlim(0, 20)
        plt.ylim(0, 41)
        plt.show()
        plt.pause(0.5)
        break  # 注销这一行,可以看到动态效果

w.data.squeeze(), b.data.squeeze()

17.Lenent实现

import torch as t
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as V


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()  # nn.Module 子类的函数必须在构造函数中执行父类的构造函数

        # 卷积层
        self.conv1 = nn.Conv2d(1, 6,
                               5)  # '1'表示输入图片为单通道,‘6’表示输出通道数,‘5’表示卷积核为 5*5
        self.conv2 = nn.Conv2d(6, 16, 5)

        # 仿射层/全连接层,y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 卷积-》激活-》池化
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)

        # reshape,‘-1’表示自适应
        x = x.view(x.size()[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)

        return x


net = Net()
params = list(net.parameters())
for name, parameters in net.named_parameters():
    print(f'{name}: {parameters.size()}')

input = V(t.randn(1, 1, 32, 32))  # 定义输入
out = net(input)
out.size()  # 输出的形状
net.zero_grad()  # 所有参数的梯度清零
out.backward(V(t.ones(1, 10)))  # 反向传播
output = net(input)  # net(input)的输出的形状是(1,10)
target = V(t.arange(0, 10)).view(1, 10).float()
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)

# 运行.backward,观察调用之前和调用之后的 grad
net.zero_grad()  # 把 net 中所有可学习参数的梯度清零
print(f'反向传播之前conv1.bias 的梯度:{net.conv1.bias.grad}')
loss.backward()
print(f'反向传播之后conv1.bias 的梯度:{net.conv1.bias.grad}')

import torch.optim as optim

# 新建一个优化器,指定要调整的参数和学习率
optimizer = optim.SGD(net.parameters(), lr=0.01)

# 在训练过程中,先将梯度清零(和 net.zero_grad()效果一样)
optimizer.zero_grad()

# 计算损失
output = net(input)
loss = criterion(output, target)

# 反向传播
loss.backward()

# 更新参数
optimizer.step()


# hub 模块
import torch 

model = torch.hub.load('pytorch/vision:v0.4.2', 'deeplabv3_resnet101', pretrained=True)  # 加载模型,第一次加载需要一点点时间
model.eval()  # 释放模型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值