ํด๋น ๊ธ์ FastCampus - '[skill-up] ์ฒ์๋ถํฐ ์์ํ๋ ๋ฅ๋ฌ๋ ์ ์น์ ๊ฐ์๋ฅผ ๋ฃ๊ณ ,
์ถ๊ฐ ํ์ตํ ๋ด์ฉ์ ๋ง๋ถ์ฌ ์์ฑํ์์ต๋๋ค.


z = torch.matmul(x, y)
# x*y๋ elemetalwise ๊ณฑ์
์ด๋ค!




๋ ธ๋ == ํผ์ ํธ๋ก == ๋ด๋ฐ
๊ฐ ์
๋ ฅ ๋
ธ๋๋ค์ weight(๊ฐ์ค์น)๋ฅผ ๊ณฑํ๊ณ ๋ชจ๋ ํฉ์น ๋ค, bias(ํธํฅ)์ ๋ํจ
โ ํ๋ ฌ ๊ณฑ์ผ๋ก ๊ตฌํ ๊ฐ๋ฅ

n์ฐจ์์์ m ์ฐจ์์ผ๋ก์ ์ ํ ๋ณํ ํจ์

x๋ฅผ ๋ฏธ๋๋ฐฐ์น์ ๊ด๊ณ ์์ด ๋จ์ํ ํ๋์ ๋ฒกํฐ๋ก ๋ณผ ๊ฒฝ์ฐ

x๋ฅผ ๋ฏธ๋๋ฐฐ์น(N๊ฐ) ํ
์๋ก ํํํ ๊ฒฝ์ฐ (์ฃผ๋ก ์ฌ์ฉ)
โ ๋ฏธ๋๋ฐฐ์น์ ๋ํ ๋ณ๋ ฌ ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅ
W = torch.FloatTensor([[1, 2],
[3, 4],
[5, 6]])
b = torch.FloatTensor([2, 2])
x = torch.FloatTensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
print(W.size(), b.size(), x.size())
def linear(x, W, b):
y = torch.matmul(x, W) + b
return y
y = linear(x, W, b)
print(y.size())
nn.Module
- PyTorch์์ ๋ชจ๋ธ์ ์ ์ํ๊ธฐ ์ํ base ํด๋์ค (์ถ์ ํด๋์ค๋ผ๊ณ ํ๊ธฐ์ init๊ณผ forward ํจ์๋ฅผ ์ ์ธํ๊ณ ๋ ๊ทธ๋๋ก ์ฌ์ฉ ๊ฐ๋ฅ)
- ํ๋ผ๋ฏธํฐ ๊ด๋ฆฌ, ํ์ดํ๋ผ์ธ ์ฒ๋ฆฌ, ์๋ ๋ฏธ๋ถ, ๋ชจ๋ธ ํ๋ จ ๋ฐ ํ๊ฐ ๊ธฐ๋ฅ์ ์ฝ๊ฒ ์ฒ๋ฆฌํ๊ธฐ ์ํด ์์ ๋ฐ๋ ํด๋์ค
- init๊ณผ forward๋ override ํ์!
forward
- ๋ฅ๋ฌ๋ ๋ชจ๋ธ์ ์์ ํ (forward pass)๋ฅผ ์ ์ํ๋ ๋ฉ์๋
- ์ ๋ ฅ ๋ฐ์ดํฐ๋ฅผ ๋คํธ์ํฌ๋ฅผ ํต๊ณผ์ํค๋ฉฐ ์ถ๋ ฅ ๊ฐ์ ๊ณ์ฐํ๋ ๊ณผ์
backward
- ๋ฅ๋ฌ๋ ๋ชจ๋ธ์ ์ญ์ ํ (backward pass)๋ฅผ ์ ์ํ๋ ๋ฉ์๋
- ์ถ๋ ฅ๊ณผ ์ค์ ๊ฐ์ ์ฐจ์ด๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๊ธฐ์ธ๊ธฐ(gradient)๋ฅผ ๊ณ์ฐํ์ฌ ๊ฐ์ค์น ์ ๋ฐ์ดํธ๋ฅผ ์ํ ์ ๋ณด๋ฅผ ์ ๊ณต
class MyLinear(nn.Module): ## nn.Module: __init__๊ณผ forward override ํ์!
def __init__(self, input_dim=3, output_dim=2):
self.input_dim = input_dim
self.output_dim = output_dim
super().__init__() #๋ถ๋ชจ ํด๋์ค ์ด๊ธฐํ
self.W = nn.Parameter(torch.FloatTensor(input_dim, output_dim)) # nn.Parameter๋ก wrapping ํด์ค์ผ ํ๋ผ๋ฏธํฐ๋ก ๋ฑ๋ก์ด ๋๊ณ ํ์ต์ด ๊ฐ๋ฅํจ
self.b = nn.Parameter(torch.FloatTensor(output_dim))
# You should override 'forward' method to implement detail.
# The input arguments and outputs can be designed as you wish.
def forward(self, x):
# |x| = (batch_size, input_dim) # ์ด dimension ์ฃผ์ ๋ค๋ ์ต๊ด์ด ๋งค์ฐ ์ข๋ค!
y = torch.matmul(x, self.W) + self.b
# |y| = (batch_size, input_dim) * (input_dim, output_dim)
# = (batch_size, output_dim)
return y
linear = MyLinear(3, 2)
y = linear(x)
print(y.size())
for p in linear.parameters():
print(p)
# Parameter containing:
# tensor([[-0.4768, 0.3792, 0.2139],
# [-0.2055, -0.3338, -0.0495]], requires_grad=True)
# Parameter containing:
# tensor([-0.3775, -0.5481], requires_grad=True)
linear = nn.Linear(3, 2)
y = linear(x) # forward๋ ์๋์ผ๋ก ์งํ
#
#
| ํญ๋ชฉ | ์ค๋ช |
|---|---|
| ํ๋ ฌ๊ณฑ | ๋ฅ๋ฌ๋์ ๊ธฐ๋ณธ ์ฐ์ฐ. ์ ๋ ฅ๊ณผ ๊ฐ์ค์น์ ๋ด์ |
| BMM | ์ฌ๋ฌ ํ๋ ฌ ์์ ๋ณ๋ ฌ๋ก ๊ณฑํ๋ ์ฐ์ฐ |
| Linear Layer | ์ ํ๋ณํ์ ์ํํ๋ ์ ๊ฒฝ๋ง์ ๊ธฐ๋ณธ ๊ตฌ์ฑ |
| ์์ | y = xW + b ํํ์ ์ ํํจ์ |
| ํ๋ผ๋ฏธํฐ | W (๊ฐ์ค์น), b (ํธํฅ) |