AI/머신러닝 - 예제

[머신러닝 - 예제] 아이리스 데이터셋 - 사이킷런 데이터셋

caramel-bottle 2023. 12. 22.

1. 데이터셋

사이킷런에서는 다양한 데이터셋을 제공합니다.

 

데이터셋이란 특정한 작업을 위해 데이터를 관련성 있게 모아놓은 것을 말합니다.

 

사이킷런에서 제공하는 데이터셋은 아래 링크에서 확인하실 수 있습니다.

https://scikit-learn.org/stable/modules/classes.html?highlight=datasets#module-sklearn.datasets

 

API Reference

This is the class and function reference of scikit-learn. Please refer to the full user guide for further details, as the class and function raw specifications may not be enough to give full guidel...

scikit-learn.org

 

 

아래 4개의 데이터셋은 사이킷런에서 제공하는 분류(Classification)에 관련된 데이터셋의 일부입니다.

  • datasets.load_breast_cancer(): 위스콘신 주에서 수집된 유방암 데이터셋
  • datasets.load_digits(): 숫자 데이터셋
  • datasets.load_iris(): 아이리스꽃 데이터셋
  • datasets.load_wine(): 와인 데이터셋

'아이리스 데이터셋'을 사용하여 사이킷런 사용법을 익혀봅시다.


2. 아이리스 데이터셋

아이리스 꽃입니다.

 

우리말로 하면 분꽃이라고 하네요.

 

이 데이터셋을 사용하여 모델을 학습시킨 후 시험문제도 잘 푸는지 확인해봅시다.

 

우선 아이리스 데이터셋 사용을 위해 load_iris를 import하고 객체를 생성해줍니다.

from sklearn.datasets import load_iris
iris = load_iris()

 

다른 방법으로도 데이터 객체를 가져올 수 있습니다.

from sklearn.datasets import fetch_openml
iris = fetch_openml(name='iris', version=1)

 

생성한 객체정보를 출력해보면 딕셔너리 형식의 데이터를 확인할 수 있습니다.

