张量运算
简单的Torch张量运算及注释如下
import torch
import numpy as np
#声明空/随机/0/数据张量,空≠0
a = torch.empty(3,4)
b = torch.rand(3,4)
c = torch.zeros(3,4,dtype=torch.long)
d = torch.tensor([5.5, 3])
print(a)
print(b)
print(c)
print(d)
#或者根据现有的张量创建张量。除非用户提供新值,否则这些方法将重用输入张量的属性,例如dtype
e = a.new_ones(3, 4, dtype=torch.double)
f = torch.randn_like(a, dtype=torch.float)
print(e)
print(f)
#得到它的大小
print(a.size())
#张量相加
result = torch.empty(3, 4)
torch.add(a, b, out=result)
print(result)
b.add_(a)
print(b)
#张量筛选
print(a[:, 1])
#张量大小调整,-1表示取决于其他维度
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
#将Torch Tensor转换为NumPy数组,Torch Tensor和NumPy阵列将共享其底层内存位置(如果Torch Tensor在CPU上),更改一个将改变另一个。
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)
a.add_(1)
print(a)
print(b)
#将NumPy数组转换为Torch Tensor
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
#CUDA Tensors
#可以使用该.to方法将张量移动到任何设备上
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!
以上列举了简单的操作,详情见官方文档PyTorch张量文档。