torch.ones_like(),expand_as(),expend()等torch.repeat

 

https://blog.csdn.net/Arthur_Holmes/article/details/104267662 

https://blog.csdn.net/weixin_39568781/article/details/110066146

https://blog.csdn.net/qq_40263477/article/details/107054675

https://blog.csdn.net/whitesilence/article/details/119575617

 

 

 

pytorch中的expand()和expand_as()函数
1.expand()函数:

(1)函数功能:

expand()函数的功能是用来扩展张量中某维数据的尺寸,它返回输入张量在某维扩展为更大尺寸后的张量。

扩展张量不会分配新的内存,只是在存在的张量上创建一个新的视图(关于张量的视图可以参考博文:由浅入深地分析张量),而且原始tensor和处理后的tensor是不共享内存的。

expand()函数括号中的输入参数为指定经过维度尺寸扩展后的张量的size。

(2)应用举例:

 

RuntimeError: Can’t call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.

待转换类型的PyTorch Tensor变量带有梯度,直接将其转换为numpy数据将破坏计算图,因此numpy拒绝进行数据转换,实际上这是对开发者的一种提醒。如果自己在转换数据时不需要保留梯度信息,可以在变量转换之前添加detach()调用。

 

 

 

 

expand的含义:为1的维度可以变大维度或者维度数增多

tensor_1.expand(size):把tensor_1扩展成size的形状
tensor_1.expand_as(tensor_2) :把tensor_1扩展成和tensor_2一样的形状

 

 

TORCH.ONES_LIKE

torch.ones_like(input*dtype=Nonelayout=Nonedevice=Nonerequires_grad=Falsememory_format=torch.preserve_format) → Tensor

Returns a tensor filled with the scalar value 1, with the same size as inputtorch.ones_like(input) is equivalent to torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device).

 

 

 

 

posted on 2022-05-09 16:05  lmqljt  阅读(510)  评论(0编辑  收藏  举报

导航