高斯混合模型sklearn實(shí)現(xiàn)

高斯混合

class sklearn.mixture.GaussianMixture(n_components=1, covariance_type='full', tol=0.001, reg_covar=1e-06, max_iter=100,
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)

  1. n_components: 混合高斯模型個(gè)數(shù)锅尘,默認(rèn)為 1
  2. covariance_type: 協(xié)方差類型检诗,包括 {‘full’,‘tied’, ‘diag’, ‘spherical’} 四種,full 指每個(gè)分量有各自不同的標(biāo)準(zhǔn)協(xié)方差矩陣,完全協(xié)方差矩陣(元素都不為零), tied 指所有分量有相同的標(biāo)準(zhǔn)協(xié)方差矩陣(HMM 會(huì)用到),diag 指每個(gè)分量有各自不同對(duì)角協(xié)方差矩陣(非對(duì)角為零,對(duì)角不為零), spherical 指每個(gè)分量有各自不同的簡(jiǎn)單協(xié)方差矩陣涂身,球面協(xié)方差矩陣(非對(duì)角為零,對(duì)角完全相同搓蚪,球面特性)蛤售,默認(rèn)‘full’ 完全協(xié)方差矩陣
  3. tol:EM 迭代停止閾值,默認(rèn)為 1e-3.
  4. reg_covar: 協(xié)方差對(duì)角非負(fù)正則化妒潭,保證協(xié)方差矩陣均為正悴能,默認(rèn)為 0
  5. max_iter: 最大迭代次數(shù),默認(rèn) 100
  6. n_init: 初始化次數(shù)雳灾,用于產(chǎn)生最佳初始參數(shù)漠酿,默認(rèn)為 1
  7. init_params: {‘kmeans’, ‘random’}, defaults to ‘kmeans’. 初始化參數(shù)實(shí)現(xiàn)方式,默認(rèn)用 kmeans 實(shí)現(xiàn)谎亩,也可以選擇隨機(jī)產(chǎn)生
  8. weights_init: 各組成模型的先驗(yàn)權(quán)重炒嘲,可以自己設(shè)宇姚,默認(rèn)按照 7 產(chǎn)生
  9. means_init: 初始化均值,同 8
  10. precisions_init: 初始化精確度(模型個(gè)數(shù)夫凸,特征個(gè)數(shù))浑劳,默認(rèn)按照 7 實(shí)現(xiàn)
  11. random_state : 隨機(jī)數(shù)發(fā)生器
  12. warm_start : 若為 True,則 fit()調(diào)用會(huì)以上一次 fit()的結(jié)果作為初始化參數(shù)夭拌,適合相同問題多次 fit 的情況魔熏,能加速收斂,默認(rèn)為 False鸽扁。
  13. verbose : 使能迭代信息顯示道逗,默認(rèn)為 0,可以為 1 或者大于 1(顯示的信息不同)
  14. verbose_interval : 與 13 掛鉤献烦,若使能迭代信息顯示,設(shè)置多少次迭代后顯示信息卖词,默認(rèn) 10 次巩那。

參考代碼

import matplotlib as mpl
import matplotlib.pyplot as plt

import numpy as np

from sklearn import datasets
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import StratifiedKFold

print(__doc__)

colors = ['navy', 'turquoise', 'darkorange']


def make_ellipses(gmm, ax):
    for n, color in enumerate(colors):
        if gmm.covariance_type == 'full':
            covariances = gmm.covariances_[n][:2, :2]
        elif gmm.covariance_type == 'tied':
            covariances = gmm.covariances_[:2, :2]
        elif gmm.covariance_type == 'diag':
            covariances = np.diag(gmm.covariances_[n][:2])
        elif gmm.covariance_type == 'spherical':
            covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[n]
        v, w = np.linalg.eigh(covariances)
        u = w[0] / np.linalg.norm(w[0])
        angle = np.arctan2(u[1], u[0])
        angle = 180 * angle / np.pi  # convert to degrees
        v = 2. * np.sqrt(2.) * np.sqrt(v)
        ell = mpl.patches.Ellipse(gmm.means_[n, :2], v[0], v[1],
                                  180 + angle, color=color)
        ell.set_clip_box(ax.bbox)
        ell.set_alpha(0.5)
        ax.add_artist(ell)
        ax.set_aspect('equal', 'datalim')

iris = datasets.load_iris()

