【PyTorch】Tensor和tensor的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tfcy694/article/details/85338745

本文列举的框架源码基于PyTorch1.0,交互语句在0.4.1上测试通过

import torch

在PyTorch中,Tensor和tensor都能用于生成新的张量:

>>> a=torch.Tensor([1,2])
>>> a
tensor([1., 2.])
>>> a=torch.tensor([1,2])
>>> a
tensor([1, 2])

但是这二者的用法有什么区别呢?我没有找到合适的中文资料,英文的资料如 https://discuss.pytorch.org/t/what-is-the-difference-between-tensor-and-tensor-is-tensor-going-to-be-deprecated-in-the-future/17134/8 也已经过时了,那就自己动手丰衣足食吧。

首先,我们需要明确一下,torch.Tensor()是python类,更明确地说,是默认张量类型torch.FloatTensor()的别名,torch.Tensor([1,2])会调用Tensor类的构造函数__init__,生成单精度浮点类型的张量。

>>> a=torch.Tensor([1,2])
>>> a.type()
'torch.FloatTensor'

而torch.tensor()仅仅是python函数:https://pytorch.org/docs/stable/torch.html#torch.tensor ,函数原型是:

torch.tensor(data, dtype=None, device=None, requires_grad=False)

其中data可以是:list, tuple, NumPy ndarray, scalar和其他类型。
torch.tensor会从data中的数据部分做拷贝(而不是直接引用),根据原始数据类型生成相应的torch.LongTensor、torch.FloatTensor和torch.DoubleTensor。

>>> a=torch.tensor([1,2])
>>> a.type()
'torch.LongTensor'
>>> a=torch.tensor([1.,2.])
>>> a.type()
'torch.FloatTensor'
>>> a=np.zeros(2,dtype=np.float64)
>>> a=torch.tensor(a)
>>> a.type()
'torch.DoubleTensor'

这里再说一下torch.empty(),根据 https://pytorch.org/docs/stable/torch.html?highlight=empty#torch.empty ,我们可以生成指定类型、指定设备以及其他参数的张量,由于torch.Tensor()只能指定数据类型为torch.float,所以torch.Tensor()可以看做torch.empty()的一个特殊情况。

最后放一个小彩蛋

>>> a=torch.tensor(1)
>>> a
tensor(1)
>>> a.type()
'torch.LongTensor'
>>> a=torch.Tensor(1)
>>> a
tensor([0.])
>>> a.type()
'torch.FloatTensor'

猜你喜欢

转载自blog.csdn.net/tfcy694/article/details/85338745