k-means模型沒有對邊界附近的點的聚類分配的概率或者不確定性進行度量魁袜,顯得不夠通用嗅回。而且贝次,簇模型的形狀只能說圓形不夠靈活(橢圓形)绳军。k-means的兩個缺點:
- 類的形狀缺少靈活性暗膜。
- 缺少簇分配的概率匀奏。、
高斯混合模型(Gaussian mixture model学搜,GMM)使用多維高斯分布的混合對輸入數據進行建模娃善。predict_prob方法給出任意點屬于某個簇的概率论衍。
可以使用全協方差擬合數據。
rng = np.random.RandomState(13)
X_stretched = np.dot(X, rng.randn(2, 2))
gmm = GaussianMixture(n_components=4, covariance_type='full', random_state=42)
plot_gmm(gmm, X_stretched)
e919f0f24fc648dba7bad5a556dfbe10.png
GMM用作密度估計
GMM本質上是一個密度估計算法聚磺,是描述數據分布的生成概率模型坯台。
也就是說,GMM為我們提供了生成與輸入數據分布類似的新隨機數據的方法瘫寝。作為一種非常方便的建模方法蜒蕾,GMM可以為數據估計出任意維度的隨機分布。
使用赤池信息準則(Akaike information criterion焕阿,AIC)咪啡、貝葉斯信息準則(Bayesian information criterion, BIC)來找最優(yōu)的n_components暮屡。
from sklearn.datasets import make_moons
Xmoon, ymoon = make_moons(200, noise=.05, random_state=0)
plt.scatter(Xmoon[:, 0], Xmoon[:, 1]);
n_components = np.arange(1, 21)
models = [GaussianMixture(n, covariance_type='full', random_state=0).fit(Xmoon)
for n in n_components]
plt.figure()
plt.plot(n_components, [m.bic(Xmoon) for m in models], label='BIC')
plt.plot(n_components, [m.aic(Xmoon) for m in models], label='AIC')
plt.legend(loc='best')
plt.xlabel('n_components');
案例:使用GMM生成新的數據
使用標準手寫數字庫生成新的手寫數字撤摸。
- 使用PCA投影保留99.9%的方差,將維度從
維降到41維褒纲。
- 使用AIC估計GMM的成分數量准夷。
- 擬合數據,確認收斂莺掠,逆變換冕象。
from sklearn.datasets import load_digits
digits = load_digits()
print(digits.data.shape)
def plot_digits(data):
fig, ax = plt.subplots(10, 10, figsize=(8, 8),
subplot_kw=dict(xticks=[], yticks=[]))
fig.subplots_adjust(hspace=0.05, wspace=0.05)
for i, axi in enumerate(ax.flat):
im = axi.imshow(data[i].reshape(8, 8), cmap='binary')
im.set_clim(0, 16)
plot_digits(digits.data)
from sklearn.decomposition import PCA
pca = PCA(0.999,whiten=True)
data = pca.fit_transform(digits.data)
print(data.shape)
n_components = np.arange(50,210,10)
models = [GaussianMixture(n, covariance_type='full', random_state=0)
for n in n_components]
aics = [model.fit(data).aic(data) for model in models]
plt.figure()
plt.plot(n_components, aics);
gmm = GaussianMixture(110, covariance_type='full', random_state=0)
gmm.fit(data)
print(gmm.converged_)
data_new,_ = gmm.sample(100)
print(data_new.shape)
digits_new = pca.inverse_transform(data_new)
plot_digits(digits_new)
297f11323c204301b55d5419b02cfaa9.png
參考:
[1]美 萬托布拉斯 (VanderPlas, Jake).Python數據科學手冊[M].人民郵電出版社,2018.