pytorch学习一、预备知识

来自于 https://tangshusen.me/Dive-into-DL-PyTorch/#/

官方文档 https://pytorch.org/docs/stable/tensors.html

一、创建tensor

import torch
x=torch.empty(5,3)
print(x)
tensor([[0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]])

随机初始化的tensor

x=torch.rand(5,3)
print(x)
tensor([[0.7624, 0.4653, 0.7209],
        [0.4361, 0.5439, 0.5854],
        [0.8580, 0.7224, 0.2054],
        [0.4909, 0.2152, 0.5398],
        [0.6228, 0.9138, 0.3790]])
x=torch.zeros(5,3,dtype=torch.long)
print(x)
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
x=torch.tensor([5.5,3])
print(x)
tensor([5.5000, 3.0000])
x=x.new_ones(5,3)
print(x)
x=torch.randn_like(x,dtype=torch.float) #通过现有的Tensor来创建
print(x)
x=torch.rand_like(x)
print(x)
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
tensor([[-1.1116,  0.1888,  0.2448],
        [ 0.2320, -1.1866, -1.0924],
        [ 1.8445,  0.3409, -0.3326],
        [ 0.5755, -1.4338,  0.5509],
        [ 0.9830, -0.0794,  1.2366]])
tensor([[0.7456, 0.3235, 0.6959],
        [0.5614, 0.7215, 0.4570],
        [0.2549, 0.2163, 0.4323],
        [0.5942, 0.8217, 0.1200],
        [0.8548, 0.0262, 0.9667]])
print(x.size())
print(x.shape)
torch.Size([5, 3])
torch.Size([5, 3])

函数 功能
|Tensor(*sizes) |基础构造函数|
|tensor(data,) |类似np.array的构造函数|
|ones(*sizes) |全1Tensor|
zeros(*sizes) 全0Tensor
eye(*sizes) 对角线为1,其他为0
arange(s,e,step) 从s到e,步长为step
linspace(s,e,steps) 从s到e,均匀切分成steps份
rand/randn(*sizes) 均匀/标准分布
normal(mean,std)/uniform(from,to) 正态分布/均匀分布
randperm(m) 随机排列

二、数据操作

y=torch.rand(5,3)
print(x+y) #加法一
print(torch.add(x,y))#加法二
result=torch.empty(5,3)
torch.add(x,y,out=result) #加法结果指定输出
print(result)
y.add_(x) #加法三
print(y)
tensor([[1.5263, 0.6306, 1.4731],
        [1.3893, 0.8269, 1.4266],
        [0.6578, 0.7498, 1.2932],
        [1.4695, 1.0189, 0.7405],
        [1.1655, 0.3981, 1.6615]])
tensor([[1.5263, 0.6306, 1.4731],
        [1.3893, 0.8269, 1.4266],
        [0.6578, 0.7498, 1.2932],
        [1.4695, 1.0189, 0.7405],
        [1.1655, 0.3981, 1.6615]])
tensor([[1.5263, 0.6306, 1.4731],
        [1.3893, 0.8269, 1.4266],
        [0.6578, 0.7498, 1.2932],
        [1.4695, 1.0189, 0.7405],
        [1.1655, 0.3981, 1.6615]])
tensor([[1.5263, 0.6306, 1.4731],
        [1.3893, 0.8269, 1.4266],
        [0.6578, 0.7498, 1.2932],
        [1.4695, 1.0189, 0.7405],
        [1.1655, 0.3981, 1.6615]])
索引,共享内存
print(x)
y=x[0,:]
y+=1
print(y)
print(x[0,:])
tensor([[0.7456, 0.3235, 0.6959],
        [0.5614, 0.7215, 0.4570],
        [0.2549, 0.2163, 0.4323],
        [0.5942, 0.8217, 0.1200],
        [0.8548, 0.0262, 0.9667]])
tensor([1.7456, 1.3235, 1.6959])
tensor([1.7456, 1.3235, 1.6959])

