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]])
- 对比有无初始化的矩阵: 当声明一个未初始化的矩阵时, 它本身不包含任何确切的值. 当创建一个未初始化的矩阵时, 分配给矩阵的内存中有什么数值就赋值给了这个矩阵, 本质上是毫无意义的数据.
- 创建一个全零矩阵并可指定数据元素的类型为long
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])
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)
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]])
- 用类似于Numpy的方式对张量进行操作:
print(x[:, 1])
- 输出结果:
tensor([-2.0902, -0.4489, -0.1441, 0.8035, -0.8341])
- 改变张量的形状: torch.view()
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])
- 如果张量中只有一个元素, 可以用.item()将值取出, 作为一个python number
x = torch.randn(1)
print(x)
print(x.item())
- 输出结果:
tensor([-0.3531])
-0.3530771732330322
a = torch.ones(5)
print(a)
- 输出结果:
tensor([1., 1., 1., 1., 1.])
- 将Torch Tensor转换为Numpy array
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.]
- 将Numpy array转换为Torch Tensor:
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)
- 关于Cuda Tensor: Tensors可以用.to()方法来将其移动到任意设备上.
# 如果服务器上已经安装了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)
学习了什么是Pytorch.
学习了Pytorch的基本元素操作.
学习了Pytorch的基本运算操作.
学习了Torch Tensor和Numpy Array之间的相互转换.
学习了任意的Tensors可以用.to()方法来将其移动到任意设备上.
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)
- 在具有requires_grad=True的Tensor上执行一个加法操作
y = x + 2
print(y)
- 输出结果:
tensor([[3., 3.],
[3., 3.]], grad_fn=)
- 打印Tensor的grad_fn属性:
print(x.grad_fn)
print(y.grad_fn)
- 输出结果:
None
- 在Tensor上执行更复杂的操作:
z = y * y * 3
out = z.mean()
print(z, out)
- 输出结果:
tensor([[27., 27.],
[27., 27.]], grad_fn=) tensor(27., grad_fn=)
- 关于方法.requires_grad_(): 该方法可以原地改变Tensor的属性.requires_grad的值. 如果没有主动设定默认为False.
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
out.backward()
print(x.grad)
- 输出结果:
tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])
- 关于自动求导的属性设置: 可以通过设置.requires_grad=True来执行自动求导, 也可以通过代码块的限制来停止自动求导.
print(x.requires_grad)
print((x ** 2).requires_grad)
with torch.no_grad():
print((x ** 2).requires_grad)
- 输出结果:
True
True
False
- 可以通过.detach()获得一个新的Tensor, 拥有相同的内容但不需要自动求导.
print(x.requires_grad)
y = x.detach()
print(y.requires_grad)
print(x.eq(y).all())
- 输出结果:
True
False
tensor(True)