(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?