1. 개념
가우시안 혼합 모델 Gausian Mixture Model 은 데이터의 분포가 가우시안인 경우 사용하는 혼합 모델이다. 데이터의 분포가 가우시안이다 = 정규분포다 라는거랜다. 왜 굳이 두가지 말을 쓰냐 해서 찾아봤는데 보통 공학에선 전자, 수학에선 후자로 말한다고 한다.. (참 나 찾아보기 전까지 어려운건줄 알고 긴장했잖아)
혼합 모델이라는건 데이터가 여러 구성 요소 분포에 의해 처리된다고 가정하는 확률밀도모델이다. 말이 되게 어려운데 예를들자면, 우리는 아시아 사람들의 쇼핑 스타일과 패턴을 알고 싶다고 가정하자. 이 때 나라를 기준으로 데이터를 쪼개 각각을 표현하는 모델을 만들고 그걸 어떻게 합쳐서 최종 모델을 만들면 국가별 특징과 대륙의 특징을 모두 살릴 수 있는 모델이 된다. 혼합 모델은 이런 경우 사용한다
중요한건 혼합모델은 반모수적 모델 (데이터가 정규분포가 아니거나 너무 적거나 독립적인 경우) 라는 거다. 생각해보면 간단하다. 이상치가 많거나 정규분포를 따르지 않는 요상한 분포의 데이터들의 정규분포 여러개를 합치면서 희소 데이터 때문에 발생하는 간격을 줄여준다. 그래서 함수가 정의되고 나면 반모수 모델이 모수 모델로 바뀌게 된다.
생성 원리 자체가 데이터가 여러 방식으로 결합된 것이기 때문에 이미지 데이터베이스 검색, 주식시장 변동 모델링, 생채 인식과 같이 이상치에 민감한 데이터셋에서 잘 응용되는 것 같다. 특히 마지막 데이터 분포를 시각화했을때 타원형으로 나오는 경우 이 모델을 쓰면 좋다
GMM 모델은 작동 원리처럼 이 가우시안 분포 여러개를 합쳐둔 수식으로 표현되는데, 여기서는 복잡한 수식은 생략하고 바로 응용해 보도록 하겠다.
*가우시안 분포? 통계 개념 알아 보기
2. 실습
2.1. 라이브러리 & 데이터셋 import &Train/Test split
iris 데이터셋을 이용했다
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
from sklearn import datasets
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import train_test_split
# Load the iris dataset
iris = datasets.load_iris()
X, y = datasets.load_iris(return_X_y=True)
# Split dataset into training and testing (80/20 split)
skf = StratifiedKFold(n_splits=5) #
skf.get_n_splits(X, y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
2.2. 타깃값 클라스 수 확인하기
이따 필요함 파라미터로 들어가요
# Extract the number of classes
num_classes = len(np.unique(y_train))
print(num_classes)
#out:3
2.3. 모델 만들기, 초기화시키기, 학습시키기
n components 로 3을 넣었다. 그 이유는 원래 쓴 데이터가 이미 분리된 라벨있는 데이터라서! 아쉽게도 이 모델 역시 초기 n 값을 정해줘야 한다는 한계가 따름. 그래서 실습땐 라벨링 된 데이터를 썼어요
# Build GMM
#n_components = 타깃의 구성 요소 수 (클라스 수)
#covariance_type = 공분산의 타입 지정
#init_params = 학습 중 업데이트하는 매개변수, k-means 를 이용하면 학습 중 가중치와 공분산이 업데이트됨
#max_iter = 훈현 중 기댓값 최대화 반복 횟수
classifier = GaussianMixture(n_components=num_classes, covariance_type='full',
init_params='kmeans', max_iter=20)
# Initialize the GMM means
classifier.means_ = np.array([X_train[y_train == i].mean(axis=0)
for i in range(num_classes)])
# Train the GMM classifier
classifier.fit(X_train)
2.4. 시각화
타원을 넣어서 시각화해봤다. 원치 않는다면 타원 부분 뺀 코드 쓰세요.. 타원 넣을라면 복잡해져.. 벡터 고유값 찾고 경계 정하고 어쩌구 저쩌구
# Draw boundaries
plt.figure()
colors = 'bgr'
for i, color in enumerate(colors):
# Extract eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eigh(
classifier.covariances_[i][:2, :2])
# Normalize the first eigenvector
norm_vec = eigenvectors[0] / np.linalg.norm(eigenvectors[0])
# Extract the angle of tilt
angle = np.arctan2(norm_vec[1], norm_vec[0])
angle = 180 * angle / np.pi
# Scaling factor to magnify the ellipses
# (random value chosen to suit our needs)
scaling_factor = 8
eigenvalues *= scaling_factor
# Draw the ellipse
ellipse = patches.Ellipse(classifier.means_[i, :2],
eigenvalues[0], eigenvalues[1], 180 + angle,
color=color)
axis_handle = plt.subplot(1, 1, 1)
ellipse.set_clip_box(axis_handle.bbox)
ellipse.set_alpha(0.6)
axis_handle.add_artist(ellipse)
# Plot the data
colors = 'bgr'
for i, color in enumerate(colors):
cur_data = iris.data[iris.target == i]
plt.scatter(cur_data[:,0], cur_data[:,1], marker='o',
facecolors='none', edgecolors='black', s=40, label=iris.target_names[i])
test_data = X_test[y_test == i]
plt.scatter(test_data[:,0], test_data[:,1], marker='s',
facecolors='black', edgecolors='black', s=40 ,label=iris.target_names[i])
# Compute predictions for training and testing data
y_train_pred = classifier.predict(X_train)
accuracy_training = np.mean(y_train_pred.ravel() == y_train.ravel()) * 100
print('Accuracy on training data =', accuracy_training)
y_test_pred = classifier.predict(X_test)
accuracy_testing = np.mean(y_test_pred.ravel() == y_test.ravel()) * 100
print('Accuracy on testing data =', accuracy_testing)
plt.title('GMM classifier')
plt.xticks(())
plt.yticks(())
plt.show()
'데이터 과학 Data Science > 비지도학습' 카테고리의 다른 글
계층적 클러스터링 (0) | 2022.10.18 |
---|---|
DBSCAN으로 클러스터링 (1) | 2022.10.04 |
유사도 전파 Affinity Propagation 모델로 클러스터링 (1) | 2022.09.20 |
평균 이동 알고리즘으로 데이터 클러스터링 (1) | 2022.09.19 |
k-means 알고리즘으로 패턴 찾고 평가까지 (0) | 2022.09.18 |