Torch的索引与形变

>>> a = torch.Tensor([[1,2],[3,4]])
>>> a
tensor([[1., 2.],
[3., 4.]])
>>> a[1] 类似python中的列表的取值
tensor([3., 4.])
>>> a[0]
tensor([1., 2.])
>>> a > 0 返回布尔值或者0,1
tensor([[True, True],
[True, True]])
>>> a = torch.Tensor([[0,2],[3,4]])
>>> a > 0
tensor([[False, True],
[ True, True]])
>>> a[a>0] 类似于列表
tensor([2., 3., 4.])
>>> torch.nonzero(a) 返回非0的坐标
tensor([[0, 1],
[1, 0],
[1, 1]])
>>> torch.full_like(a,1)   将a中的值全部为1
tensor([[1., 1.],
[1., 1.]])
>>> torch.where(a>1,torch.full_like(a,1),a) 条件判断 条件成立则为前者,条件不成立则为后者
tensor([[0., 1.],
[1., 1.]])
>>> a.clamp(1,6)  限制最小值为1,最大值为6
tensor([[1., 2.],
[3., 4.]])

 

 

Tensor的变形

>>> b = a.resize(2,2)
>>> b
tensor([[1, 2],
[3, 4]])
>>> b = a.reshape(2,2)
>>> b
tensor([[1, 2],
[3, 4]])
>>> b = a.reshape(1,4)
>>> b
tensor([[1, 2, 3, 4]])
>>> b = a.resize_(2,7)
>>> b
tensor([[ 1, 2, 3,
4, 25896191785238631, 27866512327901300,
32932988893003880],
[32088589733920884, 26740517931057249, 27866495148425318,
30962724186423412, 26740530815434867, 32651548277211241,
31525394966315103]])
>>> b = a.resize_(1,2)    #a.resize_()可以直接改变Tensor的尺寸(在原地改变)如果超过原来尺寸则会重新分配内存,多出的部分置0,如果小于原来的Tensor大小则剩余的部分仍然会隐藏保留。
>>> b
tensor([[1, 2]])

#resize() reshape() view() 在括号中输入矩阵的尺寸可以直接修改 但不能超过原来的Tensor尺寸。。。

 

>>> a = torch.randn(2,2,3)
>>> a
tensor([[[ 1.9844, -1.1686, 0.1745],
[ 0.9595, 1.4640, -0.5703]],

[[-1.0130, -0.1706, 0.6245],
[ 0.7703, -1.0161, -0.1846]]])
>>> b = a.transpose(0,1)
>>> b
tensor([[[ 1.9844, -1.1686, 0.1745],
[-1.0130, -0.1706, 0.6245]],

[[ 0.9595, 1.4640, -0.5703],
[ 0.7703, -1.0161, -0.1846]]])
>>> a.permute(2,1,0)
tensor([[[ 1.9844, -1.0130],
[ 0.9595, 0.7703]],

[[-1.1686, -0.1706],
[ 1.4640, -1.0161]],

[[ 0.1745, 0.6245],
[-0.5703, -0.1846]]])
>>> a
tensor([[[ 1.9844, -1.1686, 0.1745],
[ 0.9595, 1.4640, -0.5703]],

[[-1.0130, -0.1706, 0.6245],
[ 0.7703, -1.0161, -0.1846]]])
>>>

 

squeeze()和 unsqueeze()来处理size为1的维度

expand()和 expend_as()来复制拓展size为1为指定维度大小。

##expand和repeat可以实现维度的拓展

expand拓展维度的时候,如果维度要是不想变化,就用-1代替,

 而且拓张的时候只能从1扩张成M 不可从n拓张成M

>>> b.shape
torch.Size([1, 32, 1, 1])
>>> b.expand(4,-1,4,4).shape
torch.Size([4, 32, 4, 4])

 

repeat的使用

想重复几次就在repeat()中就重复的数不重复的话就是1

>>> b.shape
torch.Size([1, 32, 1, 1])
>>> b.repeat(1,1,4,4).shape
torch.Size([1, 32, 4, 4])
>>>

 

posted @ 2021-01-19 11:45  _八级大狂风  阅读(461)  评论(0编辑  收藏  举报