1 何处用到
yolov3中有一行这样的代码,在此记录一下三个函数的含义
例子中batch_size为int,len(self.anchors_mask[i])=3,self.bbox_attrs=25(voc数据集),input_height, input_width两个参数也均为int。
prediction = input.view(batch_size, len(self.anchors_mask[i]),
self.bbox_attrs, input_height, input_width).permute(0, 1, 3, 4, 2).contiguous()
2 view()
view变换维度,把原先tensor中的数据按行优先的顺序排成一个一维数据,然后按照输入参数要求,组合成其他维度的tensor。
import torch
a=torch.Tensor([[[1,2,3],[4,5,6]]]) # ——> torch.Size([1, 2, 3])
print(a.view(3,2)) # ——> torch.Size([3, 2])
输出:
tensor([[1., 2.],
[3., 4.],
[5., 6.]])
3 permute()
permute将tensor中任意维度利用索引调换。b=a.permute(2,0,1)
,permute里的参数对应的是张量a的维度索引,利用索引来对内部数据调换。
a.permute(2,0,1)
:把a的最后一个维度放到最前面。
import torch
inputs = [[[1, 2 ,3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]
inputs = torch.tensor(inputs)
print("inputs:", inputs, inputs.shape)
outputs = inputs.permute(0, 2, 1)
print("outputs:", outputs, outputs.shape)
输出:
inputs: tensor([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]]) torch.Size([2, 2, 3])
outputs: tensor([[[ 1, 4],
[ 2, 5],
[ 3, 6]],
[[ 7, 10],
[ 8, 11],
[ 9, 12]]]) torch.Size([2, 3, 2])
4 contiguous()
细致理解Pytorch数据布局方式和内存关系可以参考链接
仅理解contiguous()函数,可以理解为一次深拷贝
当调用contiguous()时,会强制拷贝出一份tensor,让它的布局和从头创建的一模一样,但是两个tensor完全没有联系。
5 感谢链接
https://blog.csdn.net/kdongyi/article/details/108180250