K-modes聚类实战:用Python处理电商用户分类数据(附完整代码)

K-modes聚类实战:用Python处理电商用户分类数据(附完整代码) K-modes聚类实战用Python处理电商用户分类数据附完整代码在电商行业蓬勃发展的今天用户行为数据的分析已经成为提升运营效率的关键。面对海量的用户品类偏好、购买频次等离散型数据如何从中挖掘出有价值的用户群体特征传统的K-means算法在处理这类非数值型数据时往往力不从心而K-modes算法则为我们提供了更合适的解决方案。本文将带你从零开始使用Python实现一个完整的电商用户分类分析项目。不同于单纯的理论讲解我们会聚焦于实际业务场景中的数据处理技巧、模型调参方法和结果解读策略。无论你是数据分析师还是算法工程师都能从中获得可直接应用于工作的实战经验。1. 理解K-modes算法与业务场景1.1 为什么选择K-modes在电商数据分析中我们经常遇到这样的数据类型用户性别男/女年龄段18-25/26-35/36-45等偏好品类美妆/数码/家居等购买频次低频/中频/高频这些都属于分类变量传统的K-means算法使用的欧式距离在这里并不适用。K-modes算法的核心优势在于使用汉明距离替代欧式距离用**众数(mode)**替代均值(mean)作为簇中心计算效率高适合大规模分类数据集汉明距离的计算公式为D(x,y) Σ δ(x_j, y_j) 其中δ(a,b) 0 if a b else 11.2 电商用户分群的应用价值通过K-modes聚类我们可以实现以下业务目标精准营销针对不同群体设计差异化促销策略库存优化预测各用户群体的热门商品需求用户体验提升根据群体特征优化推荐系统客户生命周期管理识别高价值用户群体2. 数据准备与预处理2.1 构建模拟数据集我们先创建一个模拟的电商用户数据集import pandas as pd import numpy as np # 设置随机种子保证可复现性 np.random.seed(42) # 定义各特征的取值 genders [Male, Female] age_groups [18-25, 26-35, 36-45, 46-55, 55] categories [Electronics, Clothing, Grocery, Beauty, Home] frequencies [Low, Medium, High] # 生成1000个样本 data { user_id: range(1000), gender: np.random.choice(genders, 1000), age_group: np.random.choice(age_groups, 1000, p[0.2, 0.3, 0.25, 0.15, 0.1]), preferred_category: np.random.choice(categories, 1000, p[0.25, 0.2, 0.15, 0.3, 0.1]), purchase_frequency: np.random.choice(frequencies, 1000, p[0.6, 0.3, 0.1]) } df pd.DataFrame(data) df.head()2.2 分类数据编码K-modes算法需要将分类变量转换为数值形式# 对分类变量进行标签编码 from sklearn.preprocessing import LabelEncoder le LabelEncoder() df_encoded df.copy() for col in [gender, age_group, preferred_category, purchase_frequency]: df_encoded[col] le.fit_transform(df[col]) # 提取特征矩阵 X df_encoded.drop(user_id, axis1)3. 模型训练与评估3.1 确定最佳聚类数使用肘部法则(Elbow Method)确定最优聚类数from kmodes.kmodes import KModes import matplotlib.pyplot as plt costs [] K range(1, 8) for k in K: kmodes KModes(n_clustersk, initHuang, n_init5, verbose0) kmodes.fit(X) costs.append(kmodes.cost_) plt.plot(K, costs, bx-) plt.xlabel(Number of clusters) plt.ylabel(Cost) plt.title(Elbow Method For Optimal k) plt.show()3.2 训练最终模型根据肘部法则选择k3# 训练最终模型 kmodes KModes(n_clusters3, initHuang, n_init5) clusters kmodes.fit_predict(X) # 将聚类结果添加到原始数据 df[cluster] clusters3.3 聚类结果分析查看各簇的分布情况cluster_counts df[cluster].value_counts().sort_index() print(cluster_counts)分析各簇的特征# 计算每个簇中各类别的比例 cluster_profiles df.groupby(cluster).agg({ gender: lambda x: x.value_counts().index[0], age_group: lambda x: x.value_counts().index[0], preferred_category: lambda x: x.value_counts().index[0], purchase_frequency: lambda x: x.value_counts().index[0], user_id: count }).rename(columns{user_id: count}) print(cluster_profiles)4. 结果可视化与业务解读4.1 可视化各簇特征import seaborn as sns # 设置绘图风格 sns.set(stylewhitegrid) # 绘制各簇的年龄分布 plt.figure(figsize(10, 6)) sns.countplot(datadf, xage_group, huecluster, paletteviridis) plt.title(Age Group Distribution by Cluster) plt.xticks(rotation45) plt.show() # 绘制各簇的品类偏好 plt.figure(figsize(10, 6)) sns.countplot(datadf, xpreferred_category, huecluster, paletteviridis) plt.title(Preferred Category Distribution by Cluster) plt.xticks(rotation45) plt.show()4.2 业务解读与策略建议根据我们的聚类结果可以识别出三个典型的用户群体年轻女性美妆爱好者主要特征女性18-35岁偏好美妆品类营销建议推送新品美妆试用装、限量版彩妆运营策略在下午6-10点推送促销信息该群体活跃时段中年男性电子产品消费者主要特征男性26-45岁偏好电子产品营销建议提供电子产品延保服务、配件套装运营策略强调技术参数和性价比全年龄段家庭采购者主要特征各年龄段均有分布偏好家居和日用品营销建议推送家庭套装、批量购买优惠运营策略强调实用性和耐用性5. 进阶技巧与优化方向5.1 处理混合型数据当数据集中同时包含数值型和分类型变量时可以使用K-prototypes算法from kmodes.kprototypes import KPrototypes # 假设我们有一个包含数值型特征的数据集 # 指定哪些列是分类变量索引从0开始 categorical_cols [0, 1, 2, 3] kproto KPrototypes(n_clusters3, initCao, verbose2) clusters kproto.fit_predict(X, categoricalcategorical_cols)5.2 特征重要性分析了解哪些特征对聚类结果影响最大# 计算每个特征在不同簇间的差异度 from scipy.stats import entropy feature_importance {} for col in [gender, age_group, preferred_category, purchase_frequency]: # 计算每个特征在各簇的分布 dist df.groupby(cluster)[col].value_counts(normalizeTrue).unstack() # 计算分布的熵值 feature_importance[col] entropy(dist.T) # 转换为DataFrame并按重要性排序 importance_df pd.DataFrame.from_dict(feature_importance, orientindex, columns[importance]) importance_df.sort_values(importance, ascendingFalse, inplaceTrue) print(importance_df)5.3 模型性能优化提升K-modes模型效果的几种方法初始化方法选择Huang计算初始中心的距离和Cao基于密度的方法random随机初始化多次初始化kmodes KModes(n_clusters3, initHuang, n_init10)特征工程合并相似类别创建更有业务意义的组合特征在实际电商数据分析项目中我们发现将用户最近浏览的品类与历史购买品类结合能显著提升聚类效果。例如创建一个兴趣转变特征标识用户是否从美妆转向了母婴用品这对识别孕期用户群体特别有效。