Module(nn.Module)
- 딥러닝을 구성하는 Layer의 base class
- Input, Output, Forward, Backward 정의
- 학습의 대상이 되는 parameter(tensor)
+super를 통해서 init을 하는이유?
nn.Parameter
- Tensor 객체의 상속 객체이다.
- nn.Module 내에 attribute 가 될 때는 required_grad=True로 지정되어 학습의 대상이 되는 Tensor이다.
- 이 객체를 사용하지 않고 Tensor를 사용하면 자동미분이 되지 않는다!
- 직접 설정하는 일은 잘 없다.(대부분의 층(layer)에는 가중치값들이 지정되어있음)
backward
한마디로 backpropagation을 수행하는 명령어이다.
- Layer에 있는 Parameter들의 미분을 수행
- Forward의 결과값 (model의 output=예측치)과 실제값간의 차이(loss) 에 대해 미분을 수행
- 해당 값으로 Parameter 업데이트
for epoch in range(epochs):
……
optimizer.zero_grad() # 아래 링크 참조
# get output from the model, given the inputs
outputs = model(inputs)
# get loss for the predicted output
loss = criterion(outputs, labels)
print(loss)
# get gradients w.r.t to parameters
loss.backward()
# update parameters
optimizer.step()
………
+Pytorch에서는 왜 항상 optimizer.zero_grad()를 해줄까?