{'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],
        [4.6, 3.1, 1.5, 0.2],
        [5. , 3.6, 1.4, 0.2],
        [5.4, 3.9, 1.7, 0.4],
        [4.6, 3.4, 1.4, 0.3],
        [5. , 3.4, 1.5, 0.2],
        [4.4, 2.9, 1.4, 0.2],
        [4.9, 3.1, 1.5, 0.1],
        [5.4, 3.7, 1.5, 0.2],
        [4.8, 3.4, 1.6, 0.2],
        [4.8, 3. , 1.4, 0.1],
        [4.3, 3. , 1.1, 0.1],
        [5.8, 4. , 1.2, 0.2],
        [5.7, 4.4, 1.5, 0.4],
        [5.4, 3.9, 1.3, 0.4],
        [5.1, 3.5, 1.4, 0.3],
        [5.7, 3.8, 1.7, 0.3],
        [5.1, 3.8, 1.5, 0.3],
        [5.4, 3.4, 1.7, 0.2],
        [5.1, 3.7, 1.5, 0.4],
        [4.6, 3.6, 1. , 0.2],
        [5.1, 3.3, 1.7, 0.5],
        [4.8, 3.4, 1.9, 0.2],
        [5. , 3. , 1.6, 0.2],
        [5. , 3.4, 1.6, 0.4],
        [5.2, 3.5, 1.5, 0.2],
        [5.2, 3.4, 1.4, 0.2],
        [4.7, 3.2, 1.6, 0.2],
        [4.8, 3.1, 1.6, 0.2],
        [5.4, 3.4, 1.5, 0.4],
        [5.2, 4.1, 1.5, 0.1],
        [5.5, 4.2, 1.4, 0.2],
        [4.9, 3.1, 1.5, 0.2],
        [5. , 3.2, 1.2, 0.2],
        [5.5, 3.5, 1.3, 0.2],
        [4.9, 3.6, 1.4, 0.1],
        [4.4, 3. , 1.3, 0.2],
        [5.1, 3.4, 1.5, 0.2],
        [5. , 3.5, 1.3, 0.3],
        [4.5, 2.3, 1.3, 0.3],
        [4.4, 3.2, 1.3, 0.2],
        [5. , 3.5, 1.6, 0.6],
        [5.1, 3.8, 1.9, 0.4],
        [4.8, 3. , 1.4, 0.3],
        [5.1, 3.8, 1.6, 0.2],
        [4.6, 3.2, 1.4, 0.2],
        [5.3, 3.7, 1.5, 0.2],
        [5. , 3.3, 1.4, 0.2],
        [7. , 3.2, 4.7, 1.4],
        [6.4, 3.2, 4.5, 1.5],
        [6.9, 3.1, 4.9, 1.5],
        [5.5, 2.3, 4. , 1.3],
        [6.5, 2.8, 4.6, 1.5],
        [5.7, 2.8, 4.5, 1.3],
        [6.3, 3.3, 4.7, 1.6],
        [4.9, 2.4, 3.3, 1. ],
        [6.6, 2.9, 4.6, 1.3],
        [5.2, 2.7, 3.9, 1.4],
        [5. , 2. , 3.5, 1. ],
        [5.9, 3. , 4.2, 1.5],
        [6. , 2.2, 4. , 1. ],
        [6.1, 2.9, 4.7, 1.4],
        [5.6, 2.9, 3.6, 1.3],
        [6.7, 3.1, 4.4, 1.4],
        [5.6, 3. , 4.5, 1.5],
        [5.8, 2.7, 4.1, 1. ],
        [6.2, 2.2, 4.5, 1.5],
        [5.6, 2.5, 3.9, 1.1],
        [5.9, 3.2, 4.8, 1.8],
        [6.1, 2.8, 4. , 1.3],
        [6.3, 2.5, 4.9, 1.5],
        [6.1, 2.8, 4.7, 1.2],
        [6.4, 2.9, 4.3, 1.3],
        [6.6, 3. , 4.4, 1.4],
        [6.8, 2.8, 4.8, 1.4],
        [6.7, 3. , 5. , 1.7],
        [6. , 2.9, 4.5, 1.5],
        [5.7, 2.6, 3.5, 1. ],
        [5.5, 2.4, 3.8, 1.1],
        [5.5, 2.4, 3.7, 1. ],
        [5.8, 2.7, 3.9, 1.2],
        [6. , 2.7, 5.1, 1.6],
        [5.4, 3. , 4.5, 1.5],
        [6. , 3.4, 4.5, 1.6],
        [6.7, 3.1, 4.7, 1.5],
        [6.3, 2.3, 4.4, 1.3],
        [5.6, 3. , 4.1, 1.3],
        [5.5, 2.5, 4. , 1.3],
        [5.5, 2.6, 4.4, 1.2],
        [6.1, 3. , 4.6, 1.4],
        [5.8, 2.6, 4. , 1.2],
        [5. , 2.3, 3.3, 1. ],
        [5.6, 2.7, 4.2, 1.3],
        [5.7, 3. , 4.2, 1.2],
        [5.7, 2.9, 4.2, 1.3],
        [6.2, 2.9, 4.3, 1.3],
        [5.1, 2.5, 3. , 1.1],
        [5.7, 2.8, 4.1, 1.3],
        [6.3, 3.3, 6. , 2.5],
        [5.8, 2.7, 5.1, 1.9],
        [7.1, 3. , 5.9, 2.1],
        [6.3, 2.9, 5.6, 1.8],
        [6.5, 3. , 5.8, 2.2],
        [7.6, 3. , 6.6, 2.1],
        [4.9, 2.5, 4.5, 1.7],
        [7.3, 2.9, 6.3, 1.8],
        [6.7, 2.5, 5.8, 1.8],
        [7.2, 3.6, 6.1, 2.5],
        [6.5, 3.2, 5.1, 2. ],
        [6.4, 2.7, 5.3, 1.9],
        [6.8, 3. , 5.5, 2.1],
        [5.7, 2.5, 5. , 2. ],
        [5.8, 2.8, 5.1, 2.4],
        [6.4, 3.2, 5.3, 2.3],
        [6.5, 3. , 5.5, 1.8],
        [7.7, 3.8, 6.7, 2.2],
        [7.7, 2.6, 6.9, 2.3],
        [6. , 2.2, 5. , 1.5],
        [6.9, 3.2, 5.7, 2.3],
        [5.6, 2.8, 4.9, 2. ],
        [7.7, 2.8, 6.7, 2. ],
        [6.3, 2.7, 4.9, 1.8],
        [6.7, 3.3, 5.7, 2.1],
        [7.2, 3.2, 6. , 1.8],
        [6.2, 2.8, 4.8, 1.8],
        [6.1, 3. , 4.9, 1.8],
        [6.4, 2.8, 5.6, 2.1],
        [7.2, 3. , 5.8, 1.6],
        [7.4, 2.8, 6.1, 1.9],
        [7.9, 3.8, 6.4, 2. ],
        [6.4, 2.8, 5.6, 2.2],
        [6.3, 2.8, 5.1, 1.5],
        [6.1, 2.6, 5.6, 1.4],
        [7.7, 3. , 6.1, 2.3],
        [6.3, 3.4, 5.6, 2.4],
        [6.4, 3.1, 5.5, 1.8],
        [6. , 3. , 4.8, 1.8],
        [6.9, 3.1, 5.4, 2.1],
        [6.7, 3.1, 5.6, 2.4],
        [6.9, 3.1, 5.1, 2.3],
        [5.8, 2.7, 5.1, 1.9],
        [6.8, 3.2, 5.9, 2.3],
        [6.7, 3.3, 5.7, 2.5],
        [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'}

 

 

정말 기네요.

 

출력을 확인해보면 data와 target은 쌍을 이루고 있을 것으로 예상됩니다.

 

실제로 data가 주어지는 정보이고 target이 정답일테니 쌍이 맞습니다.

 

data는 feature, target은 label이라고도 합니다.

 

데이터셋을 더 자세히 보기 위해 'DESCR'을 출력해보면

print(iris["DESCR"])

output>>

.. _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
                
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

.. topic:: References

   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...

이것도 기네요.

 

이렇게 'DESCR'을 통해 데이터셋에 대한 더 자세한 정보를 볼 수 있습니다. 

 

data 수치들의 의미는 'feature_names'을 통해 알 수 있습니다.

feature_names = iris['feature_names']
feature_names

output>>

['sepal length (cm)',
 'sepal width (cm)',
 'petal length (cm)',
 'petal width (cm)']
- sepal length in cm: 꽃받침의 길이
- sepal width in cm: 꽃받침의 너비
- petal length in cm: 꽃잎의 길이
- petal width in cm: 꽃잎의 너비

3. 판다스를 사용하여 데이터 전처리하기

학습에 데이터를 집어넣기 위해선 데이터를 적절하게 수정해줄 필요가 있습니다.

 

이 수정을 데이터 전처리라고 합니다.

 

판다스(pandas)를 사용하여 가진 데이터들을 머신러닝에 사용하기 좋게 만들어봅시다!

import pandas as pd

df_iris = pd.DataFrame(data, columns=feature_names)
df_iris.head()

output>>

'data'의 내용들을 DataFrame으로 만든 것입니다.

 

각각의 필드는 정답(target)이 존재하니 DataFrame에 정답을 추가해보죠.

target = iris['target']
df_iris['target'] = target
df_iris.head()

output>>

data와 target이 쌍이 맞춰져 있기 때문에 잘 만들어진 DataFrame이 되었습니다.


4. 학습

이제 문제를 풀 모델(학생)을 학습시켜봅시다.

 

우리가 가진 데이터는 독립변수인 data(feature), 종속변수인 target(label)로 나뉩니다.

 

독립변수와 종속변수의 쌍을 잘 맞춰서 train데이터와 test데이터로 나누는 작업이 필요합니다.

 

직접 데이터를 나누는 것도 가능하지만 sklearn.model_selection의 train_test_split 메서드를 사용해봅시다.

 

* train_test_split

Split arrays or matrices into random train and test subsets.
"배열이나 행렬을 무작위로 훈련 세트와 테스트 세트로 나눕니다."

 

train_test_split에 사용되는 매개변수는 다음과 같습니다.

def train_test_split(
    *arrays,
    test_size=None,
    train_size=None,
    random_state=None,
    shuffle=True,
    stratify=None,
):

 

*arrays에는 length와 shape[0]이 같은 sequence가 입력되어야합니다.

 

입력된 배열이나 행렬은 무작위로 섞인 데이터셋을 반환합니다.

 

반환값을 담는 변수는 보통 이렇게 사용합니다.

X_train, X_test, y_train, y_test = train_test_split(...)

 

이제 iris 데이터를 학습용 데이터로 만들어봅시다.


4-1. train, test

X_train, X_test, y_train, y_test = train_test_split(df_iris.drop('target', 1),
                                                    df_iris['target'],
                                                    test_size=0.2,
                                                    random_state=2023)

 

독립변수로는 df에서 'target'(종속변수)을 제외한 데이터를 사용하고, 종속변수로는 'target'을 사용합니다.

 

test_size는 훈련할 데이터를 제외한 시험(test)용 데이터 크기입니다.

 

시험(test)에 전체 데이터중 20%만 사용하기 위해 test_size=0.2로 합니다. 25%를 사용하고 싶다면 0.25를 주면 되겠죠.

 

shape 확인

X_train.shape, X_test.shape

output>>

((120, 4), (30, 4))

 

y_train.shape, y_test.shape

output>>

((120,), (30,))

5. 모델 성능 검증

우리가 사용한 데이터셋은 분류(Classification) 예제에 사용하기 좋습니다.

 

분류에 사용하기 좋은 svm(Support Vector Machine)을 사용하여 정확하게 분류하는지 확인해봅시다.

from sklearn.svm import SVC # classification class
from sklearn.metrics import accuracy_score

 

서포트 벡터 머신(svm)의 구현방법중 하나인 Support Vector Classificaion을 사용합니다.

 

SVC는 이진 분류에 사용하기 아주 좋고, 선형적으로 분리가 가능한 경우에 아주 적합합니다.

 

성능 평가 지표로는 accuracy_score를 사용합니다.

 

우선 SVC객체 즉, 학생일 될 친구를 만들어줍니다.

svc = SVC()

 

다음으로 학습을 위해 fit()을 사용합니다. fit()은 주어진 데이터를 사용하여 SVM 모델을 훈련시키는 함수입니다.

svc.fit(X_train, y_train)

 

이제 svc는 적절하게 훈련된 학생이 되었습니다.


6. 검증

이제 시험을 통해 잘 학습이 되었는지 확인해봅시다.

y_pred = svc.predict(X_test)

 

predict 함수는 입력한 데이터에 대한 정답을 예측하여 반환합니다.

print('정답률', accuracy_score(y_test, y_pred))

output>>

정답률 1.0

 

이 학생은 만점이네요
 

테스트 데이터가 아닌 돌발퀴즈를 입력해도 잘 맞출까요?

y_pred = svc.predict([[6.4, 2.6, 5.1, 1.9]])

output>>

[2]

정답을 2로 제출하였네요.

 

임의로 낸 문제라 출제자가 정답을 알아야하는데 저는 정답을 모릅니다.

 

잘 맞췄을 거라 생각합시다!


결론

사이킷 런에서 제공하는 데이터셋을 통해 간단하게 데이터 전처리, 학습, 예측, 검증의 과정을 살펴보았습니다.

 

더 자세한 머신러닝 개념은 차차 포스팅하도록 하겠습니다.

댓글