본문 바로가기
Machine Learning/Model

2. Logistic Regression

by 베짱이28호 2023. 12. 25.

2. Logistic Regression


1. 로지스틱 회귀(Logistic Regression) 알고리즘

로지스틱 회귀는 분류 문제를 해결하는 지도 학습 알고리즘.
이진 분류(Binary Classification)와 다중 클래스 분류(Multiclass Classification)에서 모두 사용되며

로지스틱 회귀는 회귀라는 이름이 붙었지만, 입력값에 대해 시그모이드 함수를 적용하여 결과값을 0과 1 사이의 확률 값으로 반환한다.


2. 로지스틱 회귀의 작동 원리

  1. 선형 회귀 모델을 사용하여 입력 데이터와 가중치의 선형 결합 계산
    $$
    z = w_1x_1 + w_2x_2 + \dots + w_nx_n + b
    $$
  2. 시그모이드를 통해 확률로 변환
    $$
    \sigma(z) = \frac{1}{1 + e^{-z}}
    $$
  3. 시그모이드 함수는 결과를 0과 1 사이의 확률값으로 반환한다.
  4. 임계값(Threshold) 설정:
    • 일반적으로 0.5를 기준으로 클래스 분류 (임계값 조정 가능).
    • 다중 분류의 경우, 소프트맥스(Softmax)를 적용하여 각 클래스에 속할 확률을 계산.

장점

  • 이진 분류 문제에서 효과적.
  • 확률 기반의 예측을 제공하므로, 모델이 예측한 값의 불확실성 파악 가능.
  • 과적합 방지를 위한 L1, L2 규제(Regularization)를 통해 일반화 성능 향상.

단점

  • 선형적 분류 경계를 가정하여 비선형 데이터에서 성능 저하.
  • 고차원 데이터에서 SVM이나 랜덤 포레스트 같은 비선형 모델보다 성능 떨어짐.

3. 실습 코드

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target

X_columns = ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
X = df[X_columns]
y = df['species']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)


log_reg = LogisticRegression(max_iter=200)
log_reg.fit(X_train, y_train)


y_pred = log_reg.predict(X_test)
accuracy = np.mean(y_pred == y_test)
print(f'Accuracy: {accuracy:.2f}')


X_test = X_test.copy()
X_test['predicted_species'] = y_pred

sns.pairplot(data=X_test, hue='predicted_species', palette="Set2", kind="scatter")
plt.show()

'Machine Learning > Model' 카테고리의 다른 글

7. CatBoost  (0) 2024.10.02
6. LightGBM  (0) 2024.04.16
5. XGBoost  (0) 2024.02.07
4. Random Forest  (0) 2024.01.29
3. SVM  (0) 2024.01.09
1. K-NN (K-Nearest Neighbor) 알고리즘  (0) 2023.12.18

댓글