[python] 파이썬(sklearn) 사이킷런(sklearn) 기초

사이킷런(sklearn)이란?

사이킷런은 파이썬에서 머신러닝 분석을 할 때 유용하게 사용할 수 있는 라이브러리 입니다. 여러가지 머신러닝 모듈로 구성되어있습니다.

자주 사용되는 모듈을 불러오자

아래 모듈은 자주 사용되는 모듈입니다.

import numpy as np
import pandas as pd
from sklearn import datasets
# 참고: 분류용 가상 데이터 만들기
from sklearn.datasets import make_classification

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn import svm
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier

import matplotlib.pyplot as plt

하나씩 설명을 드리자면

import numpy as np                                       ## 기초 수학 연산 및 행렬계산
import pandas as pd                                      ## 데이터프레임 사용
from sklearn import datasets                             ## iris와 같은 내장 데이터 사용
from sklearn.model_selection import train_test_split     ## train, test 데이터 분할

from sklearn.linear_model import LinearRegression        ## 선형 회귀분석
from sklearn.linear_model import LogisticRegression      ## 로지스틱 회귀분석
from sklearn.naive_bayes import GaussianNB               ## 나이브 베이즈
from sklearn import svm                                  ## 서포트 벡터 머신
from sklearn import tree                                 ## 의사결정나무
from sklearn.ensemble import RandomForestClassifier      ## 랜덤포레스트

import matplotlib.pyplot as plt                          ## plot 그릴때 사용

가상 데이터 랜덤으로 생성하기

sklean에 내장된 데이터를 사용할 수도 있지만, 직접 만들수도 있습니다.

# 분류용 가상 데이터 만들기
from sklearn.datasets import make_classification

바로 위와같이 make_classification을 이용하면 가상데이터를 만들수 있는데요. 사용법은 아래와 같습니다.

X, Y = make_classification(n_samples=1000, n_features=4,
                        n_informative=2, n_redundant=0,
                        random_state=0, suffle=False)

make_classification함수는 다음과 같은 옵션들을 제공합니다.

옵션명 설명
n_sample 표본 수(default=100)
n_features 독립변수 수(default=20)
n_informative 종속변수와 상관관계가 존재하는 독립변수 수(default=2)
n_redundant 독립변수끼리 종속관계에 있는 독립변수 수(default=2)
n_repeated 중복 독립변수 수(default=0)
n_classes 종속변수 클래스(라벨) 수(default=2)
n_clusters_per_class 클래스당 클러스터 수(default=2)
weights 각 클래스에 할당 된 표본 수
random_state 난수 생성 시드(seed) 번호

데이터 불러오기

### 저는 사이킷런에 내장되어있는 유방암 데이터를 사용하기로 하겠습니다.

raw = datasets.load_breast_cancer()         ## sklearn에 내장된 원본 데이터 불러오기
print(raw.feature_names)                    ## 열(column) 이름 확인
['mean radius' 'mean texture' 'mean perimeter' 'mean area'
 'mean smoothness' 'mean compactness' 'mean concavity'
 'mean concave points' 'mean symmetry' 'mean fractal dimension'
 'radius error' 'texture error' 'perimeter error' 'area error'
 'smoothness error' 'compactness error' 'concavity error'
 'concave points error' 'symmetry error' 'fractal dimension error'
 'worst radius' 'worst texture' 'worst perimeter' 'worst area'
 'worst smoothness' 'worst compactness' 'worst concavity'
 'worst concave points' 'worst symmetry' 'worst fractal dimension']

data = pd.DataFrame(raw.data)               ## 독립변수 데이터 모음  
target = pd.DataFrame(raw.target)           ## 종속변수 데이터 모음
rawData = pd.concat([data,target], axis=1)  ## 독립변수 + 종속변수 열 결합

## 열(column)이름 설정
rawData.columns=['mean radius', 'mean texture', 'mean perimeter', 'mean area',
 'mean smoothness', 'mean compactness', 'mean concavity',
 'mean concave points', 'mean symmetry', 'mean fractal dimension',
 'radius error', 'texture error', 'perimeter error', 'area error',
 'smoothness error', 'compactness error', 'concavity error',
 'concave points error', 'symmetry error', 'fractal dimension error',
 'worst radius', 'worst texture', 'worst perimeter', 'worst area',
 'worst smoothness', 'worst compactness', 'worst concavity',
 'worst concave points', 'worst symmetry', 'worst fractal dimension'
 , 'cancer']

rawData.head(10)                                ## 데이터 확인 

독립변수 갯수가 너무 많아서 예시로 들기엔 데이터가 크다는 생각이 들었습니다. 그래서 독립변수는 2개만 사용하도록 하겠습니다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

x = rawData[['mean radius', 'mean texture']]
y = rawData['cancer']

train, test 데이터 분할하기

오버피팅을 막기위해 데이터를 train, test로 분할 합시다.

x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.25, random_state=0)
옵션명 설명
test_size test셋 비율
train_size train셋 비율(default: 테스트셋의 나머지)
random_state 랜덤시드번호
suffle 데이터섞기(default: true)
statify 라벨 비율 유지

사이킷런 제공 api

