사이킷런의 sklearn.model_selection 패키지 안에는 여러 가지 분할기 클래스를 제공한다. 모든 분할기는 또한 훈련과 테스트 분할에 대한 반복자를 반환하는 split() 메소드를 가지고 있다.
이 코드에서는 StratifiedShuffleSplit을 사용해 10개의 다른 계층 분할을 생성한다.
from sklearn.model_selection import StratifiedShuffleSplit
splitter = StratifiedShuffleSplit(n_splits=10, test_size=0.2, random_state=42)
strat_splits = []
for train_index, test_index in splitter.split(housing, housing["income_cat"]):
strat_train_set_n = housing.iloc[train_index]
strat_test_set_n = housing.iloc[test_index]
strat_splits.append([strat_train_set_n, strat_test_set_n])
첫 번째 분할을 다음과 같이 사용할 수 있다.
strat_train_set, strat_test_set = strat_splits[0]
다음과 같은 방식으로 계층적 샘플링을 코드 한 줄로 불러오는 것도 가능하다.
strat_train_set, strat_test_set = train_test_split(housing, test_size=0.2, stratify=housing["income_cat"], random_state=42)
먼저, 다음과 같은 코드를 통해 지리 정보를 산점도로 만들어 시각화해보자.
housing.plot(kind="scatter", x="longitude", y="latitude", grid=True)
plt.xlabel("경도")
plt.ylabel("위도")
plt.show()

이 그래프에서, 데이터 포인트가 밀접된 영역을 확인해보자.
housing.plot(kind="scatter", x="longitude", y="latitude", grid=True, alpha=0.2)
plt.xlabel("logitude")
plt.ylabel("latitude")
plt.show()

다음으로는 구역의 인구와 주택가격까지 그림에 나타내보자.
housing.plot(kind="scatter", x="longitude", y="latitude", grid=True,
s=housing["population"] / 100, label="population",
c="median_house_value", cmap="jet", colorbar=True,
legend=True, figsize=(10, 7))
plt.show()
