250x250
Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags more
Archives
Today
Total
관리 메뉴

Python 연습장

사이킷런 데이터셋 (sklearn.datasets) 본문

코딩

사이킷런 데이터셋 (sklearn.datasets)

포숑 2021. 12. 29. 20:00
728x90

 

코딩 연습해볼 때 적절한 csv파일 데이터셋이 있는 게 가장 좋겠지만

sklearn에 기본 내장되어있는 데이터셋도 있으니 연습할 때는 sklearn에서 불러와서 쓰는 것도 좋을 것 같다.

 

 

 

sklearn dataset의 기본 구조

먼저, sklearn에서 데이터셋을 가지고 있는 함수를 불러와야 한다 : from sklearn.datasets import load_iris

load_iris() 함수는 우리가 사용하고자 하는 dataframe 형태가 아닌, key와 value를 가진 사전식으로 구성되어 있어서 데이터와 칼럼을 불러와서 따로 만들어줘야 한다.

from sklearn.datasets import load_iris 
iris = load_iris() 
print(iris.keys())
# 출력 : dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])

keys()를 통해서 어떤 키값들을 갖고 있는지 알 수 있고, 해당 데이터셋을 처음 본다면 DESCR을 사용해서 설명을 먼저 보고 시작하면 좋다.

print(iris.DESCR)

'''
_iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
....
'''

데이터 프레임 형태로 만들기 전 각 데이터들을 확인해보자.

feature에 해당하는 건 data와 feature_names를 통해서 확인할 수 있고 target 은 target, target_names로 가공할 수 있다.

# X(features)
print(iris.data.shape) # (150, 4)
print(iris.feature_names) 
# ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

# Y(target)
print(iris.target.shape) # (150,) / 0,1,2 로 구성됨
print(iris.target_names) # ['setosa' 'versicolor' 'virginica']

데이터는 (150, 4)의 shape으로 구성되어있고 칼럼명은 feature_names로 알 수 있다. target값은 150개인데 숫자로 되어있어서 저 target_names로 바꿔줄 거다. 이럴 때는 인덱싱을 사용하면 된다.

iris.target_names[iris.target]

위에서 사용한 방법을 짧게 설명하면,

testarray = np.array(['A', 'B', 'C']) 의 array에서 'A'만 뽑아주고 싶으면 testarray [0]으로 가져오고,

A 2번 B 1번 뽑고 싶으면 testarray[[0,0,1]] 로 가져오는 방법이다.

 

dataframe 은 아래와 같이 완성할 수 있다.

df = pd.DataFrame(data = iris.data, columns = iris.feature_names)
df['target'] = iris.target_names[iris.target] 
print(df)

 

sklearn.datasets에서 dataframe을 만드는 최종 코드

기본적으로 다른 dataset 들도 다 비슷한 형태로 되어있으니 이 코드 하나만 알면 될 것 같다.

from sklearn.datasets import load_breast_cancer
from sklearn.datasets import load_wine
from sklearn.datasets import load_diabetes
from sklearn.datasets import load_iris

rawdata = load_breast_cancer()
print(rawdata.keys())
df = pd.DataFrame(data = rawdata.data, columns = rawdata.feature_names)
if 'target_names' in rawdata.keys() : 
    df['target'] = rawdata.target_names[rawdata.target]
else:
    df['target'] = rawdata.target
print(df)

target_names과 value가 여러 개 있는 linnerud dataset의 경우에는 아래와 같이 정리해주면 된다.

from sklearn.datasets import load_linnerud

rawdata = load_linnerud()
print(rawdata.keys())
df = pd.DataFrame(data = rawdata.data, columns = rawdata.feature_names)
df[rawdata.target_names] = rawdata.target
728x90
Comments