无监督学习-K均值聚类

0.理论

k均值聚类是机器学习中一种非常常用的技术,简单来说,k均值聚类就是将数据分成k个组,根据数据点距离哪个组的中心点最近而决定。

1.基于收入与年龄进行人群聚类

import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.preprocessing import scale

def createClusteredData(N, k):
    """生成随机的收入、年龄数据

    Args:
        N (int): N个人
        k (int): k个聚类

    Returns:
        array: 包含收入、年龄的数组
    """   
    # 生成随机种子 
    np.random.seed(10)
    # 每个聚类的数据量
    pointsPerCluster = float(N)/k
    X = []
    # 生成k个聚类  
    for i in range (k):
        incomeCentroid = np.random.uniform(20000.0, 200000.0)
        ageCentroid = np.random.uniform(20.0, 70.0)
        # 每个聚类生成数据
        for j in range(int(pointsPerCluster)):
            X.append([np.random.normal(incomeCentroid, 10000.0), np.random.normal(ageCentroid, 2.0)])    
    return np.array(X)

N = 100
k = 5
data = createClusteredData(N, k)
# 初始化模型
model = KMeans(n_clusters=k)

# 标准化数据
model = model.fit(scale(data))

# 模型结果
print(model.labels_)

# 画图
plt.scatter(data[:,0], data[:,1], c=model.labels_)
plt.show()
C:\Users\Administrator\anaconda3\lib\site-packages\sklearn\cluster\_kmeans.py:870: FutureWarning: The default value of `n_init` will change from 10 to 'auto' in 1.4. Set the value of `n_init` explicitly to suppress the warning
  warnings.warn(
C:\Users\Administrator\anaconda3\lib\site-packages\sklearn\cluster\_kmeans.py:1382: UserWarning: KMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can avoid it by setting the environment variable OMP_NUM_THREADS=1.
  warnings.warn(


[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]

请添加图片描述

2.参考资料

Python数据科学与机器学习:从入门到实践
作者:
[美]弗兰克•凯恩(Frank Kane)

源代码下载:
https://www.ituring.com.cn/book/2426

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值