PyTorch 各种创建 Tensor 方式
import from numpy
a = np.array([2, 3.3]) torch.from_numpy(a) #tensor([2.000, 3.300], dtype = torch.float64)
a = np.ones([2, 3]) torch.from_numpy(a) #tensor([[1., 1., 1.], [1., 1., 1.]], dtype = torch.float64)
|
import from list
torch 承载的参数是现成的数据:numpy 或者 list
Torch、FloatTensor 接收 shape 作为参数,生成一个没有初始化的类型.
或使用 list 来接收现有数据(不建议).
torch.tensor([2, 3.2]) #tensor([2.0000, 3.2000])
torch.FloatTensor([2., 3.2]) #tensor([2.0000, 3.2000])
torch.tensor([[2., 3.2],[1., 22.3]])
|
uninitialized
- torch.empty(d1, d2)
- torch.FloatTensor(d1, d2, d3)
- torch.IntTensor(d1, d2, d3)
要把未初始化的数据覆盖掉,如果出现 torch.nan 或者 torch.inf,可能就是使用了未初始化的数据.
set default type
一般使用 Tensor 默认是 FloatTensor
使用 torch.set_default_tensor_type(torch.DoubleTensor)
来改变默认类型
torch.tensor([1.2, 3]).type #'torch.FloatTensor' torch.set_default_tensor_type(torch.DoubleTensor) torch.tensor([1.2, 3]).type #'torch.DoubleTensor'
|
rand/rand_like, randint
rand 随机使用 [0, 1] 均匀分布
torch.rand(3, 3) #按均匀分布生成3*3shape的随机张量
|
rand_like 接受的参数是一个 tensor,生成一个和其 shape 相同的随机张量
> *_like
randint (min, max, [shape]),左闭右开
randn 标准正态分布
torch.randn(3, 3) #按标准正态分布生成3*3shape的随机张量
|
如果想自定义均值和方差,使用 normal 生成一维张量后 reshape
torch.normal(mean = torch.full([10], 0), std = torch.arange(1, 0, -0.1)) #torch.full([10], 0)生成一个10*1的全0张量 #均值为0,方差依次递减[1, 0.9, ...]
|
full
torch.full([2, 3], 7) #tensor([[7., 7., 7.], [7., 7., 7.]) torch.full([], 7) #tensor(7.)
|
arange / range
torch.arange(0, 4) #tensor([0, 1, 2, 3]) torch.arange(0, 4, 2) #ensor([0, 2]) torch.range(0, 4) #tensor([0, 1, 2, 3, 4]) 不建议使用range
|
linspace / logspace
torch.linspace(0, 10, steps = 4) #第三个参数是数量 #tensor([0.0000, 3.3333, 6.6666, 10.0000])
torch.logspace(0, -1, steps = 10) #相当于linspace生成的这些数作为10的幂 #tensor([1.0000, 0.7743, ..., 0.1000])
|
Ones / Zeros / Eye
torch.ones(2, 2) #tensor([[1, 1], [1, 1]) torch.zeros(2, 2) #tensor([[0, 0], [0, 0]) torch.eye(2, 3) #tensor([[1, 0, 0], [0, 1, 0])
|
torch.eye(3) #tensor([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
a = torch.zeros(3, 3) torch.ones_like(a) #tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
|
eye 最多两个参数
randperm
torch.randperm(10) #tensor([1, 5, 4, 2, 0, 6, 3, 9, 7, 8]) 生成随机索引
|
- random.shuffle > 为了保持配对
a = torch.rand(2, 3) b = torch.rand(2, 2) idx = torch.randperm(2) idx #tensor([1, 0])
a[idx] b[idx]
|
Be the first person to leave a comment!