오답 노트/머신러닝

훈련데이터셋 나누기(fit.train_test_split()): 각 parameter들의 의미

히니1008 2022. 7. 25. 19:43

전제 조건

1.테스트 세트보다 훈련 세트가 더 많아야 함

2.훈련 데이터 세트를 나누기 전에 골고루 섞어야 한다


 

골고루 섞이기 위해 필요한 함수    

#골고루 섞이게 만들려면 나와야 하는 함수
np.random.seed(42)
index = np.arange(49)
np.random.shuffle(index)

How?

# 훈련데이터 세트 세팅
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
x = cancer.data
y = cancer.target

# 훈련데이터 세트 분할
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, stratify=y, test_size=0.2, random_state=42)

1) stratify: array-like, default = None

(if not None, data is split in a stratified fashion, using this as the class labels)

Stratified sampling aims at splitting a data set so that each split is similar with respect to something. 

In a classification setting, it is often chosen to ensure that the train and test sets have approximately the same percentage of smples of each target class as the complete set.( 테스트 데이터와 훈련 데이터를 나눌 때 무작위로 샘플링을 하되 original dataset의 클래스 비율이 train,test set에서도 동일하게 유지되는 것을 보장한다는 점) -> Random Sampling과 다른 점

As a result, if the data set has a large amount of each class, stratified sampling is pretty much the same as random sampling. But if one class isn't much represented in the data set, which may be the case in your dataset since you plan to oversample the minority class, then stratified sampling may yield a different target class distribution in the train and test sets than what random sampling may yield.

Note that the stratified sampling may also be designed to equally distribute some features in the next train and test sets. For example, if each sample represents one individual, and one feature is age, it is sometimes useful to have the same age distribution in both the train and test set. 

 


2) test_size = 0.2

테스트 set와 훈련 set를 75:25의 비율로 나눈다. 이 비율을 조정하고 싶을 때에는 test_size 매개변수에 test_set의 비율을 전달하면 조절할 수 있다. 여기서 입력된 데이터 세트의 20%를 테스트 세트로 나누기 위해 0.2를 전달했다.

 


3) random_state = 42

train_test_split( )는 데이터를 무작위로 섞은 뒤, 데이터 셋을 나누다. 그래서 함수를 호출할 때마다 다른 결과로 분할이 되는데, random_state 를 특정 숫자로 지정하면 항상 동일하게 분할 할 수 있다. 실제 상황에는 거의 필요 없지만, 다른 사람들과 결과를 공유해야 하거나 실험결과를 똑같이 재현해야 할 때는 유용하게 쓰인다.

 

'오답 노트 > 머신러닝' 카테고리의 다른 글

헷갈리는 함수(Train,Test split)  (0) 2022.07.30
.set_index 메서드와 .reset_index메서드  (0) 2022.07.26
딥러닝 -자연어 처리  (0) 2022.07.26
데이터 다루기  (0) 2022.07.24