今天在ssd的代码里看到了几个用法,虽说代码是基于pytorch0.4的,但这些用法应该都没有变.
用法1
keep = scores.new(scores.size(0)).zero_().long()
tensor.new(x)
新建一个和此Tensor相同datatype的Tensor; tensor内容为x,若参数为空则新建空tensor [new];
顺便调查了pytorch中多种复制tensor的方法:
[difference-between-clone()-and-new_tensor()]
[methods-comprison]
复制tensor的方法有多种:
y = tensor.new_tensor(x) #a
y = x.clone().detach()
;y = x.detach().clone() #b
y = torch.empty_like(x).copy_(x) #c
y = torch.tensor(x) #d
简言之,clone()在复制tensor的同时复制了它在计算图中的关系,
b, c两种方式运行较快,a,d比较慢
tensor.zero_()
将该tensor的内容改写为0 [zero_]
tensor.long()
将tensor 转成longTensor
同理还有Tensor.double(),Tensor.float()等
用法2
# dets is a n×5 Tensor, where 5 = score(1) + bbox(4)
mask = dets[:, 0].gt(0.).expand(5, dets.size(0)).t()
dets = torch.masked_select(dets, mask).view(-1, 5)
tensor.gt()
是否大于, 返回结果与该tensor形状一样。 [Tensor比大小]
以后根据某列的值选择2D-Tensor中符合要求的行可以参考使用 tensor.expand()
+ torch.masked_select
_select
index_select(x, dim, indices)
: 沿着某dim选值
mask_selec(x, mask)
: 选出x里在mask中相对位置为1的元素