728x90
728x90

계층적 샘플링 - Stratified sampling

- 모집단을 여러개의 층으로 구분하여, 각 층에서 n개씩 랜덤하게 추출하는 방법

- 순수한 무작위 샘플링 방식은 데이터의 크기가 충분히 크지 않은 상황 등 샘플링 편향이 발생할 수 있는 가능성이 생길수 있습니다. 

- 전체 데이터를 계층별 그룹으로 나눈뒤 . 테스트 세트가 전체 데이터의 각 계층의 계수 비율 만큼 샘플링 합니다.

 

 

사이킷 런 계층적 샘플링 - sklearn.model_selection.StratifiedShuffleSplit

- 사이킷 런에서 제공하는 API 참고 자료의 예제를 통해 알아 보겠습니다.(*사이런을 먼저 설치 합니다.)

 

StratifiedShuffleSplit(n_splits=10, *, test_size=None, train_size=None, random_state=None

- 사용할 수 있는 parameter 들입니다.

n_splits int , default = 10
분리할 데이터 셋의 개수를 지정합니다.
test_size float, int, default = None
테스트 셋의 비율을 지정합니다.
train_size float, int, defalt = None
훈련 셋의 비율을 지정합니다.
random_state int or RandomState instance, defalt = None
생성된 훈련 및 데스트 셋 난수를 지정

예제

- 파이썬 numpy를 이용해 ndarray를 생성합니다.

- 사이킷런 StratifiedShuffleSplit 을 사용해 계층적 샘플링을 진행합니다.

>>> import numpy as np
>>> from sklearn.model_selection import StratifiedShuffleSplit

>>> X = np.array([[1,2],[3,4],[1,2],[3,4],[1,2],[3,4]])
>>> y = np.array([0,0,0,1,1,1])

>>> print('X : \n', X)
>>> print('y : \n', y)

X : 
 [[1 2]
 [3 4]
 [1 2]
 [3 4]
 [1 2]
 [3 4]]
y : 
 [0 0 0 1 1 1]

- 5개 계층으로 나누고, 테스트 셋 비율을 0.5 로 지정합니다.

split = StratifiedShuffleSplit(n_splits = 5 , test_size = 0.5, random_state = 0)

StratifiedShuffleSplit Methods 

- 사용할수 있는 함수로는 get_n_splits() 와 split() 함수가 있습니다.

- get_n_splits() 함수는 X , y의 arguments 로 features 데이터 셋와 labels 등 데이터 셋을 대입하면, return 값으로 n_plits 을 반환합니다.

>>> split.get_n_splits(X, y)
5

- split() 함수는 데이터를 훈련 및 테스트 세트로 분할하기 위한 인덱스를 생성해 반환합니다.

>>> for train_index , test_index in split.split(X,y):
		print('train_index : ', train_index, 'test_index : ', test_index)

train_index :  [5 2 3] test_index :  [4 1 0]
train_index :  [5 1 4] test_index :  [0 2 3]
train_index :  [5 0 2] test_index :  [4 3 1]
train_index :  [4 1 0] test_index :  [2 3 5]
train_index :  [0 5 1] test_index :  [3 4 2]

 

Scikit learn API Reference
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html

 

 

 

728x90
728x90
728x90

+ Recent posts