Study/Python

[Python]Sckit-Learn에 있는 데이터를 csv로 만들기

SigmoidFunction 2022. 3. 17. 10:02
728x90

머신러닝 오픈소스 중 하나인 사이킷런에서는 여러가지 머신러닝용 데이터를 제공한다.

그런데 이런 데이터들을 하나의 csv파일로 정리해서 출력할 수는 없을까?

 

아주 간단한 방법으로 해당 작업을 진행하였다.

 

pandas의 데이터처리 방법도 포함이 되어있기 때문에 일부분 필요한 것만 골라서 사용할 때도 유용할테니 참고 바랍니다.

 

우선, 이 작업에서 사용할 모듈들입니다.

import pandas as pd
from sklearn.datasets import load_iris # iris data불러오기
import numpy as np

csv로 변환하고 데이터프레임으로 만들어줄 pandas, 사이킷런에서 제공하는 데이터를 받아올 load_iris, array형식으로 되어있는 데이터를 처리해줄 numpy

 

 

우선 iris데이터를 받아보자

iris_dataset = load_iris()
iris_dataset
{'data': array([[5.1, 3.5, 1.4, 0.2],
        [4.9, 3. , 1.4, 0.2],
        [4.7, 3.2, 1.3, 0.2],
       		<== (생략) ==>
        [6.7, 3. , 5.2, 2.3],
        [6.3, 2.5, 5. , 1.9],
        [6.5, 3. , 5.2, 2. ],
        [6.2, 3.4, 5.4, 2.3],
        [5.9, 3. , 5.1, 1.8]]),
 'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]),
 'frame': None,
 'target_names': array(['setosa', 'versicolor', 'virginica'], dtype='<U10'),
 'DESCR': '.. _iris_dataset:\n\nIris plants dataset\n--------------------\n\n**Data Set Characteristics:**\n\n    :Number of Instances: 150 (50 in each of three classes)\n    :Number of Attributes: 4 numeric, predictive attributes and the class\n    :Attribute Information:\n        - sepal length in cm\n        - sepal width in cm\n        - petal length in cm\n        - petal width in cm\n        - class:\n                - Iris-Setosa\n                - Iris-Versicolour\n                - Iris-Virginica\n                \n    :Summary Statistics:\n\n    ============== ==== ==== ======= ===== ====================\n                    Min  Max   Mean    SD   Class Correlation\n    ============== ==== ==== ======= ===== ====================\n    sepal length:   4.3  7.9   5.84   0.83    0.7826\n    sepal width:    2.0  4.4   3.05   0.43   -0.4194\n    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\n    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)\n    ============== ==== ==== ======= ===== ====================\n\n    :Missing Attribute Values: None\n    :Class Distribution: 33.3% for each of 3 classes.\n    :Creator: R.A. Fisher\n    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\n    :Date: July, 1988\n\nThe famous Iris database, first used by Sir R.A. Fisher. The dataset is taken\nfrom Fisher\'s paper. Note that it\'s the same as in R, but not as in the UCI\nMachine Learning Repository, which has two wrong data points.\n\nThis is perhaps the best known database to be found in the\npattern recognition literature.  Fisher\'s paper is a classic in the field and\nis referenced frequently to this day.  (See Duda & Hart, for example.)  The\ndata set contains 3 classes of 50 instances each, where each class refers to a\ntype of iris plant.  One class is linearly separable from the other 2; the\nlatter are NOT linearly separable from each other.\n\n.. topic:: References\n\n   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"\n     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to\n     Mathematical Statistics" (John Wiley, NY, 1950).\n   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.\n     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\n   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System\n     Structure and Classification Rule for Recognition in Partially Exposed\n     Environments".  IEEE Transactions on Pattern Analysis and Machine\n     Intelligence, Vol. PAMI-2, No. 1, 67-71.\n   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions\n     on Information Theory, May 1972, 431-433.\n   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II\n     conceptual clustering system finds 3 classes in the data.\n   - Many, many more ...',
 'feature_names': ['sepal length (cm)',
  'sepal width (cm)',
  'petal length (cm)',
  'petal width (cm)'],
 'filename': 'iris.csv',
 'data_module': 'sklearn.datasets.data'}

위와 같은 결과가 뜬다. 블로그의 가독성을 위해 생각했다.

이 데이터의 타입을 출력해보면

sklearn.utils.Bunch

이런식으로 나오는데 걍 딕셔너리처럼 나온다고 보면된다.

 

 

어떠한 요소들이 제공되는 지 key값을 보자.

 

print("iris_dataset의 키: \n{}".format(iris_dataset.keys()))
iris_dataset의 키: 
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])

data가 분류에 사용될 값들, target은 label이라고 보면되고 target_names는 target을 설명한 것으로 보면된다.

그리고 feature_names는 data의 컬럼명이라고 보면 된다.

한번 살펴보자

 

print("타깃의 이름: {}".format(iris_dataset['target_names']))
print("특성의 이름: \n{}".format(iris_dataset['feature_names']))
타깃의 이름: ['setosa' 'versicolor' 'virginica']
특성의 이름: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

어렵게 생각할 것없이 setosa가 target 0, virginica가 2로 보면 된다.

 

자, 나는 여기서 data와 target만 정리된 데이터프레임을 얻고 싶다.

 

위에서 data는 array형식으로 제공되는데 array는 쉽게 dataframe으로 변환 가능하다.

data = pd.DataFrame(iris_dataset['data'], columns=['sepal length','sepal width','petal length','petal width'])

iris_dataset['data']를 dataframe으로 변환하는데 컬럼명을 feature_names로 넣어서 만들었다.

 

이렇게 이쁘게 dataframe이 만들어진다.

 

이제 target데이터를 만들어서 여기에 붙여보자.

 

현재 target데이터는 0,1,2의 numeric data로 되어있는데 개인적으로 문자열로 바꿔넣고 싶다.

 

이럴 땐, np.where를 사용하면 쉽다.

(사실 더 좋은 방법이 있을 듯한데, 더좋은 방법을 아신다면 댓글 꼭 부탁드립니다.)

 

numeric_target = iris_dataset['target']
categorical_target = np.where(numeric_target == 0, 'setosa', numeric_target)
categorical_target = np.where(numeric_target == 1, 'versicolor', categorical_target)
categorical_target = np.where(numeric_target == 2, 'virginica', categorical_target)

target에서 0을 setosa로 바꾸고 저장, setosa를 저장한걸 다시 불러와서 1을 versicolor로 저장...반복해주었다.

 

기존의 0,1,2 문자열로 대체되었다.

 

이제 아까 dataframe을 만들었던것과 동일한 작업을 해준다.

 

target = pd.DataFrame(categorical_target, columns=['iris'])

짠-

 

 

이제 변환한 data와 target을 합쳐줄 것이다.

 

간단한 concat을 활용!

total = pd.concat([data,target],axis=1)
total

우리가 원했던 데이터프레임이 완성되었다.

 

total.to_csv("iris.csv", index=False)

이제 이렇게 csv로 저장해주면 모든 작업은 완료된다.

728x90