강의자료 · 전기공학머신러닝실습

Logistic Regression

학습 목표

확률을 계산하는 모델과 최종 경보를 내리는 기준을 구분해야, 놓침과 오경보의 비용을 조절할 수 있습니다.

Logit·확률

시작 조건

입력은 제공한 12×2 합성 특징이며, 두 특징 합이 1을 넘는 표본이 Class 1입니다.

진행 방법

  1. BCEWithLogitsLoss에 들어가는 값과 Sigmoid를 적용한 값을 구분해 실행하세요.
  2. 각 표본의 두 특징·정답·Logit·확률·.5 판정을 표에 적으세요.
  3. Loss 곡선과 2차원 자료의 Class를 표시하세요.

남길 결과

import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
X=torch.tensor([[-2.,-1.],[-1.,-2.],[-1.,0.],[0.,-1.],[1.,1.],[1.,2.],[2.,1.],[2.,2.],[-2.,1.],[1.,-2.],[0.,2.],[2.,0.]])
y=(X.sum(dim=1)>1).float().reshape(-1,1)
def fit_binary(weights=None):
    torch.manual_seed(7);m=nn.Linear(2,1);opt=torch.optim.SGD(m.parameters(),lr=.1);history=[]
    for _ in range(200):
        losses=nn.functional.binary_cross_entropy_with_logits(m(X),y,reduction='none')
        loss=(losses if weights is None else losses*weights).mean()
        opt.zero_grad();loss.backward();opt.step();history.append(loss.item())
    return m,history
model,history=fit_binary();prob=torch.sigmoid(model(X)).detach().reshape(-1).numpy();truth=y.numpy().reshape(-1).astype(int)
print(prob)

결과 기록·자가 점검

표본:

x1:

x2:

정답:

Logit:

확률:

판정:

확인할 점

Threshold와 오류의 종류

시작 조건

같은 학습 모델의 확률에 Threshold=.35,.5,.65를 적용합니다.

진행 방법

  1. TP·FP·FN·TN을 각각 구하세요.
  2. Accuracy와 Precision·Recall을 계산하고 분모가 0인 경우 표시 규칙을 정하세요.
  3. 센서 경보에서 미탐지를 줄이고 싶은 상황에 어떤 Threshold를 선택할지 근거를 적으세요.

남길 결과

for threshold in [.35,.5,.65]:
    predicted=prob>=threshold
    print(threshold,np.sum((predicted==1)&(truth==1)),np.mean(predicted==truth))
# TODO: 나머지 혼동 행렬과 지표를 구하세요.

결과 기록·자가 점검

Threshold:

TP:

FP:

FN:

TN:

Accuracy:

Precision:

Recall:

확인할 점

오류 비용이 달라진 경우

시작 조건

Class 1 표본의 학습 Loss에 가중치 3을 주고 기준 모델과 비교합니다. 입력·초기 seed·epoch는 같습니다.

진행 방법

  1. weights를 Class 1은 3, Class 0은 1로 정하세요.
  2. 가중 모델의 .5 판정과 기준 모델의 .35 판정을 비교하세요.
  3. 학습 Loss의 가중과 판정 Threshold 변경이 서로 다른 조작임을 설명하세요.

남길 결과

weights=torch.where(y==1,3.,1.)
weighted_model,_=fit_binary(weights)
weighted_prob=torch.sigmoid(weighted_model(X)).detach().numpy().reshape(-1)
# TODO: 두 접근의 오류와 확률을 비교하세요.

결과 기록·자가 점검

방법:

Threshold:

FP:

FN:

Accuracy:

확률 변화 관찰:

확인할 점