Pytorch中.new()的作用

举报
悲恋花丶无心之人 发表于 2021/02/02 23:47:36 2021/02/02
【摘要】 目录 一、作用 二、使用方法 三、具体代码 四、实际应用(添加噪声) 一、作用 创建一个新的Tensor,该Tensor的type和device都和原有Tensor一致,且无内容。 二、使用方法 如果随机定义一个大小的Tensor,则新的Tensor有两种创建方法,如下: inputs = torch.randn(m, n) new_inputs = i...

目录

一、作用

二、使用方法

三、具体代码

四、实际应用(添加噪声)


一、作用

创建一个新的Tensor,该Tensor的typedevice都和原有Tensor一致,且无内容。


二、使用方法

如果随机定义一个m\times n大小的Tensor,则新的Tensor有两种创建方法,如下:


  
  1. inputs = torch.randn(m, n)
  2. new_inputs = inputs.new()
  3. new_inputs = torch.Tensor.new(inputs)

三、具体代码


  
  1. import torch
  2. rectangle_height = 1
  3. rectangle_width = 4
  4. inputs = torch.randn(rectangle_height, rectangle_width)
  5. for i in range(rectangle_height):
  6. for j in range(rectangle_width):
  7. inputs[i][j] = (i + 1) * (j + 1)
  8. print("inputs:", inputs)
  9. new_inputs = inputs.new()
  10. print("new_inputs:", new_inputs)
  11. # Constructs a new tensor of the same data type as self tensor.
  12. print(new_inputs.type(), inputs.type())
  13. print('')
  14. inputs = inputs.squeeze(dim=0)
  15. print("inputs:", inputs)
  16. # new_inputs = inputs.new()
  17. new_inputs = torch.Tensor.new(inputs)
  18. print("new_inputs:", new_inputs)
  19. # Constructs a new tensor of the same data type as self tensor.
  20. print(new_inputs.type(), inputs.type())
  21. if torch.cuda.is_available():
  22. device = torch.device("cuda")
  23. inputs, new_inputs = inputs.to(device), new_inputs.to(device)
  24. print(inputs.device, new_inputs.device)

结果如下:

可以看到不论inputs是多少维的,新建的new_inputstypedevice都与inputs保持一致


  
  1. inputs: tensor([[1., 2., 3., 4.]])
  2. new_inputs: tensor([])
  3. torch.FloatTensor torch.FloatTensor
  4. inputs: tensor([1., 2., 3., 4.])
  5. new_inputs: tensor([])
  6. torch.FloatTensor torch.FloatTensor
  7. cuda:0 cuda:0

四、实际应用(添加噪声)

可以对Tensor添加噪声,添加如下代码即可实现:


  
  1. noise = inputs.data.new(inputs.size()).normal_(0,0.01)
  2. print(noise)

结果如下:

tensor([ 0.0062,  0.0137, -0.0209,  0.0072], device='cuda:0')
 

 

文章来源: nickhuang1996.blog.csdn.net,作者:悲恋花丶无心之人,版权归原作者所有,如需转载,请联系作者。

原文链接:nickhuang1996.blog.csdn.net/article/details/100014333

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。