사이킷런에서는 여러가지 머신러닝 모델을 사용할 수 있는데요.
대부분의 모델에서 공통적으로 제공되는 api가 있습니다.

fit(x_train, y_train)     ## 모수 추정(estimat)
get_params()              ## 추정된 모수 확인
predict(x_test)           ## x_test로부터 라벨 예측
predict_log_proba(x_test) ## 로그 취한 확률 예측
predict_proba(x_test)     ## 각 라벨로 예측될 확률
score(x_test, y_test)     ## 모델 정확도 평가를 위한 mean accuracy

mean accuracy란 무엇인가?

위 api 중 score이라는 함수가 있는데요. 이 함수는 모델의 성능을 평가하기 위해 mean accuracy를 제공합니다. 이 때, mean accuracy란 무엇일까요? mean accuracy는 각 라벨 종류별로 몇개를 맞췄는지를 나타냅니다. 예를들어, 유방암 데이터에서 구분되는 라벨은 2가지 입니다. 병에 걸리지 않았거나(=0), 걸린 경우(=1) 입니다. 따라서 이 경우 mean accuracy는 아래와 같습니다.

mean accuracy=(유방암에 안걸린 사람 맞춘 숫자전체 유방암 안걸린 사람 수+유방암에 걸린 사람 맞춘 숫자전체 유방암 걸린 사람 수)×12

선형회귀분석

clf = LinearRegression()
clf.fit(x_train,y_train)  # 모수 추정
clf.coef_                 # 추정 된 모수 확인(상수항 제외)
clf.intercept_            # 추정 된 상수항 확인
clf.predic(x_test)        # 예측
clf.score(x_test, y_test) # 모형 성능 평가

로지스틱 회귀분석

clf = LogisticRegression(solver='lbfgs').fit(x_train,y_train)
clf.predict(x_test)
clf.predict_proba(x_test)
clf.score(x_test,y_test)

나이브 베이즈

gnb = GaussianNB()
gnb.fit(x_train, y_train)
gnb.predict(x_test)
gnb.score(x_test, y_test)

의사결정 나무

clf = tree.DecisionTreeClassifier()
clf.fit(x_train, y_train)
clf.predict(x_test)
clf.predict_proba(x_test)
clf.score(x_test, y_test)

서포트벡터머신

clf = svm.SVC(kernel='linear')
clf.fit(x_train, y_train)
clf.predict(x_test)
clf.score(x_test, y_test)

랜덤포레스트

clf = RandomForestClassifier(max_depth=2, random_state=0)
clf.fit(x_train, y_train)
clf.feature_importances_
clf.predict(x_test)

 

[출처] https://losskatsu.github.io/machine-learning/sklearn/#%EC%9D%98%EC%82%AC%EA%B2%B0%EC%A0%95-%EB%82%98%EB%AC%B4

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
411 [python, 인터넷] Web Search Engine, 인터넷 검색 엔진 구현 file 졸리운_곰 2023.01.16 4
410 [Amazon S3 clone] minio 설치 및 파이썬 업로드 스크립트 졸리운_곰 2022.12.24 6
409 [Python][flask] Flask 로 Rest API 구현하기 - 개발환경구축 file 졸리운_곰 2022.12.24 4
408 [python][자료구조] Dropbox API 사용하기 (with python) 졸리운_곰 2022.12.03 7
407 [Python][자료구조] SQLAlchemy Tutorial(한글) - 2 졸리운_곰 2022.12.03 4
406 [Python]][자료구조] SQLAlchemy Tutorial(한글) - 1 졸리운_곰 2022.12.03 11
405 [python] [Anaconda]가상환경 설치,삭제 file 졸리운_곰 2022.12.03 7
404 [python][머신러닝] Scikit-learn Tutorial: Machine Learning in Python file 졸리운_곰 2022.11.29 13
403 [python, 그래픽] [파이썬 활용] 마우스 자동화 (pyautogui) file 졸리운_곰 2022.11.26 30
402 [python, 그래픽] 파이썬 자동화 툴 - pyautogui 사용하기 file 졸리운_곰 2022.11.26 6
401 [Python] 파이썬 프로젝트의 구조 file 졸리운_곰 2022.11.18 27
400 [python] [Python] 파이썬 Source의 기본 형태 file 졸리운_곰 2022.11.18 7
399 cython 튜토리얼 Cython 시작하기 졸리운_곰 2022.11.13 8
398 [python] 파이썬 스케줄 수행 - schedule, apscheduler file 졸리운_곰 2022.11.13 20
397 [python 일반] python 난독화 및 실행파일 한 번에 만들기 졸리운_곰 2022.11.06 29
» [python] 파이썬(sklearn) 사이킷런(sklearn) 기초 졸리운_곰 2022.08.20 27
395 [python] scikit-learn이란 file 졸리운_곰 2022.08.20 21
394 [python] Apache Airflow 소개 및 실습하기(기초) file 졸리운_곰 2022.07.25 39
393 [anaconde3][python] Create environment for tensorflow 1.4 in Anaconda 3 졸리운_곰 2022.07.02 34
392 [python 인터넷] Python으로 XML-RPC 서버 구축 file 졸리운_곰 2022.06.28 7
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED