torch.Tensor
生成的张量默认采用数据类型“FloatTensor”,而torch.tensor
则是识别输入数据的数据类型,从而生成对应数据类型的张量:
import torch
t1 = torch.tensor([1,2])
t2 = torch.Tensor([1,2])
print(t1)
print(type(t1)) # <class 'torch.Tensor'>
print(t1.type()) # torch.LongTensor
print("\n")
print(t2)
print(type(t2)) # <class 'torch.Tensor'>
print(t2.type()) # torch.FloatTensor
输出结果:
tensor([1, 2])
<class ‘torch.Tensor’>
torch.LongTensor
tensor([1., 2.])
<class ‘torch.Tensor’>
torch.FloatTensor
import torch
t1 = torch.tensor([1.,2.])
t2 = torch.Tensor([1.,2.])
print(t1)
print(type(t1)) # <class 'torch.Tensor'>
print(t1.type()) # torch.LongTensor
print("\n")
print(t2)
print(type(t2)) # <class 'torch.Tensor'>
print(t2.type()) # torch.FloatTensor
输出结果:
tensor([1., 2.])
<class ‘torch.Tensor’>
torch.FloatTensor
tensor([1., 2.])
<class ‘torch.Tensor’>
torch.FloatTensor
当然,二者都可以通过指定dtype参数来控制生成张量的数据类型,这里就不在展示,说一下我的一个小发现——Tensor不能在创建张量时指定device,而tensor可以:
import torch
device = torch.device('cuda')
t1 = torch.tensor([1.,2.],device=device) # 正常执行
t2 = torch.Tensor([1.,2.],device=device) # 抛出错误
(PS:后续的使用中发现新的差异将会继续更新)