AI/머신러닝

[머신러닝] 사이킷런(Sciket-learn)

caramel-bottle 2023. 12. 21.

사이킷런

사이킷런은 대표적인 파이썬 머신러닝 모듈이다. 지도학습(Supervised Leraning)과 비지도학습(Unsupervised Learning)의 다양한 알고리즘을 사용할 수 있고, 머신러닝 결과를 검증하는 기능또한 제공한다. 샘플 데이터도 사용할 수 있고 무료이기 때문에 굉장히 유용하다.

 

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

 

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


LinearSVC

LinearSVC는 Linear Support Vector Classification이다.

클래스를 구분으로 하는 분류 문제에서 각 클래스를 잘 구분하는 선을 그려주는 방식을 사용하는 알고리즘이다.

지도학습 알고리즘을 사용하는 학습 전용 데이터와 결과 전용 데이터를 모두 가지고 있어야 사용이 가능하다.

 

SVC를 사용하여 모델을 학습시키고 학습이 잘 되었는지 검증까지 간단하게 구현해보자.

 

모듈

from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score

 

LinearSVC는 SVM의 구현 방법 중 하나이다.

accuracy_score는 모델의 정답률을 보여주는 모듈이다.


학습 데이터 준비

# 학습 데이터 준비
learn_data = [[0, 0], [1, 0], [0, 1], [1, 1]]   # 독립변수
learn_label = [0, 0, 0, 1]  # 종속변수

 

지도학습(Supervised Learning)은 독립변수와 종속변수를 필요로 한다. 각각의 독립변수에 해당하는 종속변수를 매칭하여 준비한다.

and 연산을 예시로 하였다.


모델 객체 생성

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

학습

# 학습
svc.fit(learn_data, learn_label)

 

LinearSVC의 fit 메서드는 X, y를 매개변수로 갖는다. 아래는 공식 문서의 fit()메서드 설명이다.

"""Fit the model according to the given training data.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
    Training vector, where `n_samples` is the number of samples and
    `n_features` is the number of features.

y : array-like of shape (n_samples,)
    Target vector relative to X.

sample_weight : array-like of shape (n_samples,), default=None
    Array of weights that are assigned to individual
    samples. If not provided,
    then each sample is given unit weight.

    .. versionadded:: 0.18

Returns
-------
self : object
    An instance of the estimator.
"""

검증 데이터 준비

# 검증 데이터 준비
test_data = [[0, 0], [0, 1], [1, 0], [1, 1]]

 

이제 모델에게 시험문제를 제출해보자. 잘 학습이 되었다면 모든 문제를 맞출 것이다.


예측

# 예측
test_label = svc.predict(test_data)
test_label
array([0, 0, 0, 1])

 

눈으로 보일만한 예시 데이터이기 때문에 정답과 일치하는 것을 볼 수 있다.


결과 검증

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

 

accuracy_score 함수를 사용하여 정답을 얼마나 잘 맞췄는지 확인할 수 있다.

 

댓글