Skip to main content

로지스틱 회귀

준비

  • 데이터 불러오기
cc = pd.read_excel('cancer.xlsx')
cc.head()
  • 준비
X = cc.drop(columns=['diagnosis'])
y = cc['diagnosis'].map({'M':1, 'B':0})
  • 분할
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size = 0.2, random_state = 42)

로지스틱 회귀분석 logistic regression

  • 0~1 사이의 출력
    • z=wx+bz=wx+b
    • σ(z)=11+exp(z)\sigma(z)=\frac{1}{1+exp(-z)}
  • 출력은 확률로 해석 (예: 0.8→1일 확률이 80%)

로지스틱 회귀분석 실습

  • 훈련
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(max_iter = 1000)
model.fit(X_train, y_train)
model.score(X_test, y_test)
  • 예측
from sklearn.metrics import accuracy_score
y_pred = model.predict(X_test)
accuracy_score(y_test, y_pred)

확률로 예측

  • 확률 예측
y_prob = model.predict_proba(X_test)[:, 1]
  • 정확도
import numpy as np
threshold = 0.5
y_pred_threshold = np.where(y_prob >= threshold, 1, 0)
accuracy_score(y_test, y_pred_threshold)

정칙화

  • penalty에는 라쏘(lasso), 릿지(ridge), 엘라스틱넷(elasticnet)이 가능
  • C는 작을 수록, 강한 정칙화
model = LogisticRegression(penalty='elasticnet', l1_ratio=0.5, C=0.1,
solver='saga', max_iter = 10000)
model.fit(X_train, y_train)
model.score(X_test, y_test)

Support Vector Machine

  • 분류의 경우 두 집단 간의 최대 마진을 찾는 초평면을 학습하여 데이터를 분류
from sklearn.svm import SVC
model = SVC(kernel='linear', C=1.0, probability=True, random_state = 42)
model.fit(X_train, y_train)
model.score(X_test, y_test)

커널 트릭 kernel trick

  • 저차원 공간에서 분류가 어려운 문제도 고차원 공간에서는 분류가 쉬움
  • 실제 데이터를 고차원 공간으로 매핑하는 것은 계산이 많음
  • 커널(쉽게 말하면 두 점의 거리를 측정하는 방식)만을 변경하여 마치 데이터가 고차원 공간에 매핑된 것처럼 계산하는 트릭을 사용할 수 있음
  • SVM은 커널 트릭을 사용할 수 있는 모형

Support Vector Machine

  • RBF 커널
model = SVC(kernel='rbf', gamma='scale', C=1.0, probability=True, random_state = 42)
model.fit(X_train, y_train)
model.score(X_test, y_test)

퀴즈

사용자 정보 입력
퀴즈를 시작하기 전에 이름과 소속을 입력해주세요.

Q&A