Pytorch中.new()的作用详解

作者:悲恋花丶无心之人 时间:2023-12-11 10:28:54 

一、作用

创建一个新的Tensor,该Tensor的typedevice都和原有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_inputstypedevice都与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')

来源:https://blog.csdn.net/qq_36556893/article/details/100014333

标签:Pytorch,new
0
投稿

猜你喜欢

  • 验证码的最高境界

    2008-05-08 14:17:00
  • 优化MySQL数据库性能的八大“妙手”

    2007-11-18 14:49:00
  • 使用python+pandas读写xlsx格式中的数据

    2023-03-25 00:55:16
  • Python的进程,线程和协程实例详解

    2021-05-05 04:35:59
  • Python基础之输入,输出与高阶赋值详解

    2023-05-21 10:00:32
  • 基于Node.js模板引擎教程-jade速学与实战1

    2024-05-13 09:28:29
  • JS数组中对象去重操作示例

    2024-04-18 10:57:31
  • python实现批量解析邮件并下载附件

    2023-07-05 02:32:16
  • Oracle数据库的安全策略

    2010-07-31 13:13:00
  • 验证码-挑战你的智慧

    2008-09-10 13:08:00
  • vue中的数据绑定原理的实现

    2024-05-05 09:09:34
  • 交互设计实用指南系列(12)—避免出错

    2010-04-12 13:02:00
  • 浅析Python 中的 WSGI 接口和 WSGI 服务的运行

    2023-02-18 14:45:40
  • sqlserver 巧妙的自关联运用

    2012-07-21 14:55:12
  • python实现决策树C4.5算法详解(在ID3基础上改进)

    2022-05-06 08:01:57
  • 详解Python的爬虫框架 Scrapy

    2021-10-23 10:43:31
  • Python素数检测实例分析

    2021-05-22 02:11:41
  • python playwright 自动等待和断言详解

    2021-04-04 19:39:01
  • 闲聊html和body标签

    2009-02-21 10:50:00
  • js禁止Backspace键使浏览器后退的实现方法

    2024-04-17 09:54:05
  • asp之家 网络编程 m.aspxhome.com