文章目录
torch.expand()和torch.repeat() 区别
torch.expand()
对指定的维度进行数值大小的改变,只能改变维大小为1的维,(单数维)不改变的维可以传入-1或者原来的数值。 返回张量的一个新视图,(并不会重新分配内存)可以将张量的单个维度扩大为更大的尺寸。 |
torch.repeat()
沿着指定的维度重复tensor, 不同于expand(),本函数复制的是tensor中的数据
x.repeat(3,1) 在轴0(行))上复制3份,在轴1(列)上复制1份
a=torch.Tensor(1,256,18,18)
a.shape
torch.Size([1,256,18,18])
b=a.repeat(2,1,1,1)
b.shape
torch.Size([2,256,18,18])
b=a.repeat(2)
则会报错:
RuntimeError: Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor
区别:当复制的数据发生变化时,repeat后的数据不会变化,而expand后的数据发生变化
torch.tensor()和torch.Tensor()
在Pytorch中,Tensor和tensor都用于生成新的张量,torch.Tensor()是Python类,更明确的说,是默认张量类型torch.FloatTensor()的别名,torch.tensor()是Python函数。
>>> y=torch.Tensor([2,2,2])
>>> y
tensor([2., 2., 2.])
>>> y.shape
torch.Size([3])
>>> y.type()
'torch.FloatTensor'
>>> x=torch.tensor([2,2,2])
>>> x
tensor([2, 2, 2])
>>> x.shape
torch.Size([3])
>>> x.type()
'torch.LongTensor'
>>> x=torch.tensor(1,64,1,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: tensor() takes 1 positional argument but 4 were given
>>> x=torch.Tensor(1,64,1,1)
>>> x.shape
torch.Size([1, 64, 1, 1])
>>> x.type()
'torch.FloatTensor'
numpy_to_torch() && torch_to_numpy()
def numpy_to_torch(a:np.ndarray):
return torch.from_numpy(a).float().permute(2,0,1).unsqueeze(0)
def torch_to_numpy(a:torch.Tensor):
return a.squeeze(0).permute(1,2,0).numpy()
vot数据集的anno由八个值(Polygon)变为四个值(Rectangle–x,y,w,h)表示
import numpy as np
def convert_vot_anno_to_rect(vot_anno, type):
if len(vot_anno) == 4:
return vot_anno
if type == 'union':
x1 = min(vot_anno[0::2])
x2 = max(vot_anno[0::2])
y1 = min(vot_anno[1::2])
y2 = max(vot_anno[1::2])
return [x1, y1, x2 - x1, y2 - y1]
elif type == 'preserve_area':
if len(vot_anno) != 8:
raise ValueError
vot_anno = np.array(vot_anno)
cx = np.mean(vot_anno[0::2])
cy = np.mean(vot_anno[1::2])
x1 = min(vot_anno[0::2])
x2 = max(vot_anno[0::2])
y1 = min(vot_anno[1::2])
y2 = max(vot_anno[1::2])
A1 = np.linalg.norm(vot_anno[0:2] - vot_anno[2: 4]) * np.linalg.norm(vot_anno[2: 4] - vot_anno[4:6])
A2 = (x2 - x1) * (y2 - y1)
s = np.sqrt(A1 / A2)
w = s * (x2 - x1) + 1
h = s * (y2 - y1) + 1
x = cx - 0.5*w
y = cy - 0.5*h
return [x, y, w, h]
else:
raise ValueError
argsort()
>>> import numpy as np
>>> x=np.array([1,2,8,-4,-1,9])
>>> x
array([ 1, 2, 8, -4, -1, 9])
>>> x.argsort()
array([3, 4, 0, 1, 2, 5])
#将x中的元素从小到大排列,提取其对应的index(索引),然后输出到y
#那如果想从大到小排列呢
>>> x.argsort()[::-1]
array([5, 2, 1, 0, 4, 3])
>>> x.argsort()[0]
3 #找到最小的索引
>>> x.argsort()[-1]
5 #找到最大的索引
>>>