【pytorch学习】torch.tensor

这是一个常用的api 这里对其尽可能描述

torch.tensor

torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor
使用数据**data**构造一个tensor

'''
Returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument size.

Parameters
	data (array_like) – Initial data for the tensor. Can be a list, tuple, NumPy ndarray, scalar, and other types.
	
	dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.
	
	device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
	
	requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
	

'''

参数说明

data : 使用该数据初始化tensor,可以是一个list tuple NumPy ;其实这里也可以是一个tensor

dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, infers data type from data.

dtype:(可选)不设置值 那么tensor的数据类型就是和data的数据类型是一致的,如果需要设置那就是torch.dtype的那几个。作用是指定返回tensor的数据类型

device:(可选)就是创建的tensor存放的device,这里就不做赘述了,大致概念了解看这里\

requires_grad: (可选)是bool 类型的值,默认值是False .因为 pytorch 后期的版本将Varibale 和Tensor进行合并了,这里的如果设置为Flase 表示再反响传播的时候不会对这个节点机型求导,如果你对tensorflow熟悉,

例子

demo1
y=torch.tensor([[1,2,3]])
print(y) # 这里的输出的y的是  tensor([[1, 2, 3]])

其他注意事项

为了能够很好的理解下面的这段话,首先这里讲解一下 detach()

detach就是截断反向传播的梯度流。
Returns a new Variable, detached from the current graph。将某个node变成不需要梯度的Varibale。因此当反向传播经过这个node时,梯度就不会从这个node往前面传播。

torch.tensor()在执行的时候是将data进行copy了一份 如果不想copy可以根据data的类型使用不同的代码,这里给出pytorch 官方的提示:
在这里插入图片描述

关于detach概念和作用请看这篇博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值