import torch
x = torch.empty([5, 3]) #构造一个5x3矩阵,不初始化。
print(x)
x = torch.rand(5, 3) #构造一个随机初始化的矩阵
y = torch.randn(5, 3)
print(x)
print(y)
x = torch.zeros(5, 3, dtype=torch.long) #构造一个矩阵全为 0,而且数据类型是 long.
print(x)
x = torch.tensor([5.5, 3]) #构造一个张量,直接使用数据
print(x)
#创建一个 tensor 基于已经存在的 tensor。
x = x.new_ones(5, 3, dtype=torch.double)
# new_* methods take in sizes
print(x)
x = torch.rand_like(x, dtype=torch.float)
# override dtype!
print(x)
# result has the same size
print(x.size()) #获取它的维度信息
#加法操作: 加法: 方式 1
y = torch.rand(5, 3)
print(x + y)
#加法: 方式2
print(torch.add(x, y))
#加法: 提供一个输出 tensor 作为参数
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
#加法: in-place
y.add_(x) # adds x to y
print(y)
#你可以使用标准的 NumPy 类似的索引操作
print('你可以使用标准的 NumPy 类似的索引操作')
print(x)
print(x[:, 1])
#改变大小:如果你想改变一个 tensor 的大小或者形状,你可以使用 torch.view
x = torch.rand(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())
#如果你有一个元素 tensor ,使用 .item() 来获得这个 value
print('如果你有一个元素 tensor ,使用 .item() 来获得这个 value ')
x = torch.rand(1)
print(x)
print(x.item())
x = torch.rand(2,2)
print(x)
print(x[1, 1].item())
结果:
tensor([[8.4490e-39, 9.6429e-39, 9.2755e-39],
[1.0286e-38, 9.0919e-39, 8.9082e-39],
[9.2755e-39, 8.4490e-39, 1.0194e-38],
[9.0919e-39, 8.4490e-39, 9.9184e-39],
[9.0000e-39, 9.0919e-39, 4.2246e-39]])
tensor([[0.5786, 0.1243, 0.3223],
[0.4955, 0.0371, 0.1434],
[0.3480, 0.9232, 0.7643],
[0.9951, 0.4510, 0.4050],
[0.6481, 0.6690, 0.1541]])
tensor([[ 2.1183, -1.1326, 1.7349],
[ 0.5649, 0.4983, -0.7484],
[-0.9117, 2.0211, -1.3433],
[-1.5944, 0.5537, 0.3468],
[-0.3793, -0.9086, -0.9350]])
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
tensor([5.5000, 3.0000])
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[0.8785, 0.2749, 0.9123],
[0.4716, 0.8834, 0.5591],
[0.8171, 0.9123, 0.7681],
[0.1906, 0.2772, 0.3487],
[0.8511, 0.9399, 0.4900]])
torch.Size([5, 3])
tensor([[1.5998, 0.9139, 1.4348],
[0.8515, 1.7374, 1.1035],
[1.3134, 1.5946, 1.6506],
[1.1726, 0.3148, 1.0928],
[1.0870, 1.0643, 1.2058]])
tensor([[1.5998, 0.9139, 1.4348],
[0.8515, 1.7374, 1.1035],
[1.3134, 1.5946, 1.6506],
[1.1726, 0.3148, 1.0928],
[1.0870, 1.0643, 1.2058]])
tensor([[1.5998, 0.9139, 1.4348],
[0.8515, 1.7374, 1.1035],
[1.3134, 1.5946, 1.6506],
[1.1726, 0.3148, 1.0928],
[1.0870, 1.0643, 1.2058]])
tensor([[1.5998, 0.9139, 1.4348],
[0.8515, 1.7374, 1.1035],
[1.3134, 1.5946, 1.6506],
[1.1726, 0.3148, 1.0928],
[1.0870, 1.0643, 1.2058]])
你可以使用标准的 NumPy 类似的索引操作
tensor([[0.8785, 0.2749, 0.9123],
[0.4716, 0.8834, 0.5591],
[0.8171, 0.9123, 0.7681],
[0.1906, 0.2772, 0.3487],
[0.8511, 0.9399, 0.4900]])
tensor([0.2749, 0.8834, 0.9123, 0.2772, 0.9399])
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
如果你有一个元素 tensor ,使用 .item() 来获得这个 value
tensor([0.6242])
0.6241665482521057
tensor([[0.5151, 0.4767],
[0.9124, 0.7271]])
0.7270835041999817