Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Data Visualization
- Python
- Train-Test Split
- 통계물리학
- GMM
- confusion matrix
- scatter()
- scikit-learn
- 김범준교수
- iris데이터
- 과학서적
- 군집분석
- pyplot
- logistic regression
Archives
- Today
- Total
Basin of Attraction
iris데이터를 gaussian mixture모형을 이용한 군집화 본문
이번 예제에서는 scikit-learn의 Gaussian Mixture Model (GMM)을 사용하여 iris 데이터셋을 군집화하는 방법을 살펴보겠습니다. Gaussian Mixture Model은 데이터가 여러 개의 가우시안 분포에서 생성되었다고 가정하는 모델로, 데이터를 여러 개의 클러스터로 분리할 수 있습니다.
우선, 필요한 라이브러리를 가져옵니다.
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.mixture import GaussianMixture
다음으로, iris 데이터셋을 로드합니다.
iris = datasets.load_iris()
X = iris.data
Gaussian Mixture Model을 사용하기 전에, 적절한 클러스터 수를 결정해야합니다. 여기서는 Bayesian Information Criterion (BIC)를 사용하여 최적의 클러스터 수를 결정합니다.
lowest_bic = np.infty
bic = []
n_components_range = range(1, 7)
for n_components in n_components_range:
gmm = GaussianMixture(n_components=n_components)
gmm.fit(X)
bic.append(gmm.bic(X))
if bic[-1] < lowest_bic:
lowest_bic = bic[-1]
best_gmm = gmm
위 코드에서는 1부터 6까지의 클러스터 수에서 Gaussian Mixture Model을 학습하고, BIC를 사용하여 각 모델의 성능을 측정합니다. 최적의 클러스터 수는 BIC가 가장 작은 모델로 결정됩니다.
최적의 모델을 사용하여 iris 데이터를 군집화하고 결과를 시각화할 수 있습니다.
gmm = best_gmm
labels = gmm.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='viridis');
plt.show()
위 코드에서는 2차원 특성 공간에서 각 데이터 포인트를 색으로 나타내어 시각화합니다.
전체 코드는 다음과 같습니다.
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.mixture import GaussianMixture
# iris 데이터 로드
iris = datasets.load_iris()
X = iris.data
# 최적의 클러스터 수 결정
lowest_bic = np.infty
bic = []
n_components_range = range(1, 7)
for n_components in n_components_range:
gmm = GaussianMixture(n_components=n_components)
gmm.fit(X)
bic.append(gmm.bic(X))
if bic[-1] < lowest_bic:
lowest_bic = bic[-1]
best_gmm = gmm
# 군집화
gmm = best_gmm
labels = gmm.predict(X)
# 시각화
plt.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='viridis');
plt.show()
반응형
Comments