pytorch中stack和cat的以及to_tensor的坑

本文探讨了PyTorch中两种常见的数据堆叠方法:stack与cat的区别及应用场景。通过实例对比,阐述了它们如何影响张量的维度,并指导如何根据实际需求选择合适的方法。

初入计算机视觉遇到的一些坑

1.pytorch中转tensor

x=np.random.randint(10,100,(10,10,10))
x=TF.to_tensor(x)
print(x)

这个函数会对输入数据进行自动归一化,比如有时候我们需要将0-255的图片转为numpy类型的数据,则会自动转为0-1之间
2.stack和cat之间的差别

stack
x=torch.randn((1,2,3))
y=torch.randn((1,2,3))
z=torch.stack((x,y))#默认dim=0
print(z.shape)
#torch.Size([2, 1, 2, 3])

所以stack的之后的数据也就很好理解了,z[0,...]的数据是x,z[1,...]的数据是y。

cat
z=torch.cat((x,y))
print(z.size())
#torch.Size([2, 2, 3])

cat之后的数据 z[0,:,:]是x的值,z[1,:,:]是y的值。

其中最关键的是stack之后的数据的size会多出一个维度,而cat则不会,有一个很简单的例子来说明一下,比如要训练一个检测模型,label是一些标记点,eg:[x1,y1,x2,y2]

送入网络的加上batchsize则时Size:[batchsize,4],如果我已经有了两堆数据,data1:Size[128,4],data2:Size[128,4],需要将这两个数据合在一起的话目标data:Size[256,4]。显然我们要做的是:torch.cat((data1,data2))
如果我们的数据是这样:有100个label,每一个label被放进一个list(data)中,[[x1,y1,x2,y2],[x1,y1,x2,y2],...]其中data是一个list长度为100,而list中每一个元素是张图片的标签,size为[4]我们需要将他们合一起成为一Size:[100,4]的的数据。显然我们要做的是torch.stack(data)。而且torch.stack的输入参数为list类型!

Traceback (most recent call last): File "/root/.pycharm_helpers/pydevd_asyncio/pydevd_asyncio_utils.py", line 117, in _exec_async_code result = func() File "<input>", line 1, in <module> File "/usr/local/lib/python3.8/dist-packages/torch/_tensor.py", line 338, in __repr__ return torch._tensor_str._str(self, tensor_contents=tensor_contents) File "/usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py", line 481, in _str return _str_intern(self, tensor_contents=tensor_contents) File "/usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py", line 447, in _str_intern tensor_str = _tensor_str(self, indent) File "/usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py", line 270, in _tensor_str formatter = _Formatter(get_summarized_data(self) if summarize else self) File "/usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py", line 302, in get_summarized_data return torch.stack([get_summarized_data(x) for x in (start + end)]) File "/usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py", line 302, in <listcomp> return torch.stack([get_summarized_data(x) for x in (start + end)]) File "/usr/local/lib/python3.8/dist-packages/torch/_tensor_str.py", line 295, in get_summarized_data return torch.cat((self[:PRINT_OPTS.edgeitems], self[-PRINT_OPTS.edgeitems:])) RuntimeError: CUDA error: no kernel image is available for execution on the device CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值