1. 常用操作
1.1 GPU判断
# 判断是否有GPU,若有则进行部署
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
或
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device.type)
# cpu
# 进行部署
x = torch.tensor([1, 2, 3], device=device)
data = data.to(device)
1.2 tensor与Tensor的区别
x = torch.Tensor([1, 2])
# tensor([1., 2.])
print(x.type())
# torch.FloatTensor
y = torch.tensor([1, 2])
# tensor([1, 2])
print(y.type())
# torch.LongTensor
torch.tensor(5.6)
# tensor(5.6000)
torch.Tensor(5.6)
# TypeError: new(): data must be a sequence (got float)
torch.Tensor([5.6])
# tensor([5.6000])
2. 分布
2.1 指定分布的tensor
# 设定随机种子
torch.manual_seed(123)
# 值在0-1之间的均匀分布
y = torch.rand(5)
# tensor([0.3423, 0.2636, 0.8128, 0.1354, 0.3517])
# 均值为0,方差为1