函数 功能
index_select(input, dim, index) 在指定维度dim上选取,比如选取某些行、某些列
masked_select(input, mask) 例子如上,a[a>0],使用ByteTensor进行选取
nonzero(input) 非0元素的下标
gather(input, dim, index) 根据index,在dim维度上选取数据,输出的size与index一样

改变形状 view,虽然改变了形状,但共享data内存

虽然view返回的Tensor与源Tensor是共享data的,但是依然是一个新的Tensor(因为Tensor除了包含data外还有一些其他属性),二者id(内存地址)并不一致

y=x.view(15)
z=x.view(-1,5) # -1 所指维度可以根据其他维度的值推出来
print(x.size(),y.size(),z.size())
print(x)
print(y)
print(z)
torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])
tensor([[1.7456, 1.3235, 1.6959],
        [0.5614, 0.7215, 0.4570],
        [0.2549, 0.2163, 0.4323],
        [0.5942, 0.8217, 0.1200],
        [0.8548, 0.0262, 0.9667]])
tensor([1.7456, 1.3235, 1.6959, 0.5614, 0.7215, 0.4570, 0.2549, 0.2163, 0.4323,
        0.5942, 0.8217, 0.1200, 0.8548, 0.0262, 0.9667])
tensor([[1.7456, 1.3235, 1.6959, 0.5614, 0.7215],
        [0.4570, 0.2549, 0.2163, 0.4323, 0.5942],
        [0.8217, 0.1200, 0.8548, 0.0262, 0.9667]])
x+=1 
print(x)
print(y)  #共享内存
tensor([[2.7456, 2.3235, 2.6959],
        [1.5614, 1.7215, 1.4570],
        [1.2549, 1.2163, 1.4323],
        [1.5942, 1.8217, 1.1200],
        [1.8548, 1.0262, 1.9667]])
tensor([2.7456, 2.3235, 2.6959, 1.5614, 1.7215, 1.4570, 1.2549, 1.2163, 1.4323,
        1.5942, 1.8217, 1.1200, 1.8548, 1.0262, 1.9667])

返回新的副本,即不共享内存

x_cp=x.clone().view(15)
x-=1
print(x)
print(x_cp)
tensor([[1.7456, 1.3235, 1.6959],
        [0.5614, 0.7215, 0.4570],
        [0.2549, 0.2163, 0.4323],
        [0.5942, 0.8217, 0.1200],
        [0.8548, 0.0262, 0.9667]])
tensor([2.7456, 2.3235, 2.6959, 1.5614, 1.7215, 1.4570, 1.2549, 1.2163, 1.4323,
        1.5942, 1.8217, 1.1200, 1.8548, 1.0262, 1.9667])

使用clone还有一个好处是会被记录在计算图中,即梯度回传到副本时也会传到源Tensor(???)

x=torch.randn(1)
print(x)
print(x.item()) #item(), 它可以将一个标量Tensor转换成一个Python number
tensor([-1.1053])
-1.105263590812683

PyTorch还支持一些线性函数,这里提一下,免得用起来的时候自己造轮子,具体用法参考官方文档。如下表所示:

函数 功能
trace 对角线元素之和(矩阵的迹)
diag 对角线元素
triu/tril 矩阵的上三角/下三角,可指定偏移量
mm/bmm 矩阵乘法,batch的矩阵乘法
addmm/addbmm/addmv/addr/baddbmm… 矩阵运算
t 转置
dot/cross 内积/外积
inverse 求逆矩阵
svd 奇异值分解

三、广播机制

当对两个形状不同的Tensor按元素运算时,可能会触发广播(broadcasting)机制

x=torch.arange(1,3).view(1,2)
print(x)
y=torch.arange(1,4).view(3,1)
print(y)
print(x+y)
tensor([[1, 2]])
tensor([[1],
        [2],
        [3]])
tensor([[2, 3],
        [3, 4],
        [4, 5]])

运算内存开销

