본문 바로가기
AI

사이킷런/아이리스 데이터셋 예제

by 코낄2 2023. 12. 24.

1. 사이킷런(Scikit-learn)

사이킷런(Scikit-learn)은 파이썬에서 사용할 수 있는 머신러닝 라이브러리 중 하나로, 간단하고 효과적인 도구들, 다양한 샘플 데이터를 제공하여 머신러닝 모델을 만들고 평가, 검증하는 데 사용됩니다. BSD 라이선스이기 때문에 무료로 사용 및 배포가 가능합니다.

https://scikit-learn.org/stable/

 

scikit-learn: machine learning in Python — scikit-learn 1.3.2 documentation

Model selection Comparing, validating and choosing parameters and models. Applications: Improved accuracy via parameter tuning Algorithms: grid search, cross validation, metrics, and more...

scikit-learn.org

2. LinearSVC

LinearSVC선형 서포트 벡터 머신(Support Vector Machine) 분류기 중 하나로, 선형 결정 경계를 찾아내어 데이터를 분류하는 모델입니다. 즉, 클래스를 구분하는 분류 문제에서 각 클래스를 가장 잘 구분하는 선을 그려주는 방식을 사용하는 알고리즘입니다. 지도학습 알고리즘을 사용하기 때문에 학습 전용 데이터(독립변수)와 결과 전용 데이터(종속변수)를 모두 가지고 있어야 사용이 가능합니다. 3차원을 2차원으로 바꾸고 데이터를 분류 후에 선을 그어줍니다.

 

LinearSVC를 사용하여 모델을 학습하고 예측한 후 정확도를 평가하는 간단한 예제를 학습해보겠습니다. 주요 단계는 데이터 준비, 모델 객체 생성, (전처리), 모델 학습, 검증, 예측, 평가로 나뉩니다.

from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
# 학습 데이터 준비
learn_data = [[0,0], [1,0], [0,1], [1,1]] # 독립변수
learn_label = [0,0,0,1] # 종속변수

>> and연산으로 간단한 예제 실험

# 모델 객체 생성
svc = LinearSVC()

✔️ 간단한 and연산이기 때문에 전처리 할 데이터가 없어 전처리 과정 생략.

# 학습
svc.fit(learn_data, learn_label) # 데이터 갯수 맞아야함

학습 완료

# 검증 데이터 준비
test_data = [[0,0], [1,0], [0,1], [1,1]] 
# 원래 검증은 다른 데이터로 하지만, 현재는 and연산의 다른 데이터가 없음
# 예측
test_label = svc.predict(test_data)

학습한 모델이 test_data를 넣었을 때 예측한 답이 test_label에 담김.

test_label
// array([0, 0, 0, 1])
# 결과 검증
print(test_data, '의 예측 결과: ', test_label)
// [[0, 0], [1, 0], [0, 1], [1, 1]] 의 예측 결과:  [0 0 0 1]
print('정답률: ', accuracy_score([0,0,0,1], test_label))
// 정답률:  1.0

3. Iris DataSet

 

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

아이리스 데이터셋(Iris dataset)은 머신러닝과 통계학에서 가장 유명하고 자주 사용되는 데이터셋 중 하나입니다. 이 데이터셋은 세 종류의 붓꽃(Iris)에 대한 측정값을 포함하고 있으며, 각 붓꽃은 50개의 샘플로 구성되어 있습니다. 꽃받침 길이, 꽃받침 폭, 꽃잎 길이, 꽃잎 폭에 따라 세가지 종류 중 하나에 속합니다.

  1. Setosa(세토사): 50개의 샘플
  2. Versicolor(버시칼라): 50개의 샘플
  3. Virginica(버지니카): 50개의 샘플

꽃받침 길이, 꽃받침 폭, 꽃잎 길이, 꽃잎 폭은 독립변수가 되며, 꽃의 종류가 종속 변수가 됩니다.

{'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]),

data -> 독립변수 / target -> 종속변수

from sklearn.datasets import load_iris
iris = load_iris()
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
                
    :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 ...

 

iris['DESCR']는 Iris 데이터셋에 대한 간략한 설명(Description)을 담고 있는 문자열입니다. 이 문자열은 데이터셋의 특징, 클래스, 속성 등에 대한 정보를 제공합니다.

  1. 데이터셋에 대한 개요: 데이터셋이 어떤 정보를 담고 있는지에 대한 간략한 개요.
  2. 특징 변수(Features)에 대한 설명: 각각의 특징 변수가 어떤 의미를 가지고 있는지에 대한 설명.
  3. 클래스(종속 변수)에 대한 설명: 각각의 클래스가 어떤 의미를 가지고 있는지에 대한 설명.
  4. 데이터의 출처 및 기타 정보: 데이터셋에 대한 출처, 데이터 수, 속성의 수 등과 같은 기본적인 정보.
data = iris['data']

data에 독립변수'data'부분만 담아주기

feature_names = iris['feature_names']

feature_names
['sepal length (cm)',
 'sepal width (cm)',
 'petal length (cm)',
 'petal width (cm)']

 

데이터 가공을 위해서는 데이터 프레임으로 변경해주는 것이 좋기 때문에 pandas를 사용합니다.

import pandas as pd

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

target = iris['target']
df_iris['target'] = target

from sklearn.model_selection import train_test_split

✔️실무에서는 train, valied, test 세가지의 데이터로 나누게 됩니다.

예제는 데이터가 충분히 많지 않고, 공부를 하는 동안에는 train과 test 두가지의 데이터로 나누겠습니다.

⭐ train_test_split(독립변수, 종속변수, 테스트 사이즈, 시드값...)

train_test_split 함수를 사용할 때 테스트 사이즈(test size)는 데이터를 얼마나 분리할지를 결정하는 중요한 매개변수 중 하나입니다. 일반적으로 이 값을 0.2 또는 0.25로 설정하는 경우가 많습니다. 하지만 이 값은 상황에 따라 다를 수 있습니다.

일반적으로 데이터셋이 큰 경우에는 오버피팅 문제를 방지하기 위해 학습데이터를 줄이고 테스트 크기를 상대적으로 크게 설정합니다.

시드값을 설정하면 동일한 시드값을 가진 경우에는 항상 동일한 무작위 섞기 결과를 얻을 수 있습니다. 이는 실험의 재현성을 위해 중요할 수 있습니다. 섞기가 달라지면 다른 변수를 두고 실험을 진행할 때, 달라진 변수의 영향인지 무작위로 섞인 값이 달라져서 영향을 받은 것인지 알기 어렵기 때문입니다. 시드는 아무 숫자나 지정해도 괜찮습니다.

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)
X_train.shape, X_test.shape
// ((120, 4), (30, 4))

y_train.shape, y_test.shape
// ((120,), (30,))
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

svc = SVC()
svc.fit(X_train, y_train)

학습완료

y_pred = svc.predict(X_test)
print('정답률', accuracy_score(y_test, y_pred))
// 정답률 1.0

100% 다 맞춤

 

새로운 데이터를 만들어서 예측해보았을 때.

y_pred = svc.predict([[6.4,2.6,5.1,1.9]]) # 2에 거의 비슷한 값을 넣어봄
y_pred
// array([2])

'AI' 카테고리의 다른 글

로지스틱 회귀  (0) 2023.12.27
의사 결정 나무(자전거 대여 예제)  (0) 2023.12.26
선형 회귀(랜트비 예측)  (1) 2023.12.26
타이타닉 데이터셋  (0) 2023.12.26
머신러닝과 딥러닝  (0) 2023.12.14