sklearn.datasets

Load_Boston 데이터셋

sklearn에서는 간단한 머신러닝 알고리즘 분석과 테스트를 위해서 작은 규모의 데이터셋(small toy datasets)을 datasets이라는 패키지에 담아두었습니다. 해당 데이터셋들은 데이터에 대한 정보와 특징들이 포함되어 있어 데이터셋을 이용하는 사용자로 하여금 해당 데이터셋이 어떤 의미인가를 쉽게 이해할 수 있도록 해주고 있습니다.

https://scikit-learn.org/stable/datasets/index.html#toy-datasets

공식 홈페이지에 들어가보시면 제공하는 데이터의 내용들을 확인 하실 수 있습니다. 간략한 정보는 아래와 같습니다.

  • load_boston : 보스턴 지역의 집값 데이터(회귀분석)
  • load_iris : 붗꽃 데이터(분류)
  • load_diabetes : 당뇨병 데이터(회귀분석)
  • load_digits : 숫자 이미지 데이터(분류)
  • load_linnerud : 20대 중반 남성의 신체정보와 운동정보(다변량분석)
  • load_wine : 와인의 특징에 따른 종류(분류)
  • load_breast_cancer : 유방암 데이터(분류)
from sklearn.datasets import load_boston
boston = load_boston()

데이터셋을 로딩하는데는 load라는 명령어와 함께 해당 데이터셋의 이름을 적어주면 간단히 로딩할 수 있습니다.
데이터를 로딩한 후에는 DESCR 을 통해서 해당 데이터셋이 어떤 특징이 있는지 살펴볼 수 있습니다.

print(boston.DESCR)
.. _boston_dataset:

Boston house prices dataset
---------------------------

**Data Set Characteristics:**  

    :Number of Instances: 506 

    :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.

    :Attribute Information (in order):
        - CRIM     per capita crime rate by town
        - ZN       proportion of residential land zoned for lots over 25,000 sq.ft.
        - INDUS    proportion of non-retail business acres per town
        - CHAS     Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
        - NOX      nitric oxides concentration (parts per 10 million)
        - RM       average number of rooms per dwelling
        - AGE      proportion of owner-occupied units built prior to 1940
        - DIS      weighted distances to five Boston employment centres
        - RAD      index of accessibility to radial highways
        - TAX      full-value property-tax rate per $10,000
        - PTRATIO  pupil-teacher ratio by town
        - B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
        - LSTAT    % lower status of the population
        - MEDV     Median value of owner-occupied homes in $1000's

    :Missing Attribute Values: None

    :Creator: Harrison, D. and Rubinfeld, D.L.

This is a copy of UCI ML housing dataset.
https://archive.ics.uci.edu/ml/machine-learning-databases/housing/
...

DESCR 외에도 해당 boston 데이터셋에는 몇가지의 key 값이 더 있습니다. 해당 키값을 모두 보기 위해서는 boston.key() 명령을 사용합니다.

boston.keys()
# dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])
  • data : 데이터셋의 정보가 numpy.ndarray 형태로 저장
  • target : 레이블 정보
  • feature_names : 데이터셋의 컬럼정보
  • DESCR : 데이터셋 설명
  • filename : 해당 데이터셋의 저장 위치 정보 표시

이렇게 입력된 데이터는 컬럼 정보와 분리되어 있기 때문에 보기에 좀 불편하고 어려울 수 있습니다. 이럴 때에 pandas 패키지를 통해 데이터프레임을 만들면 탐색적데이터분석에 좀 더 유리합니다.

import pandas as pd
df = pd.DataFrame(data=boston.data, columns = boston.feature_names)
df['TARGET'] = boston.target
df.head()

pandas의 데이터프레임으로 해당 데이터를 변경해보면 위와 같은 형태로 보여지기 때문에 데이터를 보기가 좀 더 편리합니다. 좀 더 자세한 정보를 보시고 싶으시면 df.info(), df.describe()와 같은 함수를 사용해보시면 각 컬럼의 데이터 타입과 기본적인 통계정보를 확인 할 수 있습니다. 추가로 matplotlib과 같은 시각화 함수를 사용하면 데이터를 내용을 더 쉽게 파악할 수 있습니다.

import matplotlib.pyplot as plt
plt.figure(figsize=(12,5))
plt.scatter(scaled_df['AGE'],scaled_df['DIS'])
corr = scaled_df.corr()
corr.style.background_gradient(cmap='coolwarm')

시각화로 데이터셋의 내용을 살펴본 후에 학습을 위해서 데이터를 나눠줄 필요가 있을 경우에 sklearn은 훌륭한 유틸 함수를 제공합니다. 아래와 같이 model_selection 패키지에서 train_test_split을 사용해서 학습용, 훈련용 데이터셋을 만들 수 있습니다.

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, shuffle=False, random_state=701)
print(x_train.shape) #404,13
print(x_test.shape) #102,13

Load_Digit 데이터셋

boston 데이터셋은 연속된 값을 가지는 회귀분석에서 많이 사용하는 예제입니다. 이번에는 분류 문제에 사용하는 데이터셋인 숫자(digit) 데이터셋을 살펴보겠습니다. 이 데이터의 shape은 (1797, 64) 입니다. 이것은 8 x 8 이미지를 1차원(64)으로 생성한 값인데 이러한 이미지가 1,797개가 있다는 의미입니다.

from sklearn.datasets import load_digits
digits = load_digits()
digits.data[0]
array([ 0.,  0.,  5., 13.,  9.,  1.,  0.,  0.,  0.,  0., 13., 15., 10.,
       15.,  5.,  0.,  0.,  3., 15.,  2.,  0., 11.,  8.,  0.,  0.,  4.,
       12.,  0.,  0.,  8.,  8.,  0.,  0.,  5.,  8.,  0.,  0.,  9.,  8.,
        0.,  0.,  4., 11.,  0.,  1., 12.,  7.,  0.,  0.,  2., 14.,  5.,
       10., 12.,  0.,  0.,  0.,  0.,  6., 13., 10.,  0.,  0.,  0.])
plt.imshow(digits.data[0].reshape(8,8))

해당 배열의 첫번째 값을 가지고 8×8배열로 만든 후에 이것을 이미지로 표시해보면 위와 같은 이미지 “0” 값이 나옵니다. 즉 이런 데이터가 1,797개가 있다는 의미입니다. 이러한 데이터를 훈련시키면 숫자가 입력될 때 이것이 어떤 숫자인지 예측할 수 있게 됩니다.

from sklearn.decomposition import PCA
pca = PCA(n_components=2) # 시각화를 위해 2차원으로 성분을 추출
dim2data = pca.fit_transform(digits.data)
plt.figure(figsize=(6,6))
plt.scatter(dim2digit[:,0], dim2digit[:, 1], c=digits.target, linewidth=1)
plt.show()

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다