自定义数据集,使用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()
相关推荐
万粉变现经纪人几秒前
如何解决 pip install -r requirements.txt 子目录可编辑安装缺少 pyproject.toml 问题
开发语言·python·scrapy·beautifulsoup·scikit-learn·matplotlib·pip
派森先生5 天前
sk09.【scikit-learn基础】--『无监督学习』之K均值聚类
学习·均值算法·scikit-learn
派森先生5 天前
sk08.【scikit-learn基础】--『监督学习』之K近邻算法
学习·scikit-learn·近邻算法
十三画者6 天前
【文献分享】通过基于大型语言模型嵌入的蛋白质的 k 均值聚类来探索同源性检测
均值算法·语言模型·聚类
Learn Beyond Limits12 天前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
无风听海13 天前
神经网络之为什么回归任务的输出是高斯分布的均值
神经网络·均值算法·回归
java1234_小锋16 天前
Scikit-learn Python机器学习 - 模型保存及加载
python·机器学习·scikit-learn
深栈17 天前
机器学习:逻辑回归
人工智能·pytorch·机器学习·逻辑回归·scikit-learn
jie*18 天前
小杰深度学习(four)——神经网络可解释性、欠拟合、过拟合
人工智能·python·深度学习·神经网络·scikit-learn·matplotlib·sklearn
万粉变现经纪人19 天前
如何解决 pip install 安装报错 ImportError: cannot import name ‘xxx’ from ‘yyy’ 问题
python·selenium·测试工具·flask·scikit-learn·fastapi·pip