一、作用
创建一个新的Tensor,该Tensor的type和device都和原有Tensor一致,且无内容。
二、使用方法
如果随机定义一个大小的Tensor,则新的Tensor有两种创建方法,如下:
inputs = torch.randn(m, n) new_inputs = inputs.new() new_inputs = torch.Tensor.new(inputs)
三、具体代码
import torch rectangle_height = 1 rectangle_width = 4 inputs = torch.randn(rectangle_height, rectangle_width) for i in range(rectangle_height): for j in range(rectangle_width): inputs[i][j] = (i + 1) * (j + 1) print("inputs:", inputs) new_inputs = inputs.new() print("new_inputs:", new_inputs) # Constructs a new tensor of the same data type as self tensor. print(new_inputs.type(), inputs.type()) print('') inputs = inputs.squeeze(dim=0) print("inputs:", inputs) # new_inputs = inputs.new() new_inputs = torch.Tensor.new(inputs) print("new_inputs:", new_inputs) # Constructs a new tensor of the same data type as self tensor. print(new_inputs.type(), inputs.type()) if torch.cuda.is_available(): device = torch.device("cuda") inputs, new_inputs = inputs.to(device), new_inputs.to(device) print(inputs.device, new_inputs.device)
结果如下:
可以看到不论inputs是多少维的,新建的new_inputs的type和device都与inputs保持一致
inputs: tensor([[1., 2., 3., 4.]]) new_inputs: tensor([]) torch.FloatTensor torch.FloatTensor inputs: tensor([1., 2., 3., 4.]) new_inputs: tensor([]) torch.FloatTensor torch.FloatTensor cuda:0 cuda:0
四、实际应用(添加噪声)
可以对Tensor添加噪声,添加如下代码即可实现:
noise = inputs.data.new(inputs.size()).normal_(0,0.01) print(noise)
结果如下:
tensor([ 0.0062, 0.0137, -0.0209, 0.0072], device='cuda:0')
以上这篇Pytorch中.new()的作用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- Merryland《Merryland》[320K/MP3][69.48MB]
- 苏芮.1991-停在我心里的温柔【福茂】【WAV+CUE】
- 苏慧伦.2020-面面Every.Side.of.Me【相信音乐】【WAV+CUE】
- 群星.1991-不一样的感觉REMIX【宝丽金】【WAV+CUE】
- 银霞.1983-《你那好冷的小手》珍藏纪念版[WAV分轨]
- 银霞.2002-《国语巨星专辑VOL.3》2CD台湾版[WAV+CUE]
- 金池刘罡《昨日情歌HQ》头版限量编号[低速原抓WAV+CUE]
- 段奥娟.2024-23·岁碎念【白米范】【FLAC分轨】
- 顺子.2001-昨日·唯一·更多·顺子自选辑【魔岩】【WAV+CUE】
- 无印良品.1999-私藏三首·原创相对论(EP)【滚石】【WAV+CUE】
- Merryland《Merryland》[FLAC/分轨][170.22MB]
- 庄锭欣 ELKIE《没有你的未来》[320K/MP3][15.78MB]
- 庄锭欣 ELKIE《没有你的未来》[FLAC/分轨][36MB]
- TchaikovskySwanLake,Op.20柴可夫斯基天鹅湖(2013)SACD[Hi-Res]
- 24bit达人艺典《琴歌终极版》整轨WAV+CUE