- scikit-learn을 활용해보기
- 붓꽃 데이터를 사용
scikit-learn
- 머신러닝의 다양한 알고리즘과 편리한 프레임 워크를 제공하기 때문에 많이들 사용함.
- scikit-learn의 데이터셋
데이터 살펴보기
- 전체 데이터 150개
- 각 데이터는 sepal, petal 각각의 길이와 폭의 정보를 담고 있음
scikit-learn의 모듈 함수
모듈 import, 데이터 불러오기
from sklearn.datasets import load_iris
iris = load_iris()
pritn(iris)
# 출력
['DESCR', 'data', 'data_module', 'feature_names', 'filename', 'frame', ....]
데이터 정보 확인
# iris 데이터셋에 담긴 정보 종류 확인
iris.keys()
# 출력
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR',
# 위에서 확인한 정보중 data만 다로 저장
iris_data = iris.data
print(iris_data.shape)
# 출력
(150, 4)
# 150개의 데이터가 4개의 정보를 담고 있음.
# sepal_length, sepal_width, petal_length, petal_width
# tartget 데이터 저장
iris_target = iris.target
print(iris_target.shape)
# 출력
(150,) # iris의 라벨값
# 데이터셋의 설명서 출려
print(iris.DESCR)
# 출력
.. _iris_dataset:
Iris plants dataset
--------------------
**Data Set Characteristics:**
:Number of Instances: 150 (50 in each of three classes)
:Number of Attributes: 4 numeric, predictive attributes and the class
:Attribute Information:
- sepal length in cm
- sepal width in cm
- petal length in cm
- petal width in cm
- class:
- Iris-Setosa
- Iris-Versicolour
- Iris-Virginica
.
.
.
# 각 데이터의 정보 4개의 변수명 확인
iris.feature_names
# 출력
['sepal length (cm)',
'sepal width (cm)',
'petal length (cm)',
'petal width (cm)']
분류모델 학습시키기
# pandas import
import pandas as pd
# numpy.ndarry를 dataFrame으로 변격해주기
iris_df = pd.DataFrame(data = iris_data, columns = iris.feature_numes)
출력
# label 컬럼 추가해주기
iris_data['label'] = iris.target
# test, train dataset나누기
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris_data, iris_label, test_size = 0.2, random_state = 7)
# 나눠야할 데이터
# 데이터 라벨
# test_size : train test를 8대 2로 나눔
# random_state : 랜덤값을 고정
Decision Tree를 이용한 분류 지도학습
- 의사결정 나무란?
- 요약 *
- 의사결정나무는 범주나 연속형 수치 모두 예측할 수 있음.
- 예측값의 종류는 terminal노드의 갯수와 동일.
- 불순도를 측정하는 방법
- 엔트로피 : 0에 가까울수록 순도 최대, 1에 가까울수록 순도 최소
- 지니계수
- 오분류 오차 : 미분 불가능으로 자주 사용하지 않음
-
- 의사결정나무는 계산복잡성 대비 높은 예측 성능을 냄
- 변수 단위로 설명력을 가짐
- 결정경계(decision boundary)가 데이터 축에 수직이어서 특정 데이터에만 잘 작동할 가능성이 높음
Decision Tree모델 학습시키기
from sklearn.tree import DecisionTreeClassifier
decision_tree = DecisionTreeClassifier(random_state = 32)
# 재현가능하도록 random값을 고정
print(decision_tree._estimator_type
# 출력
classifier
# 학습 데이터로 모델학습 시키기
decision_tree.fit(X_train, y_train)
#출력
DecisionTreeClassifier(random_state=32)
- training dataset으로 모델을 fitting.
- training dataset에 있는 데이터를 통해 모델이 패턴을 파악하고 예측할 수 있다.
- 만약, training dataset에 없는 데이터가 들어오면 예측 잘 못함
학습시킨 Decision Tree모델 사용하기
# test dataset으로 예측값 확인
y_pred = decision_tree.predict(X_test)
y_pred
# 출력
array([2, 1, 0, 1, 2, 0, 1, 1, 0, 1, 2, 1, 0, 2, 0, 2, 2, 2, 0, 0, 1, 2,
1, 1, 2, 2, 1, 1, 2, 2])
# 진짜 label
y_test
# 출력
array([2, 1, 0, 1, 2, 0, 1, 1, 0, 1, 1, 1, 0, 2, 0, 1, 2, 2, 0, 0, 1, 2,
1, 2, 2, 2, 1, 1, 2, 2])
눈으로 대충 비교해 보면 어느정도 잘 맞는것 같네요 ㅎㅎ
예측한 값과 실제값을 비교하여 성능을 예측 할 수 있는 패캐지를 사용해 보겠습니다.
skleanr.metrics를 사용해 성능평가
- Accuracy를 확인
- Accuracy (정확도)
: 전체 개수중 맞은 것의 개수의 수치 - 실제값과 예측값을 비교하여 정확도 측정 from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
accuracy
# 출력
0.9
90% 정도의 정확도를 보이는 것을 확인할 수 있습니다.
30개의 test데이터로 예측했으니 30*0.9 총 30개중 27개는 옳게 예측했다는 것을 알 수 있습니다.
다른 모델로 학습하고 예측하기
- scikit-learn에서 다른 모델을 사용하여 붓꽃데이터를 예측해보겠습니다.
- 모델학습 과정
- 필요한 모듈 import
- 데이터 준비
- train, test 데이터 분리
- 모델 학습 및 예측
- Random Forest
: Decision Tree를 여러개 모아 놓은것.
Random Forest는 큰 Decision Tree를 사용하는 것이 아니라 여러개의 Decision Tree를 만들어 각 트리의 예측값을 종합하여 최종 예측값을 도출합니다.
위와 같은 메커니즘으로 작용하는 모델입니다.
Decision Tree만을 사용했을 때 부족한 점을 여러개를 사용해서 보충하는 방법이죠. 이렇게 여러 결과를 합치는 방식을 앙상블기법이라고 합니다. 위와 동일한 데이터로 Random Forest모델을 적용해 보겠습니다.
from sklearn.ensemble import RandomForestClassifier
random_forest = RandomForestClassifier(random_state =32)
random_forest.fit(X_train, y_train)
y_pred = random_forest.predict(X_test)
# 결과지표 확인
print(classification_report(y_test, y_pred))
# 출력
precision recall f1-score support
0 1.00 1.00 1.00 11
1 1.00 0.83 0.91 12
2 0.78 1.00 0.88 7
accuracy 0.93 30
macro avg 0.93 0.94 0.93 30
weighted avg 0.95 0.93 0.93 30
sckit-learn에서 제공하는 다양한 분류 모델들
- Support Vector Machine (SVM)
: Support Vector와 Hyperplane(초평면)을 이용해서 분류를 수행하게 되는 대표적인 선형 분류 알고리즘.
from sklearn import svm
svm_model = svm.SVC()
svm_model.fit(X_train, y_train)
y_pred = svm_model.predict(X_test)
- SGD(Stochastic Gradient Descent) Classifier
: 데이터 세트에서 random하게 선택한 하나의 데이터 포인드를 이요하여 각 단계의 예측 경사를 계산.
from sklear.liner_model import SGDClassifier
sgd_model = SGDClassifier()
sgd_model.fit(X_train, y_train)
y_pred = sgd_model.predict(X_test)
- Logistic Regression
: softmax함수를 사용한 다중 클래스 분류 알고리즘, 가장 널리 알려진 선형 분류 알고리즘
from sklearn.linear_model import :ogisticRegression
logistic_model = LogisticRegression()
sgd_model.fit(X_train, y_train)
y_pred = sgd_model.predict(X_test)
'TIL(Today I Learned)' 카테고리의 다른 글
MLE / MAP (0) | 2023.09.13 |
---|---|
likelihood와 머신러닝 (0) | 2023.09.12 |
시계열 데이터 분석, 예측하기 (1) | 2023.08.31 |
데이터 분석 (0) | 2023.08.30 |
머신러닝 모델설계하기 기초 | 내가 받을 팁 예측하기 (2) (0) | 2023.08.28 |