알고리즘 : X * n
학습 : n을 찾기 → 내 data(input/output)에 맞춘다.
⇒ 최적의 n을 찾는 알고리즘이 필요 → 최적화 → scikit-learn
Feature
- X (여러 개의 값으로 구성하면 보통 대문자)Label
- yClass
Scikit-learn
(딥러닝X)# 사이킷런 설치
conda install -y scikit-learn
pip install scikit-learn
scikit-learn 내장 데이터셋의 구성
target_names
: 예측하려는 값(class)을 가진 문자열 배열target
: Label(출력데이터)data
: Feature(입력변수)feature_names
: 입력변수 각 항목의 이름DESCR
: 데이터셋에 대한 설명dataframe/Series.apply(함수)
lambda idx : iris['target_names'][idx]
→ 함수로 구현하면,
def func(idx):
return iris['target_names'][idx]
결정 트리(Decision Tree) 알고리즘
from sklearn.tree import DecisionTreeClassifier
# XXXXXClassifier : 분류모델
# XXXXXRegressor : 회귀모델
# XXXXX -> 알고리즘 이름
# 모델 객체 생성
clf = DecisionTreeClassifier()
clf.fit(X, y) # fit(Feature, target)
# 1개 꽃을 추론
new_data = np.array([[5, 3.5, 1.4, 0.25]])
# 3개 꽃들을 추론
# new_data = np.array([[5, 3.5, 1.4, 0.25],
# [3, 1.5, 1.4, 0.25],
# [7, 3.5, 5.4, 4.25]])
new_data.shape
# 학습한 모델.predict(추론할 feature) => y값(Label)
pred = clf.predict(new_data)
pred
# 결과 후처리 : class->class name
iris['target_names'][pred]
훈련데이터셋과 평가(테스트)데이터 분할
train_test_split()
: 하나의 데이터셋을 두개의 세트로 분할 하는 함수from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
import numpy as np
iris = load_iris() # 데이터 불러오기
# iris['data']
X, y = iris.data, iris.target # feature, target 조회 => Bunch : .표기법, indexer[]
X.shape, y.shape
X_train, X_test, y_train, y_test = train_test_split(X, # features
y, # target(label)
test_size=0.2, # test set의 비율(default : 0.25)
stratify=y, # 원본의 class별 비율과 동일한 비율로 나눠지도록 한다.
shuffle=True, # 나누기 전에 랜덤하게 섞어줌
random_state=0 # random seed 값 설정
)
X_train.shape, X_test.shape, y_train.shape, y_test.shape
혼동행렬 (Confusion Matrix)
sklearn.metrics
모듈의 confusion_matrix()
함수 이용