自定义数据集,使用scikit-learn 中K均值包 进行聚类

python 复制代码
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np

class1_points = np.array([[1.9, 1.2],
                          [1.5, 2.1],
                          [1.9, 0.5],
                          [1.5, 0.9],
                          [0.9, 1.2],
                          [1.1, 1.7],
                          [1.4, 1.1]])

class2_points = np.array([[-1.9, 1.2],
                          [-1.5, 2.1],
                          [-1.9, 0.5],
                          [-1.5, 0.9],
                          [-0.9, 1.2],
                          [-1.1, 1.7],
                          [-1.4, 1.1]])

class3_points = np.array([[1.9, -1.2],
                          [1.5, -2.1],
                          [1.9, -0.5],
                          [1.5, -0.9],
                          [0.9, -1.2],
                          [1.1, -1.7],
                          [1.4, -1.1]])

class4_points = np.array([[-1.9, -1.2],
                          [-1.5, -2.1],
                          [-1.9, -0.5],
                          [-1.5, -0.9],
                          [-0.9, -1.2],
                          [-1.1, -1.7],
                          [-1.4, -1.1]])

data = np.concatenate((class1_points, class2_points, class3_points, class4_points))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

k = 4

ax1.scatter(data[:, 0], data[:, 1], s=50)
ax1.plot()

km = KMeans(n_clusters=k,max_iter=30)
km.fit(data)
centers = km.cluster_centers_
y_kmeans = km.predict(data)
print(y_kmeans)

for i in range(k):
    cluster_points = data[y_kmeans == i]
    centroid = centers[i]
    for cluster_points in cluster_points:
        ax2.plot([cluster_points[0], centroid[0]],[cluster_points[1], centroid[1]],'k--')

ax2.scatter(data[:, 0], data[:, 1], c = y_kmeans, s=50)
ax2.scatter(centers[:, 0], centers[:, 1], c='black', s=100, alpha=0.5)

plt.show()
相关推荐
程序员阿超的博客11 小时前
Python 数据分析与机器学习入门 (八):用 Scikit-Learn 跑通第一个机器学习模型
python·机器学习·数据分析·scikit-learn·入门教程·python教程
西猫雷婶12 天前
python学智能算法(十五)|机器学习朴素贝叶斯方法进阶-CountVectorizer多文本处理
人工智能·python·深度学习·机器学习·scikit-learn
ghie909021 天前
LMD分解通过局部均值分解重构信号实现对信号的降噪
算法·均值算法·重构
Blossom.11821 天前
基于深度学习的异常检测系统:原理、实现与应用
人工智能·深度学习·神经网络·目标检测·机器学习·scikit-learn·sklearn
牛马的人生22 天前
入门Scikit-learn:让机器学习像呼吸一样自然!
python·其他·机器学习·scikit-learn
databook23 天前
规则学习:让机器学习像人类一样思考的可解释之路
python·机器学习·scikit-learn
RockyRich24 天前
突然无法调用scikit-learn、xgboost
python·机器学习·scikit-learn
开开心心就好24 天前
免费PDF转图片软件
javascript·智能手机·pdf·flask·word·excel·scikit-learn
databook25 天前
概率图模型:机器学习的结构化概率之道
python·机器学习·scikit-learn
Blossom.1181 个月前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn