深度学习-预备知识

Anaconda

Anaconda是Python的一个开源发行版本,主要面向科学计算。可以简单理解为,Anaconda是一个预装了很多我们用的到或用不到的第三方库的Python。

Jupiter

有了notebook之后,世界突然美好了许多,因为notebook可以直接在代码旁写出叙述性文档,而不是另外编写单独的文档。也就是它可以能将代码、文档等这一切集中到一处,让用户一目了然。

创建Tensor


import torch

#创建一个5*3的未初始化的Tensor
x = torch.empty(5, 3)
print(x)
#output
tensor([[3.0412e+15, 7.8753e-43, 3.0412e+15],
        [7.8753e-43, 3.0412e+15, 7.8753e-43],
        [3.0412e+15, 7.8753e-43, 3.0412e+15],
        [7.8753e-43, 3.0412e+15, 7.8753e-43],
        [3.0412e+15, 7.8753e-43, 3.0412e+15]])

#创建一个5*3的随机初始化Tensor
x = torch.rand(5, 3)

#创建一个5x3的long型全0的Tensor
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
#output
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

#直接根据数据创建
x = torch.tensor([5.5, 3])
print(x)
#output
tensor([5.5000, 3.0000])

#通过现有的Tensor来创建
x = x.new_ones(5, 3, dtype=torch.float64)  # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)
#output
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x) 
#output
tensor([[ 0.6035,  0.8110, -0.0451],
        [ 0.8797,  1.0482, -0.0445],
        [-0.7229,  2.8663, -0.5655],
        [ 0.1604, -0.0254,  1.0739],
        [ 2.2628, -0.9175, -0.2251]])

#可以通过shape或者size()来获取Tensor的形状(作用一样):
print(x.size())
print(x.shape)
#output
torch.Size([5, 3])

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fI8NzGsW-1687308958698)(image/手动深度学习/1683252884155.png)]

Tensor操作

import torch

#加法
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print(x+y)
print(torch.add(x, y))#两种作用一样

result = torch.empty(5, 3)#用add函数还可以指定输出
torch.add(x, y, out=result)
print(result)

#索引(索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改)
x = torch.rand(5, 3)
print(x)
y = x[0, :]
y += 1
print(y)
print(x[0, :])
#output
tensor([[0.9581, 0.1779, 0.7106],
        [0.1819, 0.9269, 0.2064],
        [0.5119, 0.5286, 0.5199],
        [0.9384, 0.0359, 0.9702],
        [0.6956, 0.8877, 0.4842]])
tensor([1.9581, 1.1779, 1.7106])
tensor([1.9581, 1.1779, 1.7106])

#view改变Tensor的形状 https://blog.csdn.net/qimo601/article/details/112139783
y = x.view(15) #(view就是把原来的tensor拍扁,变成n个数,然后按照你给定的形状恢复出来)
z = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来
print(x.size(), y.size(), z.size())
#output
torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])

#clone返回新副本(view是共享内存)
x = torch.rand(5, 3)
print(x)
x2 = x.clone().view(15)
x -= 1
print(x)
print(x2)
#output
tensor([[0.8205, 0.6112, 0.4777],
        [0.8318, 0.0479, 0.4768],
        [0.2611, 0.0142, 0.0775],
        [0.6315, 0.4953, 0.6782],
        [0.2227, 0.0524, 0.2321]])
tensor([[-0.1795, -0.3888, -0.5223],
        [-0.1682, -0.9521, -0.5232],
        [-0.7389, -0.9858, -0.9225],
        [-0.3685, -0.5047, -0.3218],
        [-0.7773, -0.9476, -0.7679]])
tensor([0.8205, 0.6112, 0.4777, 0.8318, 0.0479, 0.4768, 0.2611, 0.0142, 0.0775,
        0.6315, 0.4953, 0.6782, 0.2227, 0.0524, 0.2321])

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

PyTorch&线性代数(官方文档)[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MKlhTPOK-1687308958700)(image/手动深度学习/1683254674398.png)]

广播机制

