张量

Factory

arange: itoa

1
2
x = torch.arange(1, 10)
print(x) # tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])

zeros: 0张量

1
2
3
4
5
6
x = torch.zeros(5, 4)
print(x) # tensor([[0., 0., 0., 0.],
         #         [0., 0., 0., 0.],
         #         [0., 0., 0., 0.],
         #         [0., 0., 0., 0.],
         #         [0., 0., 0., 0.]])

ones: 1张量

1
2
3
4
5
6
x = torch.ones(5, 4)
print(x) # tensor([[1., 1., 1., 1.],
         #         [1., 1., 1., 1.],
         #         [1., 1., 1., 1.],
         #         [1., 1., 1., 1.],
         #         [1., 1., 1., 1.]])

randn: 随机

1
2
3
4
x = torch.randn(3, 4)
print(x) # tensor([[ 1.9417,  1.3853,  0.2366,  0.4691],
         #         [ 0.2756, -0.6938, -0.9213,  0.3990],
         #         [-0.7935, -0.2569,  0.4597, -1.5561]])

Getter

.shape: 张量形状

1
2
x = torch.ones(5, 4)
print(x.shape) # torch.Size([5, 4]) 

.numel(): 元素总个数

1
2
x = torch.ones(5, 4)
print(x.numel()) # 20

Unary 运算

.reshape(): 改变形状

1
2
3
4
5
6
7
8
9
x = torch.arange(12)

print(x) 
# tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

print(x.reshape(3, 4))
# tensor([[ 0,  1,  2,  3],
#         [ 4,  5,  6,  7],
#         [ 8,  9, 10, 11]])

运算

算术运算

张量的二元算术计算都是 逐元素的 (elementwise)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
print(f"x: {x}")
print(f"y: {y}")
print(f"x + y: {x + y}")
print(f"x - y: {x - y}")
print(f"x * y: {x * y}")
print(f"x / y: {x / y}")

# x: tensor([1, 2, 3])
# y: tensor([4, 5, 6])
# x + y: tensor([5, 7, 9])
# x - y: tensor([-3, -3, -3])
# x * y: tensor([ 4, 10, 18])
# x / y: tensor([0.2500, 0.4000, 0.5000])

连接运算

1
torch.concat((x, y, z, ...), dim=1) # dim < total_dimension