生物信息学原理作业第五弹:K-means聚类的实现。

转载请保留出处!

K-means聚类的Python实现

原理参考:K-means聚类(上)

数据是老师给的,二维,2 * 3800的数据。plot一下可以看到有7类。

怎么确定分类个数我正在学习,这个脚本就直接给了初始分类了,等我学会了再发。

K-means聚类的Python实现-LMLPHP

下面贴上Python代码,版本为Python3.6。

 # -*- coding: utf-8 -*-
"""
Created on Wed Dec 6 16:01:17 2017 @author: zxzhu
"""
import numpy as np
import matplotlib.pyplot as plt
from numpy import random def Distance(x):
def Dis(y):
return np.sqrt(sum((x-y)**2)) #欧式距离
return Dis def init_k_means(k):
k_means = {}
for i in range(k):
k_means[i] = []
return k_means def cal_seed(k_mean): #重新计算种子点
k_mean = np.array(k_mean)
new_seed = np.mean(k_mean,axis=0) #各维度均值
return new_seed def K_means(data,seed_k,k_means):
for i in data:
f = Distance(i)
dis = list(map(f,seed_k)) #某一点距所有种子点的距离
index = dis.index(min(dis))
k_means[index].append(i) new_seed = [] #存储新种子
for i in range(len(seed_k)):
new_seed.append(cal_seed(k_means[i]))
new_seed = np.array(new_seed)
return k_means,new_seed def run_K_means(data,k):
seed_k = data[random.randint(len(data),size=k)] #随机产生种子点
k_means = init_k_means(k) #初始化每一类
result = K_means(data,seed_k,k_means)
count = 0
while not (result[1] == seed_k).all(): #种子点改变,继续聚类
count+=1
seed_k = result[1]
k_means = init_k_means(k=7)
result = K_means(data,seed_k,k_means)
print('Done')
#print(result[1])
print(count)
plt.figure(figsize=(8,8))
Color = 'rbgyckm'
for i in range(k):
mydata = np.array(result[0][i])
plt.scatter(mydata[:,0],mydata[:,1],color = Color[i])
return result[0] data = np.loadtxt('K-means_data')
run_K_means(data,k=7)

附上结果图:

K-means聚类的Python实现-LMLPHP

这个算法太依赖于初始种子点的选取了,随机选点很有可能会得到局部最优的结果,所以下一步学习一下怎么设置初始种子点以及分类数目。

05-04 01:36