[인공지능] 6주차(실습) | 퍼셉트론

dusruddl2·2022년 10월 12일

SJU_인공지능

목록 보기
17/23

✅ 퍼셉트론

  • 은닉 레이어가 1개인 신경망 구조
  • XOR문제를 해결할 수 x

데이터 입출력 정의

# 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]])
  • 이진분류문제를 해결하려고 하는 우리

NN모델 정의

# 모델 정의
# 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())
  • 이중분류 문제이므로 BCELoss 선택
    (생략...)

여기서 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())

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

profile
정리된 글은 https://dusruddl2.tistory.com/로 이동

0개의 댓글