pytorch张量创建、张量复制
首先注意一点:在torch中,可导张量计算出的新张量也是可导的,新张量与原张量具有可导连接,那么原张量就不是叶子张量,新张量成了叶子张量。
创建方式一:torch.tensor()
torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) → Tensor
torch.tensor只能从指定的数据创建,但是可以指定数据属性,是否可微分等属性。pin_memory是将张量放置到锁业内存中,所以这个张量只能被cpu使用。
import torch
a = [1, 2, 3]
b = torch.tensor(a, requires_grad=True, dtype=torch.float64)
创建方式二:torch.Tensor
按照形状创建,如果输入列表,就按照指定数据创建。
整数:torch.ShortTensor 16位,torch.IntTensor 32位,torch.LongTensor 64位
浮点:torch.FloatTensor=torch.Tensor 32位,torch.DoubleTensor 64位
注意:torch.Tensor(int1, int2,int3)会创建[int1, int2,int3]形状的张量,如果传入列表元组等,就会返回该列表元组张量。
import torch
torch.Tensor(3)
'''tensor([-2.6853e+05, 1.9983e-42, 2.3694e-38])'''
torch