hugeng007_demo02_Clustering_algorithm_to_build_customer_segmentation_model

本文探讨了市场成功的基础——客户细分,并通过无监督学习方法对客户数据进行了聚类分析,比较了不同聚类算法的优劣。利用多种算法建立客户细分模型,展示了均值漂移聚类模型的构建过程及效果评估。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Customer segmentation is the premise of marketing success. The data we get from the market is generally not marked. To segment customers into these market data and divide the customers into clusters is a typical unsupervised learning problem.

This project intends to use a variety of different clustering algorithms to build customer segmentation models, and compare the superiority of these clustering algorithms on this issue.

Get the dataset

The transmission of the dataset

1433065-20180913215911654-1290082909.png

For these 6 features, the data set has told us the min, max mean and other information of these 6 columns, I put them into a table, as shown below:

1433065-20180913215954138-214452756.png

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(37) # 使得每次运行得到的随机数都一样
# 准备数据集
data_path='D:\Chrome\Chrome Download\
Wholesale customers data.csv'
df=pd.read_csv(data_path)
print(df.info()) # 查看数据信息,确保没有错误
# print('-'*100)
dataset=df.values # 数据加载没有问题
# print(dataset.shape) # ((441, 8)
dataset=dataset[:,2:]# 本项目只需要后面的6列features即可
col_names=df.columns.tolist()[2:]
print(col_names)

1433065-20180913221610446-1755395813.png

# 无标签数据集可视化,将第一列feature作为X,第二列feature作为y
def visual_2D_dataset_dist(dataset):
    '''将二维数据集dataset显示在散点图中'''
    assert dataset.shape[1]==2,'only support dataset with 2 features'
    plt.figure()
    X=dataset[:,0]
    Y=dataset[:,1]
    plt.scatter(X,Y,marker='v',c='g',label='dataset')
    
    X_min,X_max=np.min(X)-1,np.max(X)+1
    Y_min,Y_max=np.min(Y)-1,np.max(Y)+1
    plt.title('dataset distribution')
    plt.xlim(X_min,X_max)
    plt.ylim(Y_min,Y_max)
    plt.xlabel('feature_0')
    plt.ylabel('feature_1')
    plt.legend()

visual_2D_dataset_dist(dataset[:,:2]) # X=fresh, y=milk

1433065-20180913221623943-223396502.png

visual_2D_dataset_dist(dataset[:,1:3]) # X=milk, y=gricery

1433065-20180913221631749-716646842.png

Constructing a mean drift clustering model(构建均值漂移聚类模型)

The code also prints out the number of clusters after clustering and prints the position of the centroid point of each cluster

该代码还打印出聚类后簇群的数量,并把每一种簇群的质心点位置打印出来。

# 构建均值漂移聚类模型
from sklearn.cluster import MeanShift, estimate_bandwidth
bandwidth=estimate_bandwidth(dataset,quantile=0.8,
                             n_samples=len(dataset))
meanshift=MeanShift(bandwidth=bandwidth,bin_seeding=True)
meanshift.fit(dataset) # 使用评估的带宽构建均值漂移模型,并进行训练
labels=meanshift.labels_
cluster_num=len(np.unique(labels))
centroids=meanshift.cluster_centers_
# 下面打印出簇群种类,和质心位置信息
print('Number of Clusters: {}'.format(cluster_num))
print('\t'.join([col_name[:5] for col_name in col_names]))
for centroid in centroids:
    print('\t'.join(str(int(x)) for x in centroid))

1433065-20180913222342639-1351721004.png

def visual_cluster_effect(cluster,dataset,title,col_id):
    assert isinstance(col_id,list) and len(col_id)==2,'col_id must be list type and length must be 2'
    
    labels=cluster.labels_ # 每一个样本对应的簇群号码
#     print(labels.shape) # (440,) 440个样本
    markers=['.',',','o','v','^','<','>','1','2','3','4','8'
                 ,'s','p','*','h','H','+','x','D','d','|']
    colors=['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 
            'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']
    
    # 将数据集绘制到图表中
    plt.figure()
    for class_id in set(labels):
        one_class=dataset[class_id==labels]
        print('label: {}, smaple_num: {}'.format(class_id,len(one_class)))
        plt.scatter(one_class[:,0],one_class[:,1],marker=markers[class_id%len(markers)],
                    c=colors[class_id%len(colors)],label='class_'+str(class_id))
    plt.legend()
        
    # 将中心点绘制到图中
    centroids=meanshift.cluster_centers_
#     print(centroids.shape)# eg (8, 6) 8个簇群,6个features
    plt.scatter(centroids[:,col_id[0]],centroids[:,col_id[1]],marker='o',
                s=100,linewidths=2,color='k',zorder=5,facecolors='b')
    plt.title(title) 
    plt.xlabel('feature_0')
    plt.ylabel('feature_1')
    plt.show()
visual_cluster_effect(meanshift,dataset,'MeanShift-X=fresh,y=milk',[0,1]) # X=fresh, y=milk

1433065-20180913222420481-1187253215.png

1433065-20180913222424499-750395786.png

visual_cluster_effect(meanshift,dataset,'MeanShift-X=grocery,y=delica',[2,5]) # X=grocery, y=Delicassen

1433065-20180913222443995-460163904.png

1433065-20180913222447860-209071075.png

# 使用轮廓系数评估模型的优虐
from sklearn.metrics import silhouette_score
si_score=silhouette_score(dataset,meanshift.labels_,
                          metric='euclidean',sample_size=len(dataset))
print('si_score: {:.4f}'.format(si_score))

si_score: 0.6548

转载于:https://www.cnblogs.com/hugeng007/p/9643648.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值