模型原型
sklearn.mixture.GaussianMixture(n_components=1,covariance_type=’full’,tol=0.001,reg_covar=1e-06, max_iter=300,n_init=1, init_params=’kmeans’,weights_init=None,means_init=None,precisions_init=None,random_state=None,warm_start=False,verbose=0, verbose_interval=10)
参数
- n_components:指定分模型的数量(默认为1)
- covariance_type:指定协方差的类型
- ’spherical’:球状型,每个分模型的协方差矩阵都是一个标量值
- ‘tied’:结点型,所有分模型都共享一个协方差矩阵
- ‘diag’:对角型,每个分模型的协方差矩阵都是对角矩阵
- ‘full’:全型,每个分模型都有自己的协方差矩阵
- tol
- reg_covar:添加到协方差矩阵对角线上元素,确保所有的协方差都是正数
- max_iter
- n_init:指定初始化次数
- init_params:可以为’kmeans’/’random’,用于指定初始化权重的策略
- weights_init:一个序列,形状为(n_components,)指定初始化的权重
- means_init:形状为(n_components,n_features),指定初始化的权重
- precisions_init:用户提供的初始precisions(协方差矩阵的逆矩阵),根据covariance_type的不同,该参数值的形状不同
- random_state
- warm_start
- verbose
- verbose_interval:指定输出日志的间隔
属性
- wights_:形状为(n_components,),该属性存储了每个分模型的权重
- means_:形状为(n_components,n_features),该属性存储了每个分模型的均值
方法
- fit(X[,y])
- fit_predict(X[,y])
- predict(X)
- prodict_proba(X):预测样本所属各个簇的概率
- sample([n_samples,random_state]):根据模型来随机生成一组样本
- score(X,[,y]):计算模型在样本总体上的对数似然函数
- score_samples(X):给出每个样本的对数似然函数
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_blobs
from sklearn import cluster
from sklearn.metrics import adjusted_rand_score
from sklearn import mixture
产生数据
def create_data(centers,num=100,std=0.7):
X,labels_true=make_blobs(n_samples=num,centers=centers,cluster_std=std)
return X,labels_true
查看生成的样本点
def plot_data(*data):
X,labels_true=data
labels=np.unique(labels_true)
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
colors='rgbyckm'
for i,label in enumerate(labels):
position=labels_true==label
ax.scatter(X[position,0],X[position,1],label='cluster %d'%label,color=colors[i%len(colors)])
ax.legend(loc='best',framealpha=0.5)
ax.set_xlabel('X[0]')
ax.set_ylabel('Y[1]')
ax.set_title('data')
plt.show()
X,labels_true=create_data([[1,1],[2,2],[1,2],[10,20]],1000,0.5)
plot_data(X,labels_true)
使用GMM
def test_GMM(*data):
X,labels_true=data
clst=mixture.GaussianMixture()
clst.fit(X)
predicted_labels=clst.predict(X)
print('ARI:%s'%adjusted_rand_score(labels_true,predicted_labels))
centers=[[1,1],[2,2],[1,2],[10,20]]
X,labels_true=create_data(centers,1000,0.5)
test_GMM(X,labels_true)
簇的数量的影响
def test_GMM_n_components(*data):
X,labels_true=data
nums=range(1,50)
ARIs=[]
for num in nums:
clst=mixture.GaussianMixture(n_components=num)
clst.fit(X)
predicted_labels=clst.predict(X)
ARIs.append(adjusted_rand_score(labels_true,predicted_labels))
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(nums,ARIs,marker='+')
ax.set_xlabel('n_components')
ax.set_ylabel('ARI')
fig.suptitle('GMM')
plt.show()
test_GMM_n_components(X,labels_true)
协方差类型的影响
def test_GMM_cov_type(*data):
X,labels_true=data
nums=range(1,50)
cov_types=['spherical','tied','diag','full']
markers='+o*s'
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
for i,cov_type in enumerate(cov_types):
ARIs=[]
for num in nums:
clst=mixture.GaussianMixture(n_components=num,covariance_type=cov_type)
clst.fit(X)
predicted_labels=clst.predict(X)
ARIs.append(adjusted_rand_score(labels_true,predicted_labels))
ax.plot(nums,ARIs,marker=markers[i],label='covariance_type:%s'%cov_type)
ax.set_xlabel('n_components')
ax.legend(loc='best')
ax.set_ylabel("ARI")
fig.suptitle('GMM')
plt.show()
test_GMM_cov_type(X,labels_true)