索引操作是不会开辟新内存的,而像y = x + y这样的运算是会新开内存的,然后将y指向新内存。为了演示这一点,我们可以使用Python自带的id函数:如果两个实例的ID一致,那么它们所对应的内存地址相同;反之则不同。

x=torch.tensor([1,2])
y=torch.tensor([3,4])
id_before=id(y)
y=y+x
print(id(y)==id_before)
False

如果想指定结果到原来的y的内存,我们可以使用前面介绍的索引来进行替换操作。在下面的例子中,我们把x + y的结果通过[:]写进y对应的内存中。

x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y[:] = y + x
print(id(y) == id_before) # True
True
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
torch.add(x, y, out=y) # y += x, y.add_(x)
print(id(y) == id_before) # True

True

四、Tensor 和 NumPy 相互转换

Tensor --> NumPy

a=torch.ones(5)
b=a.numpy()  #共享data内存
print(a,b)
print(type(a),type(b))
a+=1
print(a,b)
b+=1
print(a,b)
tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
<class 'torch.Tensor'> <class 'numpy.ndarray'>
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]

NumPy --> Tensor

import numpy as np
a=np.ones(5)
b=torch.from_numpy(a)
print(a,b)
print(type(a),type(b))
a+=1
print(a,b)
b+=1
print(a,b)
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
<class 'numpy.ndarray'> <class 'torch.Tensor'>
[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)
所有在CPU上的Tensor(除了CharTensor)都支持与NumPy数组相互转换。

此外上面提到还有一个常用的方法就是直接用torch.tensor()将NumPy数组转换成Tensor,需要注意的是该方法总是会进行数据拷贝,返回的Tensor和原来的数据不再共享内存。

c=torch.tensor(a)
a+=1
print(a,c)
[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)

Tensor on GPU

用方法to()可以将Tensor在CPU和GPU(需要硬件支持)之间相互移动。

# 以下代码只有在PyTorch GPU版本上才会执行
if torch.cuda.is_available():
    device = torch.device("cuda")          # GPU
    y = torch.ones_like(x, device=device)  # 直接创建一个在GPU上的Tensor
    x = x.to(device)                       # 等价于 .to("cuda")
    z = x + y
    print(z)
    print(z.to("cpu", torch.double))       # to()还可以同时更改数据类型

五、自动求梯度

Tensor是这个包的核心类,如果将其属性.requires_grad设置为True,它将开始追踪(track)在其上的所有操作(这样就可以利用链式法则进行梯度传播了)。完成计算后,可以调用.backward()来完成所有梯度计算。此Tensor的梯度将累积到.grad属性中。

如果不想要被继续追踪,可以调用.detach()将其从追踪记录中分离出来,这样就可以防止将来的计算被追踪,这样梯度就传不过去了。此外,还可以用with torch.no_grad()将不想被追踪的操作代码块包裹起来,这种方法在评估模型的时候很常用,因为在评估模型时,我们并不需要计算可训练参数(requires_grad=True)的梯度。

Function是另外一个很重要的类。Tensor和Function互相结合就可以构建一个记录有整个计算过程的有向无环图(DAG)。每个Tensor都有一个.grad_fn属性,该属性即创建该Tensor的Function, 就是说该Tensor是不是通过某些运算得到的,若是,则grad_fn返回一个与这些运算相关的对象,否则是None。

x=torch.ones(2,2,requires_grad=True)
print(x)
print(x.grad_fn)
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
None
y=x+2
print(y)
print(y.grad_fn)
tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward0>)
<AddBackward0 object at 0x000001FB037F39E8>

注意x是直接创建的,所以它没有grad_fn, 而y是通过一个加法操作创建的,所以它有一个为的grad_fn。

像x这种直接创建的称为叶子节点,叶子节点对应的grad_fn是None。

