# CPU 모드
import torch
torch.manual_seed(777)
X = torch.FloatTensor([[0,0], [0,1], [1,0],[1,1]])
Y = torch.FloatTensor([[0],[1],[1],[0]])
이진분류문제를 해결하려고 하는 우리# 모델 정의
# Layer 정의
linear = torch.nn.Linear(2,1,bias=True) # Fully Connected Layer
sigmoid = torch.nn.Sigmoid()
model = torch.nn.Sequential(linear,sigmoid)
model

# 모델 학습 환경 설정
# Binary Cross Entropy Loss
loss = torch.nn.BCELoss()
optimizer = torch.optim.SGD(model.parameters(),lr=1)
for stop in range(10000):
# 그래디언트 초기화
optimizer.zero_grad()
# Forward 계산
hypothesis = model(X)
# Error 계산
cost = loss(hypothesis, Y)
# Backward 계산
cost.backward()
# 가중치 갱신
optimizer.step()
if stop % 100 == 0:
print(stop, cost.item())
(생략...)여기서 optimizer.zero_grad()가 어디에 위치하든지 중요하지 않음.
optimizer.zero_grad()
cost.backward()
optimizer.step()
이 순서만 지켜주면 됨!
## w,b 평가
with torch.no_grad(): # 임시로 required_grad = false로 설정하는 것과 같다.
hypothesis = model(X)
predicted = (hypothesis > 0.5).float()
accuracy = (predicted == Y).float().mean()
print('\n Hypothesis: ', hypothesis.numpy(), '\n Correct: ', predicted.numpy(), '\n Accuracy: ', accuracy.item())

굳이 우리가 하지 않고도
.mean()을 하면 되는구나 good idea