Maciej Pacula » k-means clustering example (Python)
I had to illustrate a k-means algorithm for my thesis, but I could not find any existing examples that were both simple and looked good on paper. See below for Python code that does just what I wanted.
#!/usr/bin/python # Adapted from http://hackmap.blogspot.com/2007/09/k-means-clustering-in-scipy.html import numpy import matplotlib matplotlib.use('Agg') from scipy.cluster.vq import * import pylab pylab.close() # generate 3 sets of normally distributed points around # different means with different variances pt1 = numpy.random.normal(1, 0.2, (100,2)) pt2 = numpy.random.normal(2, 0.5, (300,2)) pt3 = numpy.random.normal(3, 0.3, (100,2)) # slightly move sets 2 and 3 (for a prettier output) pt2[:,0] += 1 pt3[:,0] -= 0.5 xy = numpy.concatenate((pt1, pt2, pt3)) # kmeans for 3 clusters res, idx = kmeans2(numpy.array(zip(xy[:,0],xy[:,1])),3) colors = ([([0.4,1,0.4],[1,0.4,0.4],[0.1,0.8,1])[i] for i in idx]) # plot colored points pylab.scatter(xy[:,0],xy[:,1], c=colors) # mark centroids as (X) pylab.scatter(res[:,0],res[:,1], marker='o', s = 500, linewidths=2, c='none') pylab.scatter(res[:,0],res[:,1], marker='x', s = 500, linewidths=2) pylab.savefig('/tmp/kmeans.png')The output looks like this (also available in vector format here):
The X’s mark cluster centers. Feel free to use any of these files for whatever purposes. An attribution would be nice, but is not required .
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)
2011-12-08 磁力链
2011-12-08 水木清华
2010-12-08 ruby rails时间处理
2010-12-08 rails ruby 时间 日期 处理
2010-12-08 jquery outerhtml
2010-12-08 javascript:void(0)