print(x.is_leaf,y.is_leaf)
True False
z=y*y*3
out=z.mean()
print(z,out)
tensor([[27., 27.],
        [27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward0>)
a=torch.randn(2,2) #default 默认 requires_grad = False
a=((a*3)/(a-1))
print(a.requires_grad)
a.requires_grad_(True)
print(a.requires_grad)
b=(a*a).sum()
print(b.grad_fn)
False
True
<SumBackward0 object at 0x000001FB7F856DD8>

梯度

因为out是一个标量,所以调用backward()时不需要指定求导变量

out.backward()  #等价于 out.bakcward(torch.tensor(1.))

我们来看看out关于x的梯度 d(out)/dx

print(x.grad)
tensor([[4.5000, 4.5000],
        [4.5000, 4.5000]])

grad在反向传播过程中是累加的(accumulated),这意味着每一次运行反向传播,梯度都会累加之前的梯度,所以一般在反向传播之前需把梯度清零

out2=x.sum()
out2.backward()
print(x.grad)

out3=x.sum()
x.grad.data.zero_()
out3.backward()
print(x.grad)
tensor([[2., 2.],
        [2., 2.]])
tensor([[1., 1.],
        [1., 1.]])

现在我们解释2.3.1节留下的问题,为什么在y.backward()时,如果y是标量,则不需要为backward()传入任何参数;否则,需要传入一个与y同形的Tensor? 简单来说就是为了避免向量(甚至更高维张量)对张量求导,而转换成标量对张量求导。举个例子,假设形状为 m x n 的矩阵 X 经过运算得到了 p x q 的矩阵 Y,Y 又经过运算得到了 s x t 的矩阵 Z。那么按照前面讲的规则,dZ/dY 应该是一个 s x t x p x q 四维张量,dY/dX 是一个 p x q x m x n的四维张量。问题来了,怎样反向传播?怎样将两个四维张量相乘???这要怎么乘???就算能解决两个四维张量怎么乘的问题,四维和三维的张量又怎么乘?导数的导数又怎么求,这一连串的问题,感觉要疯掉…… 为了避免这个问题,我们不允许张量对张量求导,只允许标量对张量求导,求导结果是和自变量同形的张量。所以必要时我们要把张量通过将所有张量的元素加权求和的方式转换为标量,举个例子,假设y由自变量x计算而来,w是和y同形的张量,则y.backward(w)的含义是:先计算l = torch.sum(y * w),则l是个标量,然后求l对自变量x的导数

x=torch.tensor([1.0,2.0,3.0,4.0],requires_grad=True)
y=2*x
z=y.view(2,2)
print(z)
tensor([[2., 4.],
        [6., 8.]], grad_fn=<ViewBackward>)

现在 z 不是一个标量,所以在调用backward时需要传入一个和z同形的权重向量进行加权求和得到一个标量。

v=torch.tensor([[1.0,0.1],[0.01,0.001]],dtype=torch.float)
z.backward(v)
print(x.grad)
tensor([2.0000, 0.2000, 0.0200, 0.0020])

中断梯度追踪

x = torch.tensor(1.0,requires_grad=True)
y1=x**2
with torch.no_grad():
    y2=x**3
y3=y1+y2
print(x.requires_grad)
print(y1,y1.requires_grad)
print(y2,y2.requires_grad)
print(y3,y3.requires_grad)
True
tensor(1., grad_fn=<PowBackward0>) True
tensor(1.) False
tensor(2., grad_fn=<AddBackward0>) True

y2是没有grad_fn而且y2.requires_grad=False的,而y3是有grad_fn

y3.backward()
print(x.grad)
tensor(2.)

如果我们想要修改tensor的数值,但是又不希望被autograd记录(即不会影响反向传播),那么我么可以对tensor.data进行操作。

x=torch.ones(1,requires_grad=True)
print(x.data)  # 还是一个tensor
print(x.data.requires_grad) # 但已经独立于计算图之外

y=2*x
x.data*=100
y.backward()
print(x)
print(x.grad)
tensor([1.])
False
tensor([100.], requires_grad=True)
tensor([2.])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值