📌 Scikit-Learn
- 2007년 구글 썸머 코드에서 처음 구현된, 현재 python으로 구현된 가장 유명한 기계 학습 open source library
- 통일된 interface를 통해 여러 기법 간단하게 적용 가능 -> 쉽고 빠른 최상의 결과 추출 가능
- library 구성 : 지도 학습, 비지도 학습, Model 선택 및 평가, Data 변환
지도 학습 | 벡터 머신, 결정 트리 (Decision Tree) |
비지도 학습 | 군집화 (Clustering), 이상치 검출 모델 |
모델 선택 및 평가 | 교차 검증 (Cross-Validation), 파이프라인 (Pipeline) |
데이터 변환 | 속성 추출 (Feature Extraction), 전처리 (Preprocessing) |
- 정제된 연습용 Data Set 존재
✔️ fit함수 : 훈련 data set에서 모델 생성
✔️ score함수 : 생성된 모델의 성능 확인
✔️predict함수 : test set의 예측값을 생성
👉 가상 데이터 생성
- make_blobs() : 군집을 위한 데이터 생성
- make_moons() : 초승달 모양의 군집 데이터 생성
- make_classification() : 분류를 위한 데이터 생성
- make_regression() : 회귀를 위한 데이터 생성
👉 연습용 데이터 세트 불러오기(소규모)
- load_breast_cancer() : 위스콘신 유방암 데이터, 이진 분류
- load_diabetes() : 당뇨병 환자 데이터, 회귀
- load_digits() : 0~9 손글씨 데이터, 다중 분류
- load_iris() : 붓꽃 품종 데이터, 다중 분류
- load_linnerud() : 피트니스 클럽 데이터, 회귀
❗ Scikit-Learn은 이미 이용 가능한 유용한 데이터셋을 갖고 있어서 load하기 편함 ❗
👉 연습용 데이터 세트 불러오기(중/대규모)
- fetch_midata() : midata.org에 존재하는 데이터 다운로드 가능
- fetch_openml() : openml.org에 존재하는 데이터 다운로드 가능
- fetch_20newsgroups() : 20개의 뉴스 그룹 데이터
- fetch_rcv1() : 로이터 뉴스 말뭉치
✔️scikit-learn의 Datasets에서 특정 함수로 불러온 데이터는 Bunch형태
make로 시작되는 함수는 numpy ndarray타임의 x와 y를 반환
✔️ Key-Value 쌍으로 python Dictionary와 유사함
keys()를 통해 key 목록 조회 가능
✔️ 공통적으로 사용되는 key
- data : X data (2차원 Numpy ndarray)
- target : Y data (1차원 Numpy ndarray)
- feature_names : X data에 대한 정보 (column name)
- target_names : Y data에 대한 정보 (분류 data에만 존재)
- DESCR : 데이터 설명문 (문자열)
👉 예시 코드를 통해 scikit-learn 익혀보기
#데이터세트 불러오기
from sklearn.datasets import load_iris
iris_bunch = load_iris()
type(iris_bunch), iris_bunch.keys()
#output)
#(sklearn.utils.Bunch,
# dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename']))
#데이터세트 설명문 조회
print(iris_bunch.DESCR)
#output)
.. _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
#데이터 컬럼 명 조회
iris_bunch.feature_names
#output)
['sepal length (cm)',
'sepal width (cm)',
'petal length (cm)',
'petal width (cm)']
#레이블 추출
iris_bunch.target_names
#output)
array(['setosa', 'versicolor', 'virginica'], dtype='<U10')
📌 scikit-learn data split (데이터 분할)
과대적합 방지 위해 전체 데이터를 학습 데이터와 평가 데이터로 분할
- 학습 데이터 : 모델 학습 시키기 위한 데이터 세트
- 평가 데이터 : 학습된 모델을 평가하기 위한 데이터 세트
👉 일반적으로 학습데이터:평가데이터 = 7:3의 비율을 많이 이용
import numpy as np
from sklearn.model_selection import train_test_split #test_split을 import
x = np.arange(10) #0부터 9까지
x_train, x_test = train_test_split(x)
#random하게 섞고 나서 7:3으로 나뉨
print(x_train) #학습 데이터
print(x_test) #평가 데이터
#output)
[1 6 2 8 4 5 0]
[9 7 3]
...코드를 돌려보면 output에 0-9까지의 숫자를 랜덤하게 섞고 난 뒤 학습 데이터(train) 70% / 평가 데이터(test) 30%로
✔️ train_test_split(x, test_size)
test_size parameter에 숫자를 넣어주면 일반적인 비율 7:3 이외 다른 비율로 가능
ex. x_train, x_test, y_train, y_test = train_test_split(iris_bunch.data, iris_bunch.target, test_size=0.3)
📌 특성과 레이블
✔️ 특성(Feature)
- 통계에서 독립 변수로 많이 사용되며 ML영역에선 특성(Feature)로 많이 사용
- 이외 설명 변수, 위험 인자라고도 함
✔️ 레이블(Label)
- 통계에서 종속 변수로 많이 사용되며 ML영역에선 레이블(Label), 클래스(Class)로 많이 사용
- 응답 변수, 표적 변수, 결과 변수라고도 함
👉 데이터 프레임의 한 column이 특성 또는 레이블이 됨
'CDS' 카테고리의 다른 글
Machine Learning [Scaling] (0) | 2021.11.15 |
---|---|
Machine Learning [K-NN] (0) | 2021.11.15 |
Machine Learning Overview (0) | 2021.11.15 |
Data Visulization : Seaborn(데이터 시각화) (0) | 2021.11.12 |
Data Visulization : Matplotlib(데이터 시각화) (0) | 2021.11.12 |