1 . 从接口的角度来讲,对 tensor 的操作可分为两类:

  • torch.function,如 torch.save 等;
  • 另一类是 tensor.function,如 tensor.view 等。

为了方便使用,对 tensor 的大部分操作同时支持这两类接口,如 torch.sum(torch.sum(a, b))tensor.sum(a.sum(b)) 功能等价。

2 . 在 Pytorch 中新建 tensor 的方法具体有很多,如下表:

函数 功能
Tensor(*sizes) 基础构造函数
tensor(data) 类似 np.array 的构造函数
ones(*sizes) 全 1 Tensor
zeros(*sizes) 全 0 Tensor
eye(*sizes) 对角线为 1,其他为 0
arange(s, e, steps) 从 s 到 e,步长为 step
linspace(s, e, steps) 从 s 到 e,均匀切分成 steps 份
rand/randn(*sizes) 均匀/标准分布
normal(mean, std)/uniform(from, to) 正态分布/均匀分布
randperm(m) 随机排列

这些创建方法都可以在创建的时候指定数据类型 dtype 和存放 device(cpu/gpu)。  

Input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import torch as t

a = t.Tensor(2, 3) # 指定 tensor 的形状,其数值取决于内存空间的状态,print 的时候可能 overflow

b = t.Tensor([[1, 2, 3], [4, 5, 6]]) # 用 list 的数据创建 tensor
print(b)

print(b.tolist()) # 把 tensor 转为 list

b_size = b.size()
print(b_size)

print(b.numel()) # 返回 b 中元素总个数,等价于 b.nelement()

c = t.Tensor(b_size) # 创建一个和 b 形状一样的 tensor
d = t.Tensor((2, 3)) # 创建一个元素为 2 和 3 的 tensor

print(c.shape) # 与 c.size() 等价

Output:

t.Tensor(*sizes) 创建 tensor 时,系统不会马上分配空间,只会计算剩余的内存是否足够使用,使用到 tensor 时才会分配,而其他操作都是在创建完 tensor 之后马上进行空间分配。

Input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import torch as t

print(t.ones(2, 3))

print(t.zeros(2, 3))

print(t.arange(1, 6, 2))

print(t.linspace(1, 10, 3))

print(t.randn(2, 3, device=t.device('cpu')))

print(t.randperm(5)) # 长度为 5 的随机排列

print(t.eye(2, 3, dtype=t.int)) # 对角线为 1,不要求行数与列数一致

scalar = t.tensor(3.14159)
print('scalar: %s, shape of scalar: %s' % (scalar, scalar.shape))

vector = t.tensor([1, 2])
print('vector: %s, shape of vector: %s' % (vector, vector.shape))

tensor = t.Tensor(1, 2)
print(tensor.shape)

matrix = t.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
print(matrix)
print(matrix.shape)

ten = t.tensor([[0.11111, 0.22222, 0.33333]], dtype=t.float64, device=t.device('cpu'))
print(ten)

empty_tensor = t.tensor([])
print(empty_tensor.shape)

Output:


笔记来源:《pytorch-book》