自定义数据集,使用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()
相关推荐
mingo_敏1 天前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法
大学生就业之家【央国企就业指导】2 天前
央国企求职避免无效海投
scrapy·scikit-learn·pygame
hboot13 天前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
cvcode_study19 天前
Scikit-learn
python·机器学习·scikit-learn
2601_9618752420 天前
花生十三资源盘|电子版|全科
python·django·flask·virtualenv·scikit-learn·pygame·tornado
金融小师妹20 天前
基于AI事件驱动模型与验证溢价框架的市场分析:从预期交易到事实验证,原油与黄金面临关键定价重构
大数据·人工智能·算法·均值算法·线性回归
金融小师妹25 天前
AI因子共振模型显示:金银比突破区间上沿,白银定价逻辑进入再校准阶段
人工智能·算法·均值算法·线性回归
龙腾AI白云1 个月前
用知识图谱重构搜索引擎
人工智能·virtualenv·scikit-learn
龙腾AI白云1 个月前
从GPT到开源大模型
scikit-learn·知识图谱
SilentSamsara1 个月前
scikit-learn 工作流工程化:Pipeline、ColumnTransformer 与自定义转换器
开发语言·人工智能·python·机器学习·青少年编程·numpy·scikit-learn