pytorch 中 区分 torch.tensor() 和 torch.Tensor()

torch.tensor()

  • torch.tensor()仅仅是python函数https://pytorch.org/docs/stable/torch.html#torch.tensor ,将数据的数据类型转化为tensor:
    • data:(其中data可以是:list, tuple, NumPy ndarray, scalar和其他类型。)
    • dtype: 可以使用参数dtype来指定张量的数据类型,
    • requires_grad: 使用参数requires_grad来指定张量是否需要计算梯度。只有计算了梯度的张量,才能在深度网络优化时根据梯度的大小进行更新。
torch.tensor(data, dtype=None, device=None, requires_grad=False)
  • 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'
  • tensor的维度可以通过.shape()查看;并可以使用.size()方法计算张量的形状大小;使用.numel()方法计算张量中包含元素的数量。 

torch.Tensor()

  • torch.Tensor()是python类,更明确地说,是默认张量类型torch.FloatTensor()的别名
  • 可以根据形状参数生成特定尺寸的张量
a = torch.Tensor(2,3)
print(a, a.type())
# tensor([[1.3563e-19, 1.7753e+28, 1.3458e-14],
#         [2.3335e-09, 2.3301e-09, 2.3301e-09]]) torch.FloatTensor

b = torch.FloatTensor(2,3)
print(b, b.type())
# tensor([[-4.0056e+18,  4.5737e-41, -4.0056e+18],
#         [ 4.5737e-41,  0.0000e+00,  0.0000e+00]]) torch.FloatTensor
  • 可以根据指定的数据生成张量,也就是类似于torch.tensor(),将其他形式的数据转化为tensor的形式,区别在于生成的是单精度浮点类型的张量。
a = torch.tensor([2,3])
print(a, a.type())
# tensor([2, 3]) torch.LongTensor

b = torch.Tensor([2,3])
print(b, b.type())
# tensor([2., 3.]) torch.FloatTensor

c = torch.FloatTensor([2,3])
print(c, c.type())
# tensor([2., 3.]) torch.FloatTensor

部分参考:https://www.jianshu.com/p/d83149dcdd79

猜你喜欢

转载自blog.csdn.net/m0_46483236/article/details/124018963