import torch # 构造一个5x3矩阵,不初始化。 x = torch.empty((5, 3) print(x)
1 2 3
# 构造一个随机初始化的矩阵 x = torch.rand((5, 3)) print(x)
1 2 3
# 构造一个填充某个值的矩阵 x = torch.full((5, 3), 3.1415) print(x)
1 2 3
# 构造全为0的矩阵,且数据类型为long x = torch.zeros((5, 3), dtype = torch.long) print(x)
1 2 3 4
# 构造单位矩阵 # torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor # Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. torch.eye(3)
1 2 3
# 使用数据构造一个张量 x = torch.tensor([5.5, 3]) print(x)
1 2 3 4 5 6 7 8
# 用已经存在的tensor构造一个tensor x = x.new_ones((5, 3), dtype = torch.double) # new_* methods take in sizes print(x)
x = torch.randn_like(x, dtype = torch.float) # size和原x的size相同,但数据类型不同 print(x)
1 2
# 获取维度信息 size() print(x.size())
1 2 3
# 加法1 + y = torch.rand(5, 3) print(x + y)
1 2 3 4
# 加法2 torch.add # torch.add(input, alpha=1, other, out=None) # Each element of the tensor other is multiplied by the scalar alpha and added to each element of the tensor input. The resulting tensor is returned. print(torch.add(x, y))
1 2 3 4
# 提供一个输出tensor作为参数 result = torch.empty((5, 3)) torch.add(x, y, out = result) print(x + y)
1 2 3 4 5
# add x to y (in-place) # 即将x+y的值赋给y # 任何使张量会发生变化的操作都有一个前缀 y.add_(x) print(y)
1 2 3 4 5 6
# 改变大小:如果你想改变一个 tensor 的大小或者形状,你可以使用 torch.view:
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())