# 构造一个未初始化的5x3矩阵
x = torch.empty(5,3)# 构造一个随机初始化的矩阵
x = torch.rand(5,3)# 构造一个填充零且dtype long的矩阵 构造全1和全0会输出dtype=torch.float64
x = torch.zeros(5,3, dtype=torch.long)# 直接从数据构造张量
x = torch.tensor([5.5,3])# 或基于现有张量创建张量。这些方法将重用输入张量的属性,例如dtype,除非用户提供新值
x = x.new_ones(5,3, dtype=torch.double)# x已知
x = torch.randn_like(x, dtype=torch.float)# override dtype!print(x)# result has the same sizeprint(x.size())# torch.Size 实际上是一个元组,因此它支持所有元组操作
二、运作方式Operations
y = torch.rand(5,3)print(x + y)# 加法1print(torch.add(x, y))# 加法2# 加法3
result = torch.empty(5,3)
torch.add(x, y, out=result)# 提供输出张量作为参数# 加法4
y.add_(x)# 复制
y.copy_(x)# 转置矩阵
y.t_()# 输出矩阵的某列print(y[:,4])# 调整大小
x = torch.randn(4,4)
y = x.view(16)
z = y.view(-1,2)# z = y.view((4, 4)) z = y.view([2, 8]) 必须达到y的16大小 若第一个参数是-1,第二个给出的为矩阵列数,行数会自动给出print(x.size(), y.size(), z.size())# 使用.item()将该值用作Python数字
x = torch.randn(1)print(x)print(x.item())
三、NumPy Bridge 将Torch张量转换为NumPy数组,反之亦然
# Torch Tensor和NumPy数组将共享其基础内存位置(如果Torch Tensor在CPU上),并且更改一个将更改另一个。# 将torch张量转换为Numpy数组# 除了CharTensor之外,CPU上的所有张量都支持转换为NumPy并返回
a = torch.ones(5)print(a)
b = a.numpy()print(b)
a.add_(1)print(a)print(b)# 结果相同# 将Numpy数组转换为torch张量
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a,1, out=a)print(a)print(b)# 结果相同
四、CUDA张量
# let us run this cell only if CUDA is available 有CUDA才可以运行# We will use ``torch.device`` objects to move tensors in and out of GPUif torch.cuda.is_available():
device = torch.device("cuda")# a CUDA device object
x = torch.rand(5,3)
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!