소개
이 실습에서는 scikit-learn 의 BayesianGaussianMixture 클래스를 사용하여 세 개의 가우시안 혼합으로 구성된 예제 데이터 세트를 맞추는 방법을 보여줍니다. 이 클래스는 weight_concentration_prior_type 매개변수를 사용하여 농도 사전 (prior) 을 지정하여 자동으로 혼합 구성 요소의 수를 조정할 수 있습니다. 이 실습에서는 0 이 아닌 가중치를 가진 구성 요소의 수를 선택하기 위해 디리클레 분포 사전과 디리클레 프로세스 사전을 사용하는 차이점을 보여줍니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근할 수 있습니다.
때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.
학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.
라이브러리 가져오기
이 단계에서는 필요한 라이브러리인 numpy, matplotlib, gridspec 및 sklearn.mixture에서 BayesianGaussianMixture를 가져옵니다.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from sklearn.mixture import BayesianGaussianMixture
함수 정의
이 단계에서는 두 개의 함수를 정의합니다. 첫 번째 함수는 BayesianGaussianMixture 클래스 모델로 맞춘 예제 데이터 세트에서 얻은 타원을 플롯합니다. 두 번째 함수는 가중치 농도 사전의 세 가지 다른 값에 대한 결과를 플롯합니다.
def plot_ellipses(ax, weights, means, covars):
for n in range(means.shape[0]):
eig_vals, eig_vecs = np.linalg.eigh(covars[n])
unit_eig_vec = eig_vecs[0] / np.linalg.norm(eig_vecs[0])
angle = np.arctan2(unit_eig_vec[1], unit_eig_vec[0])
angle = 180 * angle / np.pi
eig_vals = 2 * np.sqrt(2) * np.sqrt(eig_vals)
ell = mpl.patches.Ellipse(
means[n], eig_vals[0], eig_vals[1], angle=180 + angle, edgecolor="black"
)
ell.set_clip_box(ax.bbox)
ell.set_alpha(weights[n])
ell.set_facecolor("#56B4E9")
ax.add_artist(ell)
def plot_results(ax1, ax2, estimator, X, y, title, plot_title=False):
ax1.set_title(title)
ax1.scatter(X[:, 0], X[:, 1], s=5, marker="o", color=colors[y], alpha=0.8)
ax1.set_xlim(-2.0, 2.0)
ax1.set_ylim(-3.0, 3.0)
ax1.set_xticks(())
ax1.set_yticks(())
plot_ellipses(ax1, estimator.weights_, estimator.means_, estimator.covariances_)
ax2.get_xaxis().set_tick_params(direction="out")
ax2.yaxis.grid(True, alpha=0.7)
for k, w in enumerate(estimator.weights_):
ax2.bar(
k,
w,
width=0.9,
color="#56B4E9",
zorder=3,
align="center",
edgecolor="black",
)
ax2.text(k, w + 0.007, "%.1f%%" % (w * 100.0), horizontalalignment="center")
ax2.set_xlim(-0.6, 2 * n_components - 0.4)
ax2.set_ylim(0.0, 1.1)
ax2.tick_params(axis="y", which="both", left=False, right=False, labelleft=False)
ax2.tick_params(axis="x", which="both", top=False)
if plot_title:
ax1.set_ylabel("추정된 혼합")
ax2.set_ylabel("각 구성 요소의 가중치")
예제 데이터셋 매개변수 설정
이 단계에서는 예제 데이터셋의 매개변수를 설정합니다. 이 매개변수에는 난수 상태, 구성 요소 수, 특징 수, 색상, 공분산 행렬, 샘플 수 및 평균값이 포함됩니다.
random_state, n_components, n_features = 2, 3, 2
colors = np.array(["#0072B2", "#F0E442", "#D55E00"])
covars = np.array(
[[[0.7, 0.0], [0.0, 0.1]], [[0.5, 0.0], [0.0, 0.1]], [[0.5, 0.0], [0.0, 0.1]]]
)
samples = np.array([200, 500, 200])
means = np.array([[0.0, -0.70], [0.0, 0.0], [0.0, 0.70]])
추정기 정의
이 단계에서는 두 개의 추정기를 정의합니다. 첫 번째 추정기는 Dirichlet 분포 사전을 사용하여 0 이 아닌 가중치를 갖는 구성 요소의 수를 설정합니다. 두 번째 추정기는 Dirichlet 과정 사전을 사용하여 구성 요소의 수를 선택합니다.
estimators = [
(
"Dirichlet 분포 사전을 사용한 유한 혼합\n및 " r"$\gamma_0=$",
BayesianGaussianMixture(
weight_concentration_prior_type="dirichlet_distribution",
n_components=2 * n_components,
reg_covar=0,
init_params="random",
max_iter=1500,
mean_precision_prior=0.8,
random_state=random_state,
),
[0.001, 1, 1000],
),
(
"Dirichlet 과정 사전을 사용한 무한 혼합\n및" r"$\gamma_0=$",
BayesianGaussianMixture(
weight_concentration_prior_type="dirichlet_process",
n_components=2 * n_components,
reg_covar=0,
init_params="random",
max_iter=1500,
mean_precision_prior=0.8,
random_state=random_state,
),
[1, 1000, 100000],
),
]
데이터 생성
이 단계에서는 numpy.random.RandomState 함수와 3 단계에서 정의된 매개변수를 사용하여 데이터를 생성합니다.
rng = np.random.RandomState(random_state)
X = np.vstack(
[
rng.multivariate_normal(means[j], covars[j], samples[j])
for j in range(n_components)
]
)
y = np.concatenate([np.full(samples[j], j, dtype=int) for j in range(n_components)])
결과 플롯
이 단계에서는 2 단계에서 정의된 plot_results 함수를 사용하여 각 추정기의 결과를 플롯합니다.
for title, estimator, concentrations_prior in estimators:
plt.figure(figsize=(4.7 * 3, 8))
plt.subplots_adjust(
bottom=0.04, top=0.90, hspace=0.05, wspace=0.05, left=0.03, right=0.99
)
gs = gridspec.GridSpec(3, len(concentrations_prior))
for k, concentration in enumerate(concentrations_prior):
estimator.weight_concentration_prior = concentration
estimator.fit(X)
plot_results(
plt.subplot(gs[0:2, k]),
plt.subplot(gs[2, k]),
estimator,
X,
y,
r"%s$%.1e$" % (title, concentration),
plot_title=k == 0,
)
plt.show()
요약
이 실험에서는 scikit-learn 의 BayesianGaussianMixture 클래스를 사용하여 세 개의 가우시안 혼합으로 구성된 예제 데이터 세트를 맞추는 방법을 보여줍니다. 이 클래스는 weight_concentration_prior_type 매개변수를 사용하여 농도 사전 (prior) 을 지정하여 자동으로 혼합 구성 요소의 수를 조정할 수 있습니다. 이 실험에서는 0 이 아닌 가중치를 가진 구성 요소의 수를 선택하기 위해 디리클 분포 사전과 디리클 프로세스 사전을 사용하는 차이점을 보여줍니다.