K-means聚類的Python實現

來源:互聯網
上載者:User

標籤:array   一點   att   www.   col   保留   hive   +=   odi   

生物資訊學原理作業第五彈:K-means聚類的實現。

轉載請保留出處!

K-means聚類的Python實現

原理參考:K-means聚類(上)

資料是老師給的,二維,2 * 3800的資料。plot一下可以看到有7類。

怎麼確定分類個數我正在學習,這個指令碼就直接給了初始分類了,等我學會了再發。

                                                                      

下面貼上Python代碼,版本為Python3.6。

 1 # -*- coding: utf-8 -*- 2 """ 3 Created on Wed Dec  6 16:01:17 2017 4  5 @author: zxzhu 6 """ 7 import numpy as np 8 import matplotlib.pyplot as plt 9 from numpy import random10 11 def Distance(x):12     def Dis(y):13         return np.sqrt(sum((x-y)**2))                      #歐式距離14     return Dis15 16 def init_k_means(k):17     k_means = {}18     for i in range(k):19         k_means[i] = []20     return k_means21 22 def cal_seed(k_mean):                                      #重新計算種子點23     k_mean = np.array(k_mean)24     new_seed = np.mean(k_mean,axis=0)                      #各維度均值25     return new_seed26     27 def K_means(data,seed_k,k_means):28     for i in data:29         f = Distance(i)30         dis = list(map(f,seed_k))                        #某一點距所有種子點的距離31         index = dis.index(min(dis))32         k_means[index].append(i)33     34     new_seed = []                                           #儲存新種子35     for i in range(len(seed_k)):36         new_seed.append(cal_seed(k_means[i]))37     new_seed = np.array(new_seed)38     return k_means,new_seed39     40 def run_K_means(data,k):41     seed_k = data[random.randint(len(data),size=k)]       #隨機產生種子點42     k_means = init_k_means(k)                                #初始化每一類43     result = K_means(data,seed_k,k_means)44     count = 045     while not (result[1] == seed_k).all():                     #種子點改變,繼續聚類46         count+=147         seed_k = result[1]48         k_means = init_k_means(k=7)   49         result = K_means(data,seed_k,k_means)50     print(‘Done‘)51     #print(result[1])52     print(count)53     plt.figure(figsize=(8,8))54     Color = ‘rbgyckm‘55     for i in range(k):56         mydata = np.array(result[0][i])57         plt.scatter(mydata[:,0],mydata[:,1],color = Color[i])58     return result[0]59 60 data = np.loadtxt(‘K-means_data‘)61 run_K_means(data,k=7)   

附上結果圖:

這個演算法太依賴於初始種子點的選取了,隨機選點很有可能會得到局部最優的結果,所以下一步學習一下怎麼設定初始種子點以及分類數目。

 

K-means聚類的Python實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.