머신러닝(2)
머신러닝 과정을 이해해보기
머신러닝의 기초단계
데이터 로드
xfrom sklearn.datasets import load_breast_cancer
import pandas as pd
import numpy as np
data_cancer = load_breast_cancer()
print(dir(data_cancer))
print(data_cancer.DESCR)
사이킷런 유방암 데이터셋 불러오기
데이터 탐색
1. 데이터 프레임 만들기
xxxxxxxxxx
#훈련데이터로 데이터 프레임 만들기
data_pd = pd.DataFrame(data = data_cancer.data, columns = data_cancer.feature_names)
data_pd.head()
#타겟데이터를 꺼내고 concat 으로 타겟 시리즈를 데이터 프레임에 합치기
data_target = pd.DataFrame(data = data_cancer.target, columns = ['target'])
breast_cancer = pd.concat([data_pd,data_target], axis = 1)
breast_cancer.head()
2. Tidy data 확인
xxxxxxxxxx
#데이터 프레임 구조 확인
breast_cancer.info()
구조부터 확인하기
xxxxxxxxxx
#기술통계보기 中 통계수치 확인
breast_cancer.describe().T #칼럼이 많을 경우에는 전치를 시켜주면 보기 편함
데이터의 기술통계 확인
기술통계 중에 통계 수치 확인하기
xxxxxxxxxx
breast_cancer.boxplot(figsize = (10,5))
boxplot 그려서 각 데이터의 분포를 확인하기 (이상치도 확인)
xxxxxxxxxx
import seaborn as sns
sns.pairplot(breast_cancer, hue = 'target')
plt.savefig('머신러닝3')
각 변수의 상관관계 정도를 시각화하여 확인하기.
걸리는 시간이 오래 걸리니 주의!
데이터전처리
3. 데이터 분리하기
본 데이터 셋을 훈련 데이터와 테스트 데이터로 나눈다.
훈련 데이터를 통해서 모델을 학습시키고, 학습된 모델을 테스트 데이터를 통해서 평가한다.
이때 훈련데이터에 들어있는 data와 target 비율은 테스트 데이터의 data와 target 비율과 동일해야만 한다.
또한 훈련데이터와 타겟 데이터는 중복된 데이터가 있으면 안된다.
xxxxxxxxxx
#train_test_split으로 데이터를 분리하기 (과적합 방지)
from sklearn.model_selection import train_test_split
train_test_split(breast_cancer, test_size = 0.3, random_state = 0)
len(train_test_split(breast_cancer))
데이터 프레임을 넣어서 데이터를 분리한다.
분리된 데이터의 길이를 살펴보면 두 개로 분리가 되어있다.
3.1 test_size
test_size = 0.25 로 디폴트값
xxxxxxxxxx
X,y = train_test_split(breast_cancer)
print(len(X))
print(len(y))
test_size = 0.25 가 기본으로 설정되어 있음.
이 말은 만일 record 가 100개인 데이터셋이 있을 때, record를 train 으로 75개, test로 25 개를 배정하라는 뜻.
데이터셋 행 배정
X, train data -> 75%
y, test data -> 25 %
3.2 shuffle = True
또한
shuffle = True 가 default 따라서 순서가 제멋대로이다.
따라서 holdout 할 때 마다, 행의 순서는 달라져서 도출된다. (분리된 데이터 셋을 확인하면)
xxxxxxxxxx
#shuffle False 설정하면 순서를 뒤섞지 않는다.
x,y = train_test_split(breast_cancer, shuffle = False)
x
셔플을 하지 않으면 정순서대로 나누게 된다.
3.3 Random_state
xxxxxxxxxx
x,y = train_test_split(breast_cancer, test_size = 0.3, random_state = 42)
실행시킬 때 계속 똑같은 결과가 나와야 하는 경우가 있다.
분리의 결과가 계속 똑같이 나온다.
3.4 데이터셋을 두 개 넣기
xxxxxxxxxx
#훈련데이터와 타겟데이터가 따로 있을 때는 따로 넣을 수 있다.
#하지만 훈련용이랑, 타겟용이랑 따로 넣으면 결과가 4개로 나온다.
train_test_split(breast_cancer.iloc[:,:-1], breast_cancer.target)
return => x_train, x_test, y_train, y_teset
x_train 을 보면 데이터 프레임 (data)
x_test 를 보면 데이터 프레임 (data)
y_train을 보면 시리즈 (target)
y_test 를 보면 시리즈 (target)
이때 주의해야할 점!
xxxxxxxxxx
#원래의 타겟의 비율을 유지하면서 train, test 로 분리하는 게 중요하다.
print(breast_cancer.target.value_counts())
breast_cancer.target.value_counts().plot(kind='bar')
중요!!
train과 test를 분리할 때 앞서 test_size 를 설정해서 데이터 record 개수를 일정한 비율로 쪼개었다.
이때 train과 test에 있는 target 데이터의 각 레이블의 비율이 유지가 된채로 쪼개져야한다.
즉, 본 데이터에서 target 레이블이 0과 1이고, 0과 1의 비율이 5:5 이면,
train 데이터 안에서의 target 데이터의 0과 1의 비율도 5:5 여야 하며, test 데이터 안의 target 도 5:5 여야한다.
xxxxxxxxxx
x_train,x_test, y_train, y_test = train_test_split(breast_cancer.iloc[:,:-1], breast_cancer.target, stratify = breast_cancer.target)
stratify
는 본데이터의 타겟 데이터 레이블 비율을 그대로 유지한채 train과 test 데이터로 분리한다.
y_train 과 y_test 의 레이블 비율을 확인해보니 똑같은 비율을 유지하고 있다.
로지스틱 회귀 모형 이용해보기
xxxxxxxxxx
lr = LogisticRegression() #모형 만들기
lr.fit(x_train, y_train) #학습을 시켜준 후
lr.predict(x_test) #데이터를 넣어서 예측하기
- 모형을 만든다.
- 분리한 데이터로 모형을 학습시킨다.
- 예측 결과 값을 predict 를 통해서 확인한다.
- 예측된 결과값과 실제 데이터 값과의 일치성을 확인하여 모델을 평가한다.
xxxxxxxxxx
#정확도를 한번에 계산해준다.
lr.score(x_test, y_test)
결과값의 정확도를 확인해볼 때 함수를 사용한다. lr.score(x_test, y_test)
이용