动手学深度学习 pytorch版学习记录-------(1)
该书已经开源,以下对学习过程做一个记录。环境为anaconda,jupyter notebook。
pytorch基本操作
先介绍Tensor的一些基本功能
Tensor创建
首先导入Pytorch:
import torch
x = torch.empty(5, 3)
print(x)
y = torch.rand(5, 3)
print(y)
输出
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
tensor([[0.4963, 0.7682, 0.0885],
[0.1320, 0.3074, 0.6341],
[0.4901, 0.8964, 0.4556],
[0.6323, 0.3489, 0.4017],
[0.0223, 0.1689, 0.2939]])
还可以直接根据数据创建:
x = torch.tensor([5.5, 3])
print(x)
输出
tensor([5.5000, 3.0000])
还可以通过现有的 Tensor 来创建,此方法会默认重用输入 Tensor 的⼀些属性,例如数据类型,除非自定义数据类型。
x = x.new_ones(5, 3, dtype=torch.float64) # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)
x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x)
输出:
下面展示一些 内联代码片
。
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
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)
输出:
torch.Size([5, 3])
torch.Size([5, 3])
常用的创建Tensor函数
函数 | 功能 |
---|---|
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,step) | 从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))
//加法形式三、inplace
y.add_(x)
print(y)
索引
y = x[0, :]
y += 1
print(y)
print(x[0, :]) # 源tensor也被改了
输出:
tensor([1.6035, 1.8110, 0.9549])
tensor([1.6035, 1.8110, 0.9549])
PyTorch还提供了一些高级的选择函数
函数 | 功能 |
---|---|
index_select(input,dim,index) | 在指定维度dim上选取,比如选取某些行、某些列 |
masked_select(input,mask) | 例子如上,a(a>0),使用ByteTensor进行选取 |
non_zero(input) | 非0元素的下标 |
gather(input,dim,index) | 根据index,在dim维度上选取数据,输出的size与index一样 |
改变形状
用view()来改变Tensor的形状:
y = x.view(15)
z = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来
print(x.size(), y.size(), z.size())
输出:
torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])
view()返回的新tensor与源tensor共享内存,更改其中一个,另一个也会跟着改变。
x += 1
print(x)
print(y) # 也加一
tensor([[2.6035, 2.8110, 1.9549],
[1.8797, 2.0482, 0.9555],
[0.2771, 3.8663, 0.4345],
[1.1604, 0.9746, 2.0739],
[3.2628, 0.0825, 0.7749]])
tensor([2.6035, 2.8110, 1.9549])
为了返回一个真正的副本,推荐使用clone创作一个副本然后使用view。
x_cp = x.clone().view(15)
x -= 1
print(x)
print(x_cp)
输出:
tensor([[ 1.6035, 1.8110, 0.9549],
[ 0.8797, 1.0482, -0.0445],
[-0.7229, 2.8663, -0.5655],
[ 0.1604, -0.0254, 1.0739],
[ 2.2628, -0.9175, -0.2251]])
tensor([2.6035, 2.8110, 1.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,
1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])
常用的函数就是item(),它可以将一个标量Tensor转换成一个Python number:
x = torch.randn(1)
print(x)
print(x.item())
输出:
tensor([2.3466])
2.3466382026672363
线性代数
另外,PyTorch还支持线性函数:
函数 | 功能 |
---|---|
trace | 对角线元素之和(矩阵的迹) |
diag | 对角线元素 |
triu/tril | 矩阵的上三角/下三角,可指定偏移量 |
mm/bmm | 矩阵乘法,batch的矩阵乘法 |
addmm/addbmm/addmv/addr/badbmm… | 矩阵运算 |
t | 转置 |
dot/cross | 内积/外积 |
inverse | 求逆矩阵 |
svd | 奇异值分解 |
其他操作可以参考官方文档。
广播机制
当两个形状不同的Tensor按元素运算时,可能会触发广播(broadcasting)机制:先适当复制元素使这两个Tensor形状相同后再按元素运算。
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()
和from_numpy()
这两个函数产生的Tensor
和NumPy array实际是使用的相同的内存,改变其中一个时另一个也会改变。
tensor转numpy
a = torch.ones(5)
b = a.numpy()
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)
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.]
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)
[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)
直接用torch.tensor()
将NumPy数组转换成Tensor
,该方法总是会进行数据拷贝,返回的Tensor
和原来的数据不再共享内存。
# 用torch.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
# 以下代码只有在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()还可以同时更改数据类型