Data Analysis/Machine Learning

scikit-learn libraray 사용, 데이터 분할

유방울 2023. 6. 1. 17:01

데이터 셋 가져오기

라이브러리 import
import pandas as pd
from sklearn.preprecessing import StandardScaler
from sklearn.model_selection imort train_test_split
from sklearn.neighbors import KNeighborsClassifier
# [1]  bigdata/iris_data.csv 를  가져오기 한다
# 어떤 붓꽃인지 맞추기 !!
# 3가지 종류가 있음 0,1,2로 맞춰놓음
df = pd.read_csv('iris_data.csv')
df.head()


sepal length (cm)	sepal width (cm)	petal length (cm)	petal width (cm)	target
0	5.1	3.5	1.4	0.2	0
1	4.9	3.0	1.4	0.2	0
2	4.7	3.2	1.3	0.2	0
3	4.6	3.1	1.5	0.2	0
4	5.0	3.6	1.4	0.2	0

petal : 꽃잎

sepal : 꽃받침

 

데이터 전처리

fit(X_train) : 전처리에 필요한 값 준비, return scaler

transform(X_train) : 전처리 실행, return 변환된 값

fit_transform(X_train) : 전처리에 필요 값 준비 + 처리, return 변환된 값

 

X_train, X_test 합쳐서 전처리 작업

전처리 작업 후 분리해서 X_train은 학습모델 생성

X_test 제출용값을 구하는 데 사용

scaler.fit_transform(X_train + X_test)

 

X_train, X_test 각각 전처리 작업

X_train에 적용된 전처리가 그대로 X_test에 적용되어야 함

scaler.fit(X_train) : 전처리에 필요한 값 준

scaler.transform(X_train)

scaler.transofrm(X_test) 

 

# X, Y 데이터로 분리
X = df.iloc[:,:-1]
Y = df.iloc[:,-1] # df['target']
# StandardScaler 사용해 표준 정규 분포 만들기
scaledX = StandardScaler().fit_transform(X)

# 정규화 후 평균 0에 가까움, 표준편차 1에 가까움
print(scaledX.mean(), scaledX.std())

-1.273055734903513e-16 0.9999999999999998

데이터 분할

sklearn.model_selection.train_test_split

x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size, train_size, random_state, shuffle, stratify)

- 배열들을 지정된 비율로 나눠서 반환

- test_size = 0.25 : 0.0 ~1.0 데스트 데이터셋 비율

- train_size = None: 0.0 ~1.0 훈련 데이터셋 비율

   - 둘 중 하나 설명하면 나머지 알아서 설정됨 -> 각각 지정도 가능하지만 합이 1이어야 함

- random_state = None : 정수값, 난ㅅㅜ 발새의 시드 값 

- shuffle = True : boolean 값을 전달해 섞을지 말지 결정, 디폴트 True,

- stratify : Y의 지정한 데이터 비율을 유지 (층화추출), Y가 범주형일 때 사용

  - but 회귀에서 사용 x

 

from sklearn.model_selection import train_test_split

# 8:2 나누기
a = list(range(10))
x = train_test_split(a, test_size=0.2)
# 층화추출 이해
a = [1,1,2,3] * 5 # 20개 데이터로 8:2, 4:1

# 20개 데이터라 테스트 4개 트레인 16개로 1:4
x_train, x_test = train_test_split(a, test_size=0.2, stratify=a)
print(x_train, x_test)

[3, 3, 1, 1, 3, 2, 1, 1, 2, 1, 3, 1, 2, 1, 2, 1] [3, 2, 1, 1]
#[6] 여러 개 데이터셋을 분할
a = list(range(10))
b = list(range(10))
# a, b는 같은 길이를 가져야 함!
# 데이터의 수가 부족하면 random_state가 어떤 수를 지정할 때 값이 달라짐
# 수가 많으면 값이 같음
a_train, a_test, b_train, b_test = train_test_split(a,b, test_size=0.2, random_state=0)
print(a_train, a_test, b_train, b_test)
x_train, x_test, y_train, y_test = train_test_split(scaledX, test_size=0.2, random_state=0, stratify=Y)
print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)

(120, 4) (30, 4) (120,) (30,)