(04๊ฐ) AutoGrad & Optimizer
210818
๋
ผ๋ฌธ์ ๊ตฌํํ ๋์๋ ๋ธ๋ฝ ๋๋ ๋ ์ด์ด๋ผ๊ณ ๋ถ๋ฆฌ๋ ํํ๊ฐ ๋ฐ๋ณต๋์ด์๋ ๊ตฌ์กฐ๋ฅผ ๊ตฌํํ๊ฒ ๋๋ค. ์ด ๋๋ torch.nn.Module ๋ฅผ ๊ตฌํํด์ผ ํ๋ค. ์ด๋ ๋ฅ๋ฌ๋์ ๊ตฌ์ฑํ๋ Layer์ ๊ธฐ๋ณธ์ด ๋๋ class ์ด๋ค. ์ฌ๊ธฐ์ Input , Output , Forward ,Backward ๋ฅผ ์ ์ํ๋ค. ๋, ํ์ต์ ๋์์ด ๋๋ parameter ๋ ์ ์ํ๋๋ฐ ์ด๊ฒ์ torch.nn.Parameter ํด๋์ค์์ ์ ์ํ๋ค.
nn.Parameter ๋ Tenser ๊ฐ์ฒด๋ฅผ ์์๋ฐ์ ๊ฐ์ฒด๊ธฐ ๋๋ฌธ์ Tensor์ ๋งค์ฐ ๋น์ทํ๋ฐ ์ฐจ์ด์ ์ nn.Module ๋ด์ attribute๊ฐ ๋ ๋ required_grad = True ๋ก ์ง์ ๋์ด์ ํ์ต์ ๋์์ด ๋๋ค. ๊ทธ๋์ ์ฐ๋ฆฌ๊ฐ ์ด ํ๋ผ๋ฏธํฐ๋ฅผ ์ง์ ์ง์ ํ ์ผ์ด ์๊ฒ๋๋ค.
class MyLinear(nn.Module):
def __init__(self, in_features, out_features, bias=True):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weights = nn.Parameter(
torch.randn(in_features, out_features))
self.bias = nn.Parameter(torch.randn(out_features))
def forward(self, x : Tensor):
return x @ self.weights + self.bias๋ง์ฝ์ nn.Parameter ๋์ nn.Tensor๋ก ์ ์ธํ๋ฉด ๊ฒฐ๊ณผ๋ ๋์ผํ์ง๋ง MyLinear.parameters() ๋ก ํ๋ผ๋ฏธํฐ๋ฅผ ์ถ๋ ฅ์ ํ
์๋ ์ถ๋ ฅ๋์ง ์๋๋ค. ์๋ํ๋ฉด ์ด ๊ฐ๋ค์ ๋ฏธ๋ถ๋ ์ ์๋ ๊ฐ๋ค๋ง ์ถ๋ ฅ๋๊ธฐ ๋๋ฌธ์ด๋ค.
๊ทธ๋์ ํ ์๋ก ์ ์ธํ ์ผ์ ์๋ค.
Last updated
Was this helpful?