교육3주차(1)

Taixi·2024년 9월 1일

생성형 AI 교육

목록 보기
7/35
post-thumbnail

결정 트리 알고리즘과 K -NN 알고리즘

결정 트리 알고리즘 학습하기


  • 분류와 회귀(예측을 수행)가 모두 가능한 머신러닝 알고리즘
  • 분석과정이 직관적이고 이해하기 쉬움
  • RandomForest의 구성요소
  • 종류

    • 분류나무: 목표변수가 이산형인 의사결정나무
    • 회귀나무: 목표변수가 연속적인 의사결정나무
  • 특징

    • 새로운 데이터를 분류하거나 값을 예측
    • 순수도가 증가하도록 분류나무를 형성
  • 장점 및 단점

    • 비모수적 모형
    • 종속변수로 범주형과 수치형 변수를 모두사용
    • 의사결정나무의 과적합 경향

의사경정마무의 결정 규칙

  • 분할 규칙을 사용하여 데이터를 나누고 정지규칙을 사용하여 트리생성을 중지하고, 가지치기 규칙을 사용하여 트리를 단순화
  1. 정지규칙
  • 더 이상 분리가 일어나지 않고 현재마디가 최종마디가 되도록함
  • 트리가 지나치게 깊어지거나 과대적합 방지
  1. 가지치기 규칙
  • 의사결정나무를 단순화하는 프로세스로 모델의 일반화능력을 향상
  • 최종 노드가 너무많으면 과대적합 가능성이 커지는걸 해결함

분류용 불순도 측정 지표

  1. 지니지수
  • 불순도 측정 지표, 값이 작을수록 순수도가 높음
  1. 엔트로피 지수
  • 불순도 측정지표, 가장 작은 값을 갖는 방법 선택
  • 확률이 0,5인경우 불순도가 가장 높은 상태이며, 이때 Entropy=1 임

모형

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, stratify=cancer.target, random_state=42)
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_train, y_train)
print("훈련 세트 정확도: {:.3f}".format(tree.score(X_train, y_train)))
print("테스트 세트 정확도: {:.3f}".format(tree.score(X_test, y_test)))

K - 최근접 이웃(k - NN)알고리즘 이해하기


  • 새로운 데이터에 대해 주어진 이웃의 개수만큼 가까운 멤버들과 비교하여 결과를 판단
  • 이웃의 개수에 따라 소속되는 그룹이 달라질 수 있음
  • 거리를 축적해 이웃들을 뽑기 때문에 스케일링이 중요함

거리계산

  1. 유클리드 거리 (Euclidean Distance)
  • 일반적으로 점과 점 사이의 거리를 구하는 방법
  1. 맨해튼 거리 (Manhattan Distance)
  • X축, Y축을 따라 간 거리
  1. 마할노비스거리 척도
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

# Assign colum names to the dataset
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']

# Read dataset to pandas dataframe
dataset = pd.read_csv(url, names=names)

print(dataset.head())

# Preprocessing
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)

#Feature Scaling
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)

X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

# Training and Predictions
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

# Evaluating the Algorithm
from sklearn.metrics import classification_report, confusion_matrix
print(classification_report(y_test, y_pred))

참고자료

https://foss4g.tistory.com/1312

https://lcyking.tistory.com/entry/머신러닝-의사결정트리Decision-Tree-알고리즘

https://bkshin.tistory.com/entry/머신러닝-4-결정-트리Decision-Tree

https://heeya-stupidbutstudying.tistory.com/entry/ML-결정트리Decision-Tree-파헤치기

https://m.blog.naver.com/bestinall/221760380344

https://d-craftshop.tistory.com/8

profile
개발자를 위한 첫시작

0개의 댓글