1. 程式人生 > >pytroch 函式學習

pytroch 函式學習

1.  tensor=torch.from_numpy(ndarray).

ndarray轉化為tensor

2 .     ndarray =tensor.numpy()

將tensor轉化為ndarray

3.    x = torch.zeros(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

>>> torch.zeros(2, 3)
tensor([[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]])

>>> torch.zeros(5)
tensor([ 0.,  0.,  0.,  0.,  0.]

初始化一個全零陣列。

4.  y=torch.zeros_like(x)

構造一個形狀和型別和x一致的全零陣列

5. torch.ones(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

 torch.ones_like(input, dtype=None, layout=None, device=None, requires_grad=False) → Tensor

和上面的例子一樣,只是這次構造的是全一陣列

6. torch.arange

(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

torch.range(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor

構造一個順序陣列

>>> torch.arange(5)
tensor([ 0,  1,  2,  3,  4])
>>> torch.arange(1, 4)
tensor([ 1,  2,  3])
>>> torch.arange(1, 2.5, 0.5)
tensor([ 1.0000,  1.5000,  2.0000])

arange()和range()的區別是range()結果多了一位,並且range()需要起始點。

>>>a=torch.range(0,5)
>>>print a
tensor([ 0.,  1.,  2.,  3.,  4.,  5.])

7. torch.masked_select(input, mask, out=None) → Tensor

可以根據掩模選擇為一的數值重新組成一個數組

>>> x = torch.randn(3, 4)
>>> x
tensor([[ 0.3552, -2.3825, -0.8297,  0.3477],
        [-1.2035,  1.2252,  0.5002,  0.6248],
        [ 0.1307, -2.0608,  0.1244,  2.0139]])
>>> mask = x.ge(0.5)
>>> mask
tensor([[ 0,  0,  0,  0],
        [ 0,  1,  1,  1],
        [ 0,  0,  0,  1]], dtype=torch.uint8)
>>> torch.masked_select(x, mask)
tensor([ 1.2252,  0.5002,  0.6248,  2.0139])

8. torch.reshpe(input,shape)

改變陣列形狀,但總體大小必須一致,不然會報錯

>>> a = torch.arange(4.)
>>> torch.reshape(a, (2, 2))
tensor([[ 0.,  1.],
        [ 2.,  3.]])
>>> b = torch.tensor([[0, 1], [2, 3]])
>>> torch.reshape(b, (-1,))
tensor([ 0,  1,  2,  3])

9. torch.squeeze(input, dim=None, out=None) → Tensor

將多餘的一維去除

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)
>>> y.size()
torch.Size([2, 2, 1, 2])

10. torch.stack(seq, dim=0, out=None) → Tensor

Concatenates sequence of tensors along a new dimension.

All tensors need to be of the same size.

Parameters:
  • seq (sequence of Tensors) – sequence of tensors to concatenate
  • dim (int) – dimension to insert. Has to be between 0 and the number of dimensions of concatenated tensors (inclusive)
  • out (Tensor, optional) – the output tensor

按維度拼接陣列