# Break up the dataset into non-overlapping training (75%) and testing
# (25%) sets.
skf = StratifiedKFold(n_splits=4)
# Only take the first fold.
train_index, test_index = next(iter(skf.split(iris.data, iris.target)))


X_train = iris.data[train_index]
y_train = iris.target[train_index]
X_test = iris.data[test_index]
y_test = iris.target[test_index]

n_classes = len(np.unique(y_train))

# Try GMMs using different types of covariances.
# print(n_classes)
estimators = {cov_type: GaussianMixture(n_components=n_classes,
              covariance_type=cov_type, max_iter=20, random_state=0)
              for cov_type in ['spherical', 'diag', 'tied', 'full']}

n_estimators = len(estimators)

plt.figure(figsize=(3 * n_estimators // 2, 6))
plt.subplots_adjust(bottom=.01, top=0.95, hspace=.15, wspace=.05,
                    left=.01, right=.99)


for index, (name, estimator) in enumerate(estimators.items()):
    # Since we have class labels for the training data, we can
    # initialize the GMM parameters in a supervised manner.
    estimator.means_init = np.array([X_train[y_train == i].mean(axis=0)
                                    for i in range(n_classes)])

    # Train the other parameters using the EM algorithm.
    estimator.fit(X_train)

    h = plt.subplot(2, n_estimators // 2, index + 1)
    make_ellipses(estimator, h)

    for n, color in enumerate(colors):
        data = iris.data[iris.target == n]
        plt.scatter(data[:, 0], data[:, 1], s=0.8, color=color,
                    label=iris.target_names[n])
    # Plot the test data with crosses
    for n, color in enumerate(colors):
        data = X_test[y_test == n]
        plt.scatter(data[:, 0], data[:, 1], marker='x', color=color)

    y_train_pred = estimator.predict(X_train)
    train_accuracy = np.mean(y_train_pred.ravel() == y_train.ravel()) * 100
    plt.text(0.05, 0.9, 'Train accuracy: %.1f' % train_accuracy,
             transform=h.transAxes)

    y_test_pred = estimator.predict(X_test)
    test_accuracy = np.mean(y_test_pred.ravel() == y_test.ravel()) * 100
    plt.text(0.05, 0.8, 'Test accuracy: %.1f' % test_accuracy,
             transform=h.transAxes)

    plt.xticks(())
    plt.yticks(())
    plt.title(name)

plt.legend(scatterpoints=1, loc='lower right', prop=dict(size=12))


plt.show()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市此蜈,隨后出現(xiàn)的幾起案子即横,更是在濱河造成了極大的恐慌,老刑警劉巖裆赵,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件东囚,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡战授,警方通過查閱死者的電腦和手機(jī)页藻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來植兰,“玉大人份帐,你說我怎么就攤上這事¢沟迹” “怎么了废境?”我有些...
    開封第一講書人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長筒繁。 經(jīng)常有香客問我噩凹,道長,這世上最難降的妖魔是什么毡咏? 我笑而不...
    開封第一講書人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任驮宴,我火速辦了婚禮,結(jié)果婚禮上呕缭,老公的妹妹穿的比我還像新娘幻赚。我一直安慰自己禀忆,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開白布落恼。 她就那樣靜靜地躺著箩退,像睡著了一般。 火紅的嫁衣襯著肌膚如雪佳谦。 梳的紋絲不亂的頭發(fā)上戴涝,一...
    開封第一講書人閱讀 51,598評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音钻蔑,去河邊找鬼啥刻。 笑死,一個(gè)胖子當(dāng)著我的面吹牛咪笑,可吹牛的內(nèi)容都是我干的可帽。 我是一名探鬼主播,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼窗怒,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼映跟!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起扬虚,我...
    開封第一講書人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤努隙,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后辜昵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體荸镊,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年堪置,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了躬存。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡舀锨,死狀恐怖优构,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情雁竞,我是刑警寧澤钦椭,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站碑诉,受9級(jí)特大地震影響彪腔,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望臼勉。 院中可真熱鬧漠另,春花似錦格嗅、人聲如沸番挺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽玄柏。三九已至,卻和暖如春贴铜,著一層夾襖步出監(jiān)牢的瞬間粪摘,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來泰國打工绍坝, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留徘意,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓轩褐,卻偏偏與公主長得像椎咧,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子把介,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容