GitHub链接
张量的基本概念.
数据类型
张量的数据类型 (dtype) 基本和numpy.array一致, 但不支持 str 类型. 包括:
torch.float64(torch.double), torch.float32(torch.float), torch.float16, torch.int64(torch.long), torch.int32(torch.int), torch.int16, torch.int8, torch.uint8, torch.bool
|
一般使用torch.float32类型.
i = torch.tensor(1, dtype=torch.int32) x = torch.tensor(2.0, dtype=torch.double)
i = torch.IntTensor(1) x = torch.Tensor(np.array(2.0)) b = torch.BoolTensor(np.array([1,0,2,0]))
i = torch.tensor(1) x = i.float() y = i.type(torch.float) z = i.type_as(x)
|
张量的维度
标量 0 维, 向量 1 维, 矩阵 2 维, 彩色图像有 RGB 三维, 可以用 3 维张量表示, 视频还有时间维, 可以用 4 维.
省流: 有几层中括号就是几维.
tensor3 = torch.tensor([[[1.0,2.0],[3.0,4.0]],[[5.0,6.0],[7.0,8.0]]]) print(tensor3) print(tensor3.dim())
tensor4 = torch.tensor([[[[1.0,1.0],[2.0,2.0]],[[3.0,3.0],[4.0,4.0]]], [[[5.0,5.0],[6.0,6.0]],[[7.0,7.0],[8.0,8.0]]]]) print(tensor4) print(tensor4.dim())
|
张量的尺寸
可以使用 shape 属性或 size () 方法查看张量在每一维的长度, 使用 view 方法或 reshape 方法改变张量的尺寸.
vector = torch.arange(0,12) print(vector) print(vector.shape)
matrix34 = vector.view(3,4) print(matrix34) print(matrix34.shape)
matrix43 = vector.view(4,-1) print(matrix43) print(matrix43.shape)
|
view 要求数据是连续存放的, 转置等操作后, 数据不再连续存放, 可以使用 reshape 方法.
matrix26 = torch.arange(0,12).view(2,6) print(matrix26) print(matrix26.shape) matrix62 = matrix26.t() print(matrix62.is_contiguous())
matrix34 = matrix62.reshape(3,4) print(matrix34)
|
张量和 numpy 数组
可以用 numpy 方法从张量得到 numpy 数组, 也可以用torch.from_numpy从 numpy 数组得到张量. 这样得到的张量和数组共享内存, 改变其中一个, 另一个也会改变. 可以通过 clone 方法中断这种改变.
可以用 item 方法从标量张量得到对应数值, 通过 tolist 方法从张量得到对应的数值列表.
arr = np.zeros(3) tensor = torch.from_numpy(arr) print(arr) print(tensor)
np.add(arr,1, out = arr) print(arr) print(tensor)
tensor = torch.zeros(3) arr = tensor.numpy() print(tensor) print(arr)
tensor.add_(1) print(tensor) print(arr)
tensor = torch.zeros(3) arr = tensor.clone().numpy()
scalar = torch.tensor(1.0) s = scalar.item() print(s) print(type(s)) tensor = torch.rand(2, 2) t = tensor.tolist() print(t) print(type(t))
|