https://blog.csdn.net/flyingluohaipeng/article/details/125107959

import torch
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]])

Tensor和NumPy的转换

#使用numpy()将Tensor转换成NumPy数组
a = torch.ones(5)
b = a.numpy()
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)
#output
tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]

#使用from_numpy()将NumPy数组转换成Tensor
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)
#output
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
[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)

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

自动求梯度

在深度学习中,我们经常需要对函数求梯度(gradient)。PyTorch提供的autograd包能够根据输入和前向传播过程自动构建计算图,并执行反向传播。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2znwDZ0C-1687308958701)(image/手动深度学习/1683272093984.png)]

Tensor
#创建一个Tensor并设置requires_grad=True
import torch
x = torch.ones(2, 2, requires_grad=True)
print(x)
print(x.grad_fn)
#output
tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
None
'''
(grad_fn:该Tensor是不是通过某些运算得到的,若是,则grad_fn返回一个与这些运算相关的对象,否则是None)
'''

#再做一下运算操作
y = x + 2
print(y)
print(y.grad_fn)
#output
tensor([[3., 3.],
        [3., 3.]], grad_fn=<AddBackward0>)
<AddBackward0 object at 0x000001AFB6195390>

'''
注意x是直接创建的,所以它没有grad_fn, 而y是通过一个加法操作创建的,所以它有一个为<AddBackward>的grad_fn。
像x这种直接创建的称为叶子节点,叶子节点对应的grad_fn是None。
'''
#判断是否为叶子节点
print(x.is_leaf, y.is_leaf) 
#output
True False

#一些复杂度运算操作
z = y * y * 3
out = z.mean()#求平均数
print(z, out)
#output
tensor([[27., 27.],
        [27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward0>)

#通过.requires_grad_()来用in-place的方式改变requires_grad属性
a = torch.randn(2, 2) # 缺失情况下默认 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)
#output
False
True
<SumBackward0 object at 0x000001840FEF7FD0>
梯度
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()  #因为out是一个标量,所以调用backward()时不需要指定求导变量
out.backward()  #等价于 out.backward(torch.tensor(1.))
print(x.grad)   #打印out关于x的梯度 d(out)/dx
#output
tensor([[4.5000, 4.5000],
        [4.5000, 4.5000]])

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mlRa9Uad-1687308958702)(image/手动深度学习/1683304107630.png)]

# 再来反向传播一次,注意grad是累加的
out2 = x.sum()
out2.backward()
print(x.grad)
out3 = x.sum()
x.grad.data.zero_()
out3.backward()
print(x.grad)
#output
tensor([[5.5000, 5.5000],
        [5.5000, 5.5000]])
tensor([[1., 1.],
        [1., 1.]])

一个实际求梯度的例子:

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

#现在z不是一个标量,所以在调用backward时需要传入一个和z同形的权重向量进行加权求和得到一个标量
v = torch.tensor([[1.0, 0.1], [0.01, 0.001]], dtype=torch.float)
z.backward(v)
print(x.grad)#x.grad是和x同形的张量
#output
tensor([2.0000, 0.2000, 0.0200, 0.0020])

中断梯度追踪的例子:

import torch
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) 
#output
True
tensor(1., grad_fn=<PowBackward0>) True
tensor(1.) False
tensor(2., grad_fn=<ThAddBackward>) True

#将y3对x求梯度
y3.backward()
print(x.grad)
#output
tensor(2.)
'''
为什么是2呢?y3=y1+y2=x^2+x^3当x=1时 dy3/dx不应该是5吗?
事实上,由于 y2的定义是被torch.no_grad():包裹的,所以与 y2有关的梯度是不会回传的,只有与y1有关的梯度才会回传,即x^2对x的梯度。
'''

'''
上面提到,y2.requires_grad=False,所以不能调用 y2.backward(),
会报错:RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
'''

'''
此外,如果我们想要修改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) # 更改data的值也会影响tensor的值
print(x.grad)
#output
tensor([1.])
False
tensor([100.], requires_grad=True)
tensor([2.])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值