python数据分析入门——聚类

python数据分析入门—聚类

  • 数据载入
  • 数据算法---皮尔逊相关系数
  • 分级聚类
  • 开始

用我自己的大白话理解聚类就是,
聚类是无监督学习,就是没有标准样本去学习。一堆数据放在一起,判断谁和谁靠的近,把靠的近的当成一个新的整体,在去对新的整体继续分析。直到最后只剩下一个整体,则为聚类结束

数据载入

//载入文件
def readfile(filename):
	lines = [line for line in open(filename)]
	colname = lines[0].strip().split('\t')[1:]
	//strip() 去除空格
	//split() 以xx为分割
	rowsname = []
	data = []
	for line in lines[1:]:
		p = line.strip().split('\t')
		rowsname.append(p[0])
		data.append([float(x) for x in p[1:]])
	return colname,rowsname,data

数据算法—皮尔逊相关系数

把俩组数据想象成俩条直线,求俩条直线的过拟合线。
算法不难,就是记不住哈哈

//皮尔逊相关系数
def sim_person(p1,p2):
	sum1 = sum(p1)
	sum2 = sum(p2)
	sum1Sq = sum([pow(v,2) for v in p1])
	sum2Sq = sum([pow(v,2) for v in p2])
	pSum = sum([p1[i]*p2[i] for i in range(len(p1))])
	num = pSum-(sum1*sum2/len(v1))
	den = sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v2)))
	if den == 0:
		return 0
	return 1.0-num/den

分级聚类

创建一个类,用来表示聚类

//皮尔逊相关系数
class bicuster:
	//俩个_ 刚开始学习的时候看书,俩个一个傻傻看不清楚
	def __init__(self,vec,left=None,right=None,distance=0.0,id=None):
		//C++里的构造函数
		self.left = left
		self.right = right
		//左右用来表示聚类的位置
		self.vec = vec
		//聚类数据
		self.id = id
		//用来表示聚类是原始的还是生成的
		self.distance = distance
		//表示距离

开始

def hcluster(rows,distance=sim_person):
	distances = {}
	currentocustid = -1
	clust = [bicluster(rows[i],id=i) for i in range(len(rows))]
	while len(clust) > 1:
		lowspair = (0,1)
		closest = distance(clust[0].vec,clust[1].vec)
		for i in range(len(clust)):
			for j in range(i+1,len(clust)):
				 if(clust[i].id,clust[j].id) not in distances:
				 	distances[(clust[i].id,clust[j].id)] = distance(clust[i].vec,clust[j].vec)
				 d = distances[(clust[i].id,clust[j].id)] 
				 if d < closest:
				 	lowspair = (i,j)
		mergevec = [(clust[lowspair[0]].vec[i]+clust[lowspair[1]].vec[i])/2.0 for i in range(len(clust[0].vec))]
		newcluster = bicluster(mergevec,left=clust[lowspair[0]],right=clust[lowspair[1]],distance=closest,id=currentocustid)
		del clust[lowerstpair[1]]
		del clust[lowerstpair[0]]
		clust.append(newcluster)
	return clust[0]

《集体智慧编程》这本书确实不错,以上就是第三章中的例子。

你可能感兴趣的:(数据挖掘,聚类,集体智慧编程)