⊢MachineLearning

지도학습 : 분류모델 - SVM

최 수빈 2025. 3. 13. 17:48

 

SVM(Support Vertor Machine)

 

분류(classification)  회귀(regression)분석에 사용되는 지도학습(Supervised Learning) 모델

 

 

데이터를 분류하기 위해 결정 경계(Decision Boundary) 를 찾음 →  결정 초평면(Hyperplane)

결정 초평면은 두 클래스 사이의 최대 마진(Maximum Margin) 을 보장하는 방식으로 선택됨

 

  • 마진(Margin) : 두 클래스 간의 가장 가까운 데이터 포인트 사이의 거리
  • 서포트 벡터(Support Vector) : 결정 초평면에 가장 가까이 위치한 데이터 포인트 → 결정 초평면을 정의하는 역할
  • 커널 함수(Kernel Function) : 선형적으로 분리되지 않는 데이터를 더 높은 차원으로 매핑하여 분리 가능하게 함

 

SVM의 목적

마진을 최대화하면서 결정 초평면을 찾아 일반화 성능(Generalization Performance)을 높이고 데이터 포인트를 정확하게 분류하는 것

 

 

SVM에서 결정 초평면

 

w  x + b = 0

  • w : 가중치 벡터 (Weight Vector)
  • x : 입력 벡터 (Input Vector)
  • b : 절편 (Bias)

 

 

SVM 실습

 

Scikit-learn의 유방암 데이터와 Seaborn의 타이타닉 데이터를 이용하여 SVM을 학습하고 평가

 

 

유방암 데이터셋

 

데이터 로드 및 전처리

import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 유방암 데이터 로드
data = load_breast_cancer()
X = data.data
y = data.target

# 데이터 분할 (80% 훈련, 20% 테스트)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 데이터 스케일링 (평균 0, 분산 1로 조정)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

 

모델 학습

from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# SVM 모델 생성 및 학습 (선형 커널 사용)
model = SVC(kernel='linear')
model.fit(X_train, y_train)

# 테스트 데이터 예측
y_pred = model.predict(X_test)

# 성능 평가
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
print(f"Classification Report:\n{classification_report(y_test, y_pred)}")
print(f"Confusion Matrix:\n{confusion_matrix(y_test, y_pred)}")

"""
Accuracy: 0.956140350877193
Classification Report:
              precision    recall  f1-score   support

           0       0.93      0.95      0.94        43
           1       0.97      0.96      0.96        71

    accuracy                           0.96       114
   macro avg       0.95      0.96      0.95       114
weighted avg       0.96      0.96      0.96       114

Confusion Matrix:
[[41  2]
 [ 3 68]]
"""
  • SVC(kernel='linear') : 선형 커널을 사용하는 SVM 모델 생성
  • fit(X_train, y_train) : 모델 훈련
  • predict(X_test) : 테스트 데이터 예측
  • accuracy_score() : 모델 정확도 계산
  • classification_report() : 분류 성능 지표(정밀도, 재현율 등) 출력
  • confusion_matrix() : 실제값과 예측값의 혼동 행렬 출력

 

타이타닉 데이터셋

 

데이터 로드 및 전처리

import seaborn as sns

# 타이타닉 데이터 로드
titanic = sns.load_dataset('titanic')

# 필요한 열 선택 및 결측값 제거
titanic = titanic[['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked']].dropna()

# 성별과 탑승한 곳을 숫자로 변환
titanic['sex'] = titanic['sex'].map({'male': 0, 'female': 1})
titanic['embarked'] = titanic['embarked'].map({'C': 0, 'Q': 1, 'S': 2})

# 특성과 타겟 분리
X = titanic.drop('survived', axis=1)
y = titanic['survived']

# 데이터 분할 (80% 훈련, 20% 테스트)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 데이터 스케일링
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

 

모델 학습

# SVM 모델 생성 및 학습 (선형 커널 사용)
model = SVC(kernel='linear')
model.fit(X_train, y_train)

# 테스트 데이터 예측
y_pred = model.predict(X_test)

# 성능 평가
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
print(f"Classification Report:\n{classification_report(y_test, y_pred)}")
print(f"Confusion Matrix:\n{confusion_matrix(y_test, y_pred)}")

"""
Accuracy: 0.7482517482517482
Classification Report:
              precision    recall  f1-score   support

           0       0.74      0.85      0.79        80
           1       0.76      0.62      0.68        63

    accuracy                           0.75       143
   macro avg       0.75      0.73      0.74       143
weighted avg       0.75      0.75      0.74       143

Confusion Matrix:
[[68 12]
 [24 39]]
 """

 

 


  • SVM은 분류와 회귀에 사용되는 강력한 지도학습 알고리즘
  • 결정 초평면(Hyperplane)을 찾아 마진을 최대화하는 방식으로 분류 수행
  • 선형적으로 분리되지 않는 데이터는 커널 트릭(Kernel Trick)을 이용해 높은 차원에서 분리 가능
  • 정확도(Accuracy), 분류 보고서(Classification Report), 혼동 행렬(Confusion Matrix) 등을 활용해 모델 평가