先來試試建立簡單的tensor
import torch
torch.tensor(1,2,3)
---------------------------------------------------------------------------TypeError Traceback (most recent call last)
<ipython-input-7-40857d3d51eb> in <module>
----> 1 torch.tensor(1,2,3)
TypeError: tensor() takes 1 positional argument but 3 were given
若要創建tensor 一定要在誇號內加入中誇號[] ,如下:
torch.tensor([1,2,3])
>>>tensor([1, 2, 3])可見其操作如Numpy一樣簡單
torch.arange(5)
>>>tensor([0, 1, 2, 3, 4])torch.arange(5).dtype
>>>torch.int64torch.arange(5.0).dtype
>>>torch.float32torch.arange(6.0).reshape(2,3)
>>>tensor([[0., 1., 2.],[3., 4., 5.]])
也可以將其轉成numpy的形式:
import numpy as np
a = np.array([1, 2, 3])
t = torch.from_numpy(a)
>>>a
out : array([1, 2, 3])
>>>t
out : tensor([1, 2, 3], dtype=torch.int32)
更多Torch 用法,見官網Doc
來試試處理資料normalization
a = torch.arange(1., 6.)
a_nor = a/torch.mean(a)
a_nor = a/torch.std(a)
a_nor
out : tensor([0.6325, 1.2649, 1.8974, 2.5298, 3.1623])最後來練習Torch 的梯度
AUTOGRAD: AUTOMATIC DIFFERENTIATION
創建一個 2*2 的矩陣,每個 tensor 值都是1。
x = torch.ones(2, 2, requires_grad=True)
print(x)
out : tensor([[1., 1.],
[1., 1.]], requires_grad=True)
y = x + 2z = y * y * 3out = z.mean()
print(z, out)
out : tensor([[27., 27.],
[27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward1>)
out.backward()
print(x.grad)
out : tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])
不難算出每個tensor 的 梯度值 d(out)/dx 就是 4.5
沒有留言:
張貼留言