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)