日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【机器学习】Kmeans聚类

發(fā)布時(shí)間:2024/1/23 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【机器学习】Kmeans聚类 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

寫在篇前

??Kmeans算法是一種經(jīng)典的聚類算法,屬于無(wú)監(jiān)督學(xué)習(xí)的范疇。所謂聚類,即指對(duì)于給定的一個(gè)樣本集,按照樣本之間的距離大小,將樣本集劃分為K個(gè)簇,且讓簇內(nèi)的點(diǎn)盡量緊密的連在一起,而讓簇間的距離盡量的大。

優(yōu)點(diǎn):

  • 原理簡(jiǎn)單
  • 速度快
  • 對(duì)大數(shù)據(jù)集有比較好的伸縮性

缺點(diǎn):

  • 需要指定聚類數(shù)量K
  • 對(duì)異常值敏感
  • 對(duì)初始值敏感

原理概述

算法流程

?????????????????????????以下描述基于 Lloyd’s 算法

  • 設(shè)定一個(gè)k值,即設(shè)定需要聚類多少個(gè)簇
  • 隨機(jī)選擇k個(gè)質(zhì)心(centroids)
  • 計(jì)算各個(gè)樣本點(diǎn)到質(zhì)心的距離,劃分簇
  • 重復(fù)第2、3步驟,直至迭代次數(shù)達(dá)到設(shè)定的最大值或者質(zhì)心不再移動(dòng)
  • 評(píng)價(jià)準(zhǔn)則

    ??The k-means algorithm divides a set of N samples X into K disjoint clusters C, each described by the mean μj\mu_jμj? of the samples in the cluster. The means are commonly called the cluster “centroids”; note that they are not, in general, points from X, although they live in the same space. The K-means algorithm aims to choose centroids that minimise the inertia, or within-cluster sum of squared criterion:
    E=∑i=1k∑x∈Ci∣∣x?μi∣∣22E = \sum\limits_{i=1}^k\sum\limits_{x \in C_i} ||x-\mu_i||_2^2 E=i=1k?xCi??x?μi?22?
    attention, μj\mu_jμj? is just the so-called centroids:
    μi=1∣Ci∣∑x∈Cix\mu_i = \frac{1}{|C_i|}\sum\limits_{x \in C_i}x μi?=Ci?1?xCi??x

    ??值得注意的是:

    • Inertia假設(shè)聚類是凸的和各向同性的(convex and isotropic),但它對(duì)細(xì)長(zhǎng)簇或具有不規(guī)則形狀數(shù)據(jù)聚類不佳;

    • Inertia不是標(biāo)準(zhǔn)化的度量標(biāo)準(zhǔn):我們只知道較低的值更好,零是最佳的;

    算法改進(jìn)

    Kmeans ++

    ?

    ??k個(gè)初始化的質(zhì)心的位置選擇對(duì)最后的聚類結(jié)果和運(yùn)行時(shí)間都有很大的影響,因此需要選擇合適的k個(gè)質(zhì)心。K-Means++算法就是對(duì)K-Means隨機(jī)初始化質(zhì)心的方法的優(yōu)化:

    • 從輸入的數(shù)據(jù)點(diǎn)集合中隨機(jī)選擇一個(gè)點(diǎn)作為第一個(gè)聚類中心\mu_1

    • 對(duì)于數(shù)據(jù)集中的每一個(gè)點(diǎn)x_i,計(jì)算它與已選擇的聚類中心中最近聚類中心的距離
      D(xi)=arg  min∣∣xi?μr∣∣22    r=1,2,...kselectedD(x_i) = arg\;min||x_i- \mu_r||2^2\;\;r=1,2,...k{selected} D(xi?)=argminxi??μr?22r=1,2,...kselected

    • 選擇一個(gè)新的數(shù)據(jù)點(diǎn)作為新的聚類中心,選擇的原則是:D(x)較大的點(diǎn),被選取作為聚類中心的概率較大

    • 重復(fù)b和c直到選擇出k個(gè)聚類質(zhì)心

    • 利用這k個(gè)質(zhì)心來(lái)作為初始化質(zhì)心去運(yùn)行標(biāo)準(zhǔn)的K-Means算法

      ?

    elkan

    ?

    ??在傳統(tǒng)的K-Means算法中,我們?cè)诿枯喌鷷r(shí),要計(jì)算所有的樣本點(diǎn)到所有的質(zhì)心的距離,這樣會(huì)比較的耗時(shí)。elkan K-Means算法就是從這塊入手加以改進(jìn)。它的目標(biāo)是減少不必要的距離的計(jì)算。elkan K-Means利用了兩邊之和大于等于第三邊,以及兩邊之差小于第三邊的三角形性質(zhì),來(lái)減少距離的計(jì)算。利用上邊的兩個(gè)規(guī)律,elkan K-Means比起傳統(tǒng)的K-Means迭代速度有很大的提高。但是如果我們的樣本的特征是稀疏的,有缺失值的話,這個(gè)方法就不使用了,此時(shí)某些距離無(wú)法計(jì)算,則不能使用該算法。

    ?

    mini-batch

    ?

    ?MiniBatch-KMeans是KMeans算法的一種變體,它使用mini-batch來(lái)減少計(jì)算時(shí)間,同時(shí)仍試圖優(yōu)化相同的目標(biāo)函數(shù)。mini-batch是輸入數(shù)據(jù)集的子集,在每次訓(xùn)練迭代中隨機(jī)采樣。它大大減少收斂到局部最優(yōu)值所需的計(jì)算量,并達(dá)到大致相同的效果。

    算法實(shí)現(xiàn)

    ??在本篇主要借助sklearn包提供的接口來(lái)實(shí)現(xiàn)kmeans算法,具體的實(shí)現(xiàn)當(dāng)然我們可以直接看源碼啦~首先看一下構(gòu)造函數(shù):

    def __init__(self,n_clusters=8, # 即理論部分的k值init='k-means++', # 質(zhì)心初始化方法n_init=10, # 質(zhì)心初始化次數(shù),最后結(jié)果取結(jié)果最好的一個(gè)max_iter=300, # 最大迭代次數(shù)tol=1e-4, # 容忍度,即kmeans運(yùn)行準(zhǔn)則收斂的條件precompute_distances='auto', # 是否需要提前計(jì)算距離,并將其放入內(nèi)存verbose=0, # 冗長(zhǎng)模式,深入看源碼你會(huì)發(fā)現(xiàn)和操作系統(tǒng)底層有關(guān),個(gè)人認(rèn)為與算法本身無(wú)關(guān)random_state=None, # 實(shí)際上是種子,改參數(shù)會(huì)傳入check_random_state()函數(shù)copy_x=True, # 當(dāng)并行計(jì)算時(shí),必須為True,為數(shù)據(jù)建立copyn_jobs=1, # 并行計(jì)算進(jìn)程數(shù),-1時(shí)表示占滿cpualgorithm='auto' # ‘a(chǎn)uto’, ‘full’, ‘elkan’, 其中 'full’表示用EM方式實(shí)現(xiàn),即傳統(tǒng)的kmeans算法計(jì)算距離)

    ??上面這些參數(shù)可以一一對(duì)應(yīng)到上面講的理論部分,為了進(jìn)一步了解我們繼續(xù)深入,看看一個(gè)Kmeans對(duì)象有哪些屬性和方法,同樣直接看代碼:

    #! /usr/bin/python # _*_ coding: utf-8 _*_ __author__ = 'Jeffery'import numpy as np from sklearn.cluster import KMeansdata = np.random.rand(100, 3) # 生成一個(gè)隨機(jī)數(shù)據(jù),shape(100, 3) estimator = KMeans(n_clusters=3,init='k-means++',n_init=10,max_iter=300,tol=1e-4,precompute_distances='auto', verbose=0,random_state=None,copy_x=False,n_jobs=1,algorithm='auto') # 對(duì)于非稀疏數(shù)據(jù),會(huì)選擇elkan算法estimator.fit(data) # 聚類# --------------------屬性------------------------- # 獲取estimator構(gòu)造函數(shù)中設(shè)置的屬性 print('n_clusters:', estimator.n_clusters) print('init:', estimator.init) print('max_iter:', estimator.max_iter) print('tol:', estimator.tol) print('precompute_distances:', estimator.precompute_distances) print('verbose:', estimator.verbose) print('random_state:', estimator.random_state) print('copy_x:', estimator.copy_x) print('n_jobs:', estimator.n_jobs) print('algorithm:', estimator.algorithm) print('n_init:', estimator.n_init)# 其他重要屬性 print('n_iter_:', estimator.n_iter_) # 實(shí)際迭代次數(shù) print('cluster_centers_:', estimator.cluster_centers_) # 獲取聚類中心點(diǎn)結(jié)果 print('inertia_:', estimator.inertia_) # 獲取聚類準(zhǔn)則的總和,越小越好 print('labels_:', estimator.labels_) # 獲取聚類標(biāo)簽結(jié)果 # --------------------函數(shù)------------------------- print('get_params:', estimator.get_params(deep=True)) # 與set_params()相對(duì)# 這里的介紹先不講 fit()、transform()、fit_transform()、fit_predict()、predict()、score()等函數(shù) # 這些函數(shù)放在案例里面

    案例

    ??這個(gè)示例來(lái)源于官網(wǎng),這個(gè)示例旨在說(shuō)明k-means的一些不合適的場(chǎng)景:在前三個(gè)圖中,輸入數(shù)據(jù)不符合k-means所產(chǎn)生的一些隱含假設(shè),結(jié)果產(chǎn)生了不希望的聚類結(jié)果;在最后一個(gè)圖中,k-means返回直觀、合理的簇,盡管大小不均勻。這個(gè)示例很簡(jiǎn)單,但是一定要充分看到kmeans的應(yīng)用關(guān)鍵,比如k選取的重要性、聚類各向異性數(shù)據(jù)的局限性

    #! /usr/bin/python # _*_ coding: utf-8 _*_ __author__ = 'Jeffery' __date__ = '2018/11/11 13:55'import numpy as np import matplotlib.pyplot as pltfrom sklearn.cluster import KMeans from sklearn.datasets import make_blobsplt.figure(figsize=(12, 12))n_samples = 1500 random_state = 170 X, y = make_blobs(n_samples=n_samples, random_state=random_state)# Incorrect number of clusters y_pred = KMeans(n_clusters=2, random_state=random_state).fit_predict(X)plt.subplot(221) plt.scatter(X[:, 0], X[:, 1], c=y_pred) plt.title("Incorrect Number of Blobs")# Anisotropicly distributed data transformation = [[0.60834549, -0.63667341], [-0.40887718, 0.85253229]] X_aniso = np.dot(X, transformation) y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_aniso)plt.subplot(222) plt.scatter(X_aniso[:, 0], X_aniso[:, 1], c=y_pred) plt.title("Anisotropicly Distributed Blobs")# Different variance X_varied, y_varied = make_blobs(n_samples=n_samples,cluster_std=[1.0, 2.5, 0.5],random_state=random_state) y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X_varied)plt.subplot(223) plt.scatter(X_varied[:, 0], X_varied[:, 1], c=y_pred) plt.title("Unequal Variance")# Unevenly sized blobs X_filtered = np.vstack((X[y == 0][:500], X[y == 1][:100], X[y == 2][:10])) y_pred = KMeans(n_clusters=3,random_state=random_state).fit_predict(X_filtered)plt.subplot(224) plt.scatter(X_filtered[:, 0], X_filtered[:, 1], c=y_pred) plt.title("Unevenly Sized Blobs")plt.show()

    寫在篇后

    ??如果有足夠的時(shí)間,K-means將最終收斂,但這可能是局部最優(yōu)值,這很大程度上取決于質(zhì)心的初始化;另外,對(duì)于大數(shù)據(jù)集,可以先做PCA等降維處理(PCA請(qǐng)參考降維技術(shù)-PCA),然后再進(jìn)行聚類,以減少計(jì)算資源的消耗以及可能的提升聚類效果。

    總結(jié)

    以上是生活随笔為你收集整理的【机器学习】Kmeans聚类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。