k-means算法的Python实现
#coding=utf-8
import codecs
import numpy
from numpy import *
import pylab def loadDataSet(fileName):
dataMat = []
fr = codecs.open(fileName)
for line in fr.readlines():
curLine = line.strip().split('\t')
fltLine = map(float, curLine)
dataMat.append(fltLine)
return dataMat def distMeasure(vecA, vecB):
#print vecA
dist = sqrt(sum(power(vecA - vecB, 2)))
return dist def kMeansInitCentroids(X, K):
"""
KMEANSINITCENTROIDS This function initializes K centroids that are to be
used in K-Means on the dataset X
centroids = KMEANSINITCENTROIDS(X, K) returns K initial centroids to be
used with the K-Means on the dataset X.
"""
n = shape(X)[1]
centroids = mat(zeros((K,n)))
for j in range(n):
#print X[:,j]
minJ = min(X[:,j])
rangeJ = float(max(array(X)[:,j]) - minJ)
centroids[:,j] = minJ + rangeJ * random.rand(K,1)
return centroids def findClosestCentroids(X, centroids):
"""
FINDCLOSESTCENTROIDS computes the centroid memberships for every example
idx = FINDCLOSESTCENTROIDS (X, centroids) returns the closest centroids
in idx for a dataset X where each row is a single example. idx = m x 1
vector of centroid assignments (i.e. each entry in range [1..K])
"""
# 数据总量
m = shape(X)[0]
K = shape(centroids)[0]
clusterAssment = mat(zeros((m,2)))#create mat to assign data points
#to a centroid, also holds SE of each point
#centroids = createCent(dataSet, k)
clusterChanged = True
while clusterChanged:
clusterChanged = False
for i in range(m):#for each data point assign it to the closest centroid
minDist = inf; minIndex = -1
# k个中间数据(质心)都与数据i进行欧氏比较,选择距离最近的第minIndex类
for j in range(K):
distJI = distMeasure(centroids[j,:],X[i,:])
if distJI < minDist:
minDist = distJI; minIndex = j
if clusterAssment[i,0] != minIndex: clusterChanged = True
clusterAssment[i,:] = minIndex,minDist**2
return clusterAssment def computeCentroids(X, clusterAssment, K):
"""
COMPUTECENTROIDS returs the new centroids by computing the means of the
data points assigned to each centroid.
centroids = COMPUTECENTROIDS(X, idx, K) returns the new centroids by
computing the means of the data points assigned to each centroid. It is
given a dataset X where each row is a single data point, a vector
idx of centroid assignments (i.e. each entry in range [1..K]) for each
example, and K, the number of centroids. You should return a matrix
centroids, where each row of centroids is the mean of the data points
assigned to it.
"""
n = shape(X)[1]
centroids = mat(zeros((K,n)))
for centroid in range(K):#recalculate centroids
# nonzero会产生两个array,第一个非零的为序号列表
ptsInClust = X[nonzero(clusterAssment[:,0].A==centroid)[0]]#get all the point in this cluster
#print 'ererer:',ptsInClust,'dfdf'
centroids[centroid,:] = mean(ptsInClust, axis=0) #assign centroid to mean
return centroids def show(dataSet, k, centroids, clusterAssment):
from matplotlib import pyplot as plt
numSamples, dim = dataSet.shape
mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']
print type(dataSet)
for i in xrange(numSamples):
markIndex = int(clusterAssment[i, 0])
plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex])
mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']
for i in range(k):
plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 12)
plt.show() def runkMeans(X, initial_centroids,max_iters, plot_progress):
"""
RUNKMEANS runs the K-Means algorithm on data matrix X, where each row of X
is a single example
[centroids, idx] = RUNKMEANS(X, initial_centroids, max_iters, ...
plot_progress) runs the K-Means algorithm on data matrix X, where each
row of X is a single example. It uses initial_centroids used as the
initial centroids. max_iters specifies the total number of interactions
of K-Means to execute. plot_progress is a true/false flag that
indicates if the function should also plot its progress as the
learning happens. This is set to false by default. runkMeans returns
centroids, a Kxn matrix of the computed centroids and idx, a m x 1
vector of centroid assignments (i.e. each entry in range [1..K]).
"""
(m,n) = shape(X)
K = shape(initial_centroids)[0]
centroids = initial_centroids
clusterAssment = zeros((m,2)) #Run K-Means
for i in range(max_iters):
clusterAssment = findClosestCentroids(X, centroids)
centroids = computeCentroids(X, clusterAssment, K); return centroids, clusterAssment def main():
K =5
max_iters = 10
dataSet = loadDataSet('E://PythonSpace//TextClustering//data//test2.txt')
X = array(dataSet)
X = (X - mean(X)) / std(X) initial_centroids = kMeansInitCentroids(X, K)
myCentroids, clusterAssment = runkMeans(X, initial_centroids, max_iters,False);
print "-------------------------------------"
show(X, K, myCentroids, clusterAssment) main()
参考了Andrew Ng的Machine Learning Assignment(https://github.com/rieder91/MachineLearning/blob/master/Exercise%207/ex7/runkMeans.m)
以及博文http://www.cnblogs.com/MrLJC/p/4127553.html
运行结果:
k-means算法的Python实现的更多相关文章
- Fuzzy C Means 算法及其 Python 实现——写得很清楚,见原文
Fuzzy C Means 算法及其 Python 实现 转自:http://note4code.com/2015/04/14/fuzzy-c-means-%E7%AE%97%E6%B3%95%E5% ...
- 分类算法——k最近邻算法(Python实现)(文末附工程源代码)
kNN算法原理 k最近邻(k-Nearest Neighbor)算法是比较简单的机器学习算法.它采用测量不同特征值之间的距离方法进行分类,思想很简单:如果一个样本在特征空间中的k个最近邻(最相似)的样 ...
- KNN 与 K - Means 算法比较
KNN K-Means 1.分类算法 聚类算法 2.监督学习 非监督学习 3.数据类型:喂给它的数据集是带label的数据,已经是完全正确的数据 喂给它的数据集是无label的数据,是杂乱无章的,经过 ...
- K-means算法
K-means算法很简单,它属于无监督学习算法中的聚类算法中的一种方法吧,利用欧式距离进行聚合啦. 解决的问题如图所示哈:有一堆没有标签的训练样本,并且它们可以潜在地分为K类,我们怎么把它们划分呢? ...
- Python实现kNN(k邻近算法)
Python实现kNN(k邻近算法) 运行环境 Pyhton3 numpy科学计算模块 计算过程 st=>start: 开始 op1=>operation: 读入数据 op2=>op ...
- 机器学习算法与Python实践之(五)k均值聚类(k-means)
机器学习算法与Python实践这个系列主要是参考<机器学习实战>这本书.因为自己想学习Python,然后也想对一些机器学习算法加深下了解,所以就想通过Python来实现几个比较常用的机器学 ...
- 机器学习算法与Python实践之(六)二分k均值聚类
http://blog.csdn.net/zouxy09/article/details/17590137 机器学习算法与Python实践之(六)二分k均值聚类 zouxy09@qq.com http ...
- 用Python从零开始实现K近邻算法
KNN算法的定义: KNN通过测量不同样本的特征值之间的距离进行分类.它的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别.K通 ...
- 机器学习 Python实践-K近邻算法
机器学习K近邻算法的实现主要是参考<机器学习实战>这本书. 一.K近邻(KNN)算法 K最近邻(k-Nearest Neighbour,KNN)分类算法,理解的思路是:如果一个样本在特征空 ...
- K均值算法-python实现
测试数据展示: #coding:utf-8__author__ = 'similarface''''实现K均值算法 算法摘要:-----------------------------输入:所有数据点 ...
随机推荐
- ./encrypt: error while loading shared libraries: libcrypto.so.10:
./encrypt: error while loading shared libraries: libcrypto.so.10:
- php的错误和异常处理
php中try catch的例子: <?php try { if (@mysql_connect('localhost','root','123456')){ // echo 'success! ...
- 【servlet】客户端是否可以访问到WEB-INF下的jsp文件
一般情况下(不考虑出现安全问题被入侵,那样啥都能访问到),WEB-INF下的jsp文件单凭浏览器端请求时访问不到的. 想访问的话需要通过服务端servlet的转发. 下面通过转发和重定向的尝试来观察访 ...
- 【java】基础中的杂乱总结(二)
1 内部类进阶 package package8; //原则:先用内部类写 之后由于内部类匿名无法引用 用其继承的父类或实现的接口名 //再复写所有的抽象方法即可(是所有,否者还是抽象的,无法创建对象 ...
- 事件委托小demo(原生版)
<style type="text/css"> body, div, span { margin:; padding:; font-family: "\5FA ...
- Filter 解决web网页跳转乱码
为什么采用filter实现了字符集的统一编码 问题: 为什么会有字符集编码的问题呢?对于Java Web应用,使用Tomcat容器获取和传递的参数(request.getParameter())默认是 ...
- linux内核移植到S5pv210
make s5pv210_defconfig 1.System Type ---> (0) S3C UART to use for low-level messages 2.Kernel ha ...
- HDU2216:Game III(BFS)
Game III Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other) Total Subm ...
- java 线程的中断
Example12_6.java public class Example12_6 { public static void main(String args[]) { ClassRoom room6 ...
- HDU 5722 Jewelry
矩形面积并. 需要转化一下思路:记录每一个位置的数以及位置. 对数字进行从小到大排序,数字一样的按位置从小到大排. 这样,一样的数就在一起了.连续的相同的x个数就可以构成很多解,这些解对应于二维平面上 ...