11월 둘째 주( 11/06 ~ 11/10 )
학습 회고
torch.Tensor(), torch.tensor()
>텐서를 만드는 함수
torch.add(a,b), torch.mul(a,b), torch.div(a,b), torch.sub(a,b)
>tensor을 기반으로 하는 사칙연산
torch.index_select(A,div,torch.tensor([n]).view(-1)
> tensor A에서 div 차원 기준으로 n번째를 선택후 view, 즉 원하는 차원으로 풀어준다.
torch.gather()
>후에 수정
torch.nn.Linear(a,b)
> a차원을 b차원으로 바꿔주는 함수
torch.nn.Identity(x)
> 자신과 동일한 텐서를 반환하는 함수
nn.Sequential
>
class Add(nn.Module):
def __init__(self, value):
super().__init__()
self.value = value
def forward(self, x):
return x + self.value
# TODO : 위에 모듈(Module)과 nn.Sequential를 이용해서
# 입력값 x가 주어지면 다음의 연산을 처리하는 모델을 만들어보세요!
# y = x + 3 + 2 + 5
calculator = nn.Sequential(Add(3),Add(2),Add(5))
x = torch.tensor([1])
output = calculator(x)
nn.ModuleList
>
class Add(nn.Module):
def __init__(self, value):
super().__init__()
self.value = value
def forward(self, x):
return x + self.value
class Calculator(nn.Module):
def __init__(self):
super().__init__()
self.add_list = nn.ModuleList([Add(2), Add(3), Add(5)])
def forward(self, x):
# y = ((x + 3) + 2) + 5 의 연산을 구현하세요!
for f in self.add_list:
x =f(x)
return x
x = torch.tensor([1])
calculator = Calculator()
output = calculator(x)
torch.nn.ModuleDict()
class Add(nn.Module):
def __init__(self, value):
super().__init__()
self.value = value
def forward(self, x):
return x + self.value
class Calculator(nn.Module):
def __init__(self):
super().__init__()
self.add_dict = nn.ModuleDict({'add2': Add(2),
'add3': Add(3),
'add5': Add(5)})
def forward(self, x):
# y = ((x + 3) + 2) + 5 의 연산을 구현하세요!
for f in ['add2','add3','add5']:
x = self.add_dict[f](x)
return x
# 아래 코드는 수정하실 필요가 없습니다!
x = torch.tensor([1])
calculator = Calculator()
output = calculator(x)
torch.nn.ModuleList()
>
class Add(nn.Module):
def __init__(self, value):
super().__init__()
self.value = value
def forward(self, x):
return x + self.value
class PythonList(nn.Module):
"""Python List"""
def __init__(self):
super().__init__()
# Python List
self.add_list = [Add(2), Add(3), Add(5)]
def forward(self, x):
x = self.add_list[1](x)
x = self.add_list[0](x)
x = self.add_list[2](x)
return x
class PyTorchList(nn.Module):
"""PyTorch List"""
def __init__(self):
super().__init__()
# Pytorch ModuleList
self.add_list = nn.ModuleList([Add(2), Add(3), Add(5)])
def forward(self, x):
x = self.add_list[1](x)
x = self.add_list[0](x)
x = self.add_list[2](x)
return x
Tensor와 Parameter와 다른점?
> 단순 계산으로써의 역할은 동일하게 수행하지만, Tensor에는 gradient계산, 값 업데이트 모델 저장시 값 저장등이 안되기 때때문에, Parameter를 사용해야 합니다.
- "Tensor"
- ❌ gradient 계산
- ❌ 값 업데이트
- ❌ 모델 저장시 값 저장
- "Parameter"
- ✅ gradient 계산
- ✅ 값 업데이트
- ✅ 모델 저장시 값 저장
- "Buffer"
- ❌ gradient 계산
- ❌ 값 업데이트
- ✅ 모델 저장시 값 저장
get_parameter, name_parameters , get_buffer, name_buffers
>
parameter = model.get_parameter('ab,a,w1')
이번주 회고
저번주에 학습하는 일정을 맞춰 보자라고 마음을 먹었는데, 어느날은 늦게 자고 늦게일어나고, 아직 확실하게 일정을 맞추지는 못했다, 이번주말에 다른 바쁜 일들이 마무리 되기 때문에, 조금씩 밀어왔던 일들을 다음주에는 마무리 해야겠다.