自定义数据集,使用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()
相关推荐
Evand J3 天前
【MATLAB例程】滑动窗口均值滤波、中值滤波、最小值/最大值滤波对比。附代码下载链接
开发语言·matlab·均值算法
Yn3123 天前
如何安装 scikit-learn Python 库
python·机器学习·scikit-learn
芥末章宇3 天前
Jetson NX Python环境搭建:使用APT轻松安装NumPy, scikit-learn, OpenCV
python·numpy·scikit-learn
万粉变现经纪人4 天前
何解决PyCharm中pip install安装Python报错ModuleNotFoundError: No module named ‘json’问题
python·pycharm·json·beautifulsoup·scikit-learn·matplotlib·pip
tryCbest6 天前
Python人工智能中scikit-learn模块的使用介绍
人工智能·python·scikit-learn
西猫雷婶6 天前
scikit-learn/sklearn学习|岭回归解读
开发语言·人工智能·机器学习·支持向量机·回归·scikit-learn·sklearn
码界筑梦坊7 天前
99-基于Python的京东手机数据分析及预测系统
python·智能手机·数据分析·django·毕业设计·scikit-learn
万粉变现经纪人9 天前
如何解决pip安装报错ModuleNotFoundError: No module named ‘transformers’问题
人工智能·python·beautifulsoup·pandas·scikit-learn·pip·ipython
路人蛃10 天前
Scikit-learn - 机器学习库初步了解
人工智能·python·深度学习·机器学习·scikit-learn·交友
xw337340956410 天前
scikit-learn工具介绍
python·机器学习·scikit-learn