Pytorch是一个基于Numpy的科学计算包, 向它的使用者提供了两大功能.
- 作为Numpy的替代者, 向用户提供使用GPU强大功能的能力.
- 做为一款深度学习的平台, 向用户提供最大的灵活性和速度.
Tensors张量: 张量的概念类似于Numpy中的ndarray数据结构, 最大的区别在于Tensor可以利用GPU的加速功能.
我们使用Pytorch的时候, 常规步骤是先将torch引用进来, 如下所示:
from __future__ import print_function
import torch
x = torch.empty(5, 3)
print(x)
– 输出结果:
tensor([[2.4835e+27, 2.5428e+30, 1.0877e-19],
[1.5163e+23, 2.2012e+12, 3.7899e+22],
[5.2480e+05, 1.0175e+31, 9.7056e+24],
[1.6283e+32, 3.7913e+22, 3.9653e+28],
[1.0876e-19, 6.2027e+26, 2.3685e+21]])
x = torch.rand(5, 3)
print(x)
– 输出结果:
tensor([[0.1368, 0.8070, 0.4567],
[0.4369, 0.8278, 0.5552],
[0.6848, 0.4473, 0.1031],
[0.5308, 0.9194, 0.2761],
[0.0484, 0.9941, 0.2227]])
– 对比有无初始化的矩阵: 当声明一个未初始化的矩阵时, 它本身不包含任何确切的值. 当创建一个未初始化的矩阵时, 分配给矩阵的内存中有什么数值就赋值给了这个矩阵, 本质上是毫无意义的数据.
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([2.5, 3.5])
print(x)
– 输出结果:
tensor([2.5000, 3.3000])
# 利用news_methods方法得到一个张量
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
# 利用randn_like方法得到相同张量尺寸的一个新张量, 并且采用随机初始化来对其赋值
y = torch.randn_like(x, dtype=torch.float)
print(y)
– 输出结果:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[-0.1497, -0.5832, -0.3805],
[ 0.9001, 2.0637, 1.3299],
[-0.8813, -0.6579, -0.9135],
[-0.1374, 0.1000, -0.9343],
[-1.1278, -0.9140, -1.5910]])
print(x.size())
– 输出结果:
torch.Size([5, 3])
- 注意:
torch.Size函数本质上返回的是一个tuple, 因此它支持一切元组的操作.
y = torch.rand(5, 3)
print(x + y)
输出结果:
tensor([[ 1.6978, -1.6979, 0.3093],
[ 0.4953, 0.3954, 0.0595],
[-0.9540, 0.3353, 0.1251],
[ 0.6883, 0.9775, 1.1764],
[ 2.6784, 0.1209, 1.5542]])
print(torch.add(x, y))
输出结果:
tensor([[ 1.6978, -1.6979, 0.3093],
[ 0.4953, 0.3954, 0.0595],
[-0.9540, 0.3353, 0.1251],
[ 0.6883, 0.9775, 1.1764],
[ 2.6784, 0.1209, 1.5542]])
# 提前设定一个空的张量
result = torch.empty(5, 3)
# 将空的张量作为加法的结果存储张量
torch.add(x, y, out=result)
print(result)
输出结果:
tensor([[ 1.6978, -1.6979, 0.3093],
[ 0.4953, 0.3954, 0.0595],
[-0.9540, 0.3353, 0.1251],
[ 0.6883, 0.9775, 1.1764],
[ 2.6784, 0.1209, 1.5542]])
y.add_(x) # 执行的功能是y = y+x
print(y)
输出结果:
tensor([[ 1.6978, -1.6979, 0.3093],
[ 0.4953, 0.3954, 0.0595],
[-0.9540, 0.3353, 0.1251],
[ 0.6883, 0.9775, 1.1764],
[ 2.6784, 0.1209, 1.5542]])
注意:
所有in-place的操作函数都有一个下划线的后缀. 比如x.copy_(y), x.add_(y), 都会**直接改变x的值.**
用类似于Numpy的方式对张量进行操作:
print(x[:, 1])
解释:
python print(x[:, 1]) # 冒号代表取所有的行 ",1"代表取第一列
print(x[:,:3]) # 打印所有行、 0-2列
print(x[:,:2]) # 打印所有行、 0-1列
输出结果:
tensor([-2.0902, -0.4489, -0.1441, 0.8035, -0.8341])
x = torch.randn(4, 4)
# tensor.view()操作需要保证数据元素的总数量不变
y = x.view(16)
# -1代表自动匹配个数
z = x.view(-1, 8)
print(x.size(), y.size(), z.size())
输出结果:
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
详细注释版代码:
# 改变张量的形状: torch.view() x = torch.randn(4, 4) # tensor.view()操作需要保证数据元素的总数量不变 y = x.view(16) # 只有一行的张量 # -1代表自动匹配 # (-1,8) :第一个数代表行,第二个数代表列 # (-1,8) 代表 行 自动匹配(-1),列有8行 所以行自动匹配出来有两行(4*4/8) # 需要保证数据元素的总数量不变 且要能“整除” z = x.view(-1, 8) y2 = x.view(16,-1) # 代表 列 自动匹配(-1),行有16行 所以列自动匹配出来有1列(4*4/16) print(y) print(y2) print(x.size(),y.size(), z.size(),y2.size()) ```
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
输出结果:
tensor([-1.2186, -0.7919, 0.0411, -0.4893, -0.4517, 0.0588, 0.5275, -0.5617, 2.1183, 1.3618, -0.3788, 0.9497, -0.4051, 0.2710, 0.9537, -1.6315]) tensor([[-1.2186], [-0.7919], [ 0.0411], [-0.4893], [-0.4517], [ 0.0588], [ 0.5275], [-0.5617], [ 2.1183], [ 1.3618], [-0.3788], [ 0.9497], [-0.4051], [ 0.2710], [ 0.9537], [-1.6315]]) torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8]) torch.Size([16, 1]) ```
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
x = torch.randn(1)
print(x)
print(x.item())
输出结果:
tensor([-0.3531])
-0.3530771732330322
a = torch.ones(5)
print(a)
输出结果:
python tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
输出结果:
[1. 1. 1. 1. 1.]
a.add_(1)
print(a)
print(b)
输出结果:
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
- 1
- 2
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
输出结果:
[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
- 1
- 2
- 3
注意:
所有在CPU上的Tensors, 除了CharTensor, 都可以转换为Numpy array并可以反向转换.
# 如果服务器上已经安装了GPU和CUDA
if torch.cuda.is_available():
# 定义一个设备对象, 这里指定成CUDA, 即使用GPU
device = torch.device("cuda")
# 直接在GPU上创建一个Tensor
y = torch.ones_like(x, device=device)
# 将在CPU上面的x张量移动到GPU上面
x = x.to(device)
# x和y都在GPU上面, 才能支持加法运算
z = x + y
# 此处的张量z在GPU上面
print(z)
# 也可以将z转移到CPU上面, 并同时指定张量元素的数据类型
print(z.to("cpu", torch.double))
输出结果:
tensor([0.6469], device='cuda:0') tensor([0.6469], dtype=torch.float64)
- 1
- 2
x1 = torch.ones(3, 3)
print(x1)
x = torch.ones(2, 2, requires_grad=True)
print(x)
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[1., 1.],
[1., 1.]], requires_grad=True)
y = x + 2
print(y)
tensor([[3., 3.],
[3., 3.]], grad_fn=<AddBackward0>)
print(x.grad_fn)
print(y.grad_fn)
None
<AddBackward0 object at 0x10db11208>
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)
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 0x7f191afd6be0>
out.backward()
print(x.grad)
tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])
print(x.requires_grad)
print((x ** 2).requires_grad)
with torch.no_grad():
print((x ** 2).requires_grad)
True
True
False
print(x.requires_grad)
y = x.detach()
print(y.requires_grad)
print(x.eq(y).all())
True
False
tensor(True)