K-Means Using Python


原文来自我的个人博客:http://www.yuanyong.org/blog/python/k-means-using-python

最近在翻译《Programming Computer Vision with Python》第六章Clustering Images,其中用到了k-means,这里根据书中给出的实例对k-means python code做一些解释。关于k-means聚类算法的原理,这里不再赘述,原理可以查阅相关资料。

在给出完整代码之前,我们先来理解两个numpy、scipy两个模块中设计到的两个函数,分别对应的是numpy.vstack()和scipy.cluster.vq()。我们直接看这两个函数的例子:

Example for numpy.vstack()

1 >>> a = np.array([123])
2 >>> b = np.array([234])
3 >>> np.vstack((a,b))

输出结果为:

array([[1, 2, 3], [2, 3, 4]])

从这个简单的例子可以看出,np.vstack()这个函数实现connection的作用,即connection(a,b),为了看得更清楚,我们再来看一个这个函数的例子:

1 >>> a = np.array([[1], [2], [3]])
2 >>> b = np.array([[2], [3], [4]])
3 >>> np.vstack((a,b))

输出结果这里不给出了,具体可以再python shell上test。好了,现在我们了解了这个函数的作用,我们再来看scipy.cluster.vq()函数的作用,这里也直接给出实例,通过实例解释该函数的作用:

Example for scipy.cluster.vq()

1 >>> from numpy import array
2 >>> from scipy.cluster.vq import vq
3 >>> code_book = array([[1.,1.,1.],[2.,2.,2.]])
4 >>> features  = array([[  1.9,2.3,1.7],[  1.5,2.5,2.2],[  0.8,0.6,1.7]])
5 >>> vq(features,code_book)

输出结果为:

(array([1, 1, 0]), array([ 0.43588989,  0.73484692,  0.83066239])),下图解释了该结果的意义,array([1, 1, 0])中的元素表示features中的数据点对应于code_book中离它最近距离的索引,如数据点[1.9, 2.3, 1.7]离code_book中的[2., 2., 2.]最近,该数据点对的对应于code_book中离它最近距离的索引为1,在python中索引值时从0开始的。

当然,对于上面的结果可以用linalg.norm()函数进行验证,验证过程为:

1 >>> from numpy import array
2 >>> from scipy.cluster.vq import vq
3 >>> code_book = array([[1.,1.,1.],[2.,2.,2.]])
4 >>> features  = array([[  1.9,2.3,1.7],[  1.5,2.5,2.2],[  0.8,0.6,1.7]])
5 >>> vq(features,code_book)
6 >>> from numpy import *
7 dist = linalg.norm(code_book[1,:] - features[0,:])

输出的dist的结果为:dist: 0.43588989435406728

好了,了解完这两个函数,我们可以上完整了演示k-means完整的代码了。

1 """
2 Function: Illustrate the k-means
3 Date: 2013-10-27
4 """"
5 from pylab import *
6 from scipy.cluster.vq import *
7  
8 class1 = 1.5 * randn(100,2)
9 class2 = randn(100,2+ array([5,5])
10 features = vstack((class1,class2))
11 centroids,variance = kmeans(features,2)
12 code,distance = vq(features,centroids)
13 figure()
14 ndx = where(code==0)[0]
15 plot(features[ndx,0],features[ndx,1],'*')
16 ndx = where(code==1)[0]
17 plot(features[ndx,0],features[ndx,1],'r.')
18 plot(centroids[:,0],centroids[:,1],'go')
19 axis('off')
20 show()

上述代码中先随机生成两类数据,每一类数据是一个100*2的矩阵,centroids是聚类中心,这里聚类中心k=2,并将其作为code_book代用vq(),代码运行结果如下:

上图显示了原数据聚完类后的结果,绿色圆点表示聚类中心。

Hello Python. Enjoy yourself.

Reference:

[1]. http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.vq.html#scipy.cluster.vq.vq

[2]. http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html


### 使用Python实现K-Means聚类分析来创建用户画像 #### 准备工作 为了使用`scikit-learn`库执行K-Means聚类并构建用户画像,需先安装必要的软件包。如果尚未安装这些依赖项,则可以通过pip命令完成安装。 ```bash pip install numpy pandas matplotlib seaborn scikit-learn ``` #### 导入所需库 导入用于数据分析、可视化以及实施K-Means算法所需的各个库: ```python import numpy as np import pandas as pd from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import seaborn as sns sns.set(style="white", color_codes=True) ``` #### 加载数据集 假设有一个CSV文件包含了用户的多种属性信息,比如年龄、性别编码后的数值、消费金额等特征列。这里简单模拟一组数据作为示范用途。 ```python # 创建虚拟数据框以供测试 data = { 'Age': [25, 30, 45, 67, 28], 'Gender': [1, 0, 1, 0, 1], # 假设男=1女=0 'SpendingScore': [40, 55, 65, 90, 35] } df = pd.DataFrame(data) print(df.head()) ``` #### 数据预处理 标准化输入变量使得不同尺度下的特性能够被公平对待,在此阶段会去除量纲影响从而提高模型性能。 ```python features = ['Age', 'Gender', 'SpendingScore'] X = df[features] scaler = StandardScaler() scaled_features = scaler.fit_transform(X) ``` #### 应用K-Means聚类 设定预期的簇数目(本例中为3),接着调用`fit_predict()`方法对已缩放的数据点分配标签。 ```python num_clusters = 3 kmeans = KMeans(n_clusters=num_clusters, random_state=42).fit(scaled_features) labels = kmeans.labels_ df['Cluster'] = labels print(df[['Age', 'Gender', 'SpendingScore', 'Cluster']].head()) ``` #### 可视化结果 利用散点图展示各群组间的分布情况,以便直观理解所形成的分段效果。 ```python plt.figure(figsize=(10, 6)) sns.scatterplot(x='Age', y='SpendingScore', hue='Cluster', data=df, palette='viridis') plt.title('Customer Segmentation using K-Means Clustering') plt.show() ``` 上述过程展示了如何基于给定的数据集运用K-Means聚类技术来进行简单的客户细分操作[^1]。值得注意的是实际应用场景下可能涉及更多维度的信息采集与更复杂的前处理步骤;此外选择合适的簇数也是至关重要的环节之一,通常借助肘部法则或轮廓系数法辅助决策[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值