1 什么是张量?
张量(Tensor)是多维数组结构,在人工智能范畴应用广泛,比方输入彩色图片便是3维张量——RGB三维且每维都是二维平面像素矩阵。
下面这张表直观地总结了张量的情势,这张表可以解决大部门的张量明白标题
维数图例名称0 标量1 向量2 矩阵3 三阶张量 N N N N N N阶张量 2 Pytorch数据类型与转化
数据类型CPU TensorGPU Tensor32位浮点torch.FloatTensortorch.cuda.FloatTensor64位浮点torch.DoubleTensortorch.cuda.DoubleTensor16位半精度浮点N/Atorch.cuda.HalfTensor8位无符号整型torch.ByteTensortorch.cuda.ByteTensor8位有符号整型torch.CharTensortorch.cuda.CharTensor16位有符号整型torch.ShortTensortorch.cuda.ShortTensor32位有符号整型torch.IntTensortorch.cuda.IntTensor64位有符号整型torch.LongTensortorch.cuda.LongTensor Pytorch中Tensor数据类型的转换可以利用
- 显式的type(new_type)
- 隐式的type_as(var)
举比方下:
- a = torch.Tensor(2, 2)
- b = a.type(torch.DoubleTensor)
- c = a.type_as(b)
- >> a: tensor([[0.0000e+00, 0.0000e+00],
- [8.4078e-45, 0.0000e+00]])
- >> b: tensor([[0.0000e+00, 0.0000e+00],
- [8.4078e-45, 0.0000e+00]], dtype=torch.float64)
- >> c: tensor([[0.0000e+00, 0.0000e+00],
- [8.4078e-45, 0.0000e+00]], dtype=torch.float64)
复制代码 3 张量Tensor的创建
张量Tensor重要的创建方法如下所示。
3.1 类型创建
创建方法
- torch.Tensor()
- torch.DoubleTensor()
- …
实例
- b = torch.cuda.DoubleTensor(2,2)
- >> b: tensor([[0., 0.],
- [0., 0.]], device='cuda:0', dtype=torch.float64)
复制代码 3.2 序列转换
创建方法
- torch.Tensor(list)
- torch.Tensor(narray)
实例
- a = torch.DoubleTensor([[1, 2],[3, 4]])
- >> a: tensor([[1., 2.],
- [3., 4.]], dtype=torch.float64)
复制代码 3.3 0/1张量
创建方法
- torch.zeros()
- torch.ones()
实例
- a = torch.ones(2,2)
- >> a: tensor([[1., 1.],
- [1., 1.]])
复制代码 3.4 对角张量
创建方法
实例
- a = torch.eye(2,2)
- >> a: tensor([[1., 0.],
- [0., 1.]])
复制代码 3.5 正态张量
创建方法
实例
- a = torch.randn(2,2)
- >> a: tensor([[-0.0451, -0.1602],
- [-0.1116, 0.8266]])
复制代码 3.6 随机向量
创建方法
- torch.randperm(n):将0~n-1的整数随机分列成向量
实例
- a = torch.randperm(3)
- >> a: tensor([2, 0, 1])
复制代码 3.7 线性张量
创建方法
- torch.arrange(s,e,step):天生从s到e隔断step的向量
- torch.linspace(s,e,num):天生从s到e共num的匀称向量
实例
- a = torch.arange(1,8,3)
- >> tensor([1, 4, 7])
- b = torch.linspace(1,8,3)
- >> tensor([1.0000, 4.5000, 8.0000])
复制代码 4 张量Tensor的索引
对于一个给定Tensor,可通过Tensor的shape属性或size()方法检察其维度,通过numel()方法检察元素总数
- a = torch.eye(3,3)
- print("shape维度", a.shape)
- print("size维度", a.size())
- print("numel元素个数", a.numel())
- >> shape维度 torch.Size([3, 3])
- >> size维度 torch.Size([3, 3])
- >> numel元素个数 9
复制代码 Tensor维度按从左到右次序分配dim索引号如下,新增维度的dim索引号总为0

具体的索引方式如下,设a=torch.Tensor([[0,1],[2,3]]))
4.1 下标索引
索引方法
实例
- a[1]
- >> tensor([2., 3.])
- a[0,1]
- >> tensor(1.)
复制代码 4.2 条件索引
索引方法
- tensor>0:符合条件为True
- tensor[tensor>0]:取出符合条件的元素
- torch.nonzero(tensor):取出非零元素坐标
实例
- a>0
- >> tensor([[False, True],
- [ True, True]])
- a[a>0]
- >> tensor([1., 2., 3.])
- torch.nonzero(a)
- >> tensor([[0, 1],
- [1, 0],
- [1, 1]])
复制代码 4.3 附加控制索引
索引方法
- torch.where(condition,x,y):两个同型张量x、y,符合条件输出x相应位置元素,否则输出y
- tensor.clamp(min,max):限定元素极值
实例
- torch.where(a > 1, torch.full_like(a, 1), a)
- >> tensor([[0., 1.],
- [1., 1.]])
- a.clamp(1,2)
- >> tensor([[1., 1.],
- [2., 2.]])
复制代码 |