Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0820
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
本教程同步发布在:
个人网站: `https://oeasy.org`
蓝桥云课: `https://www.lanqiao.cn/courses/3584`
GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
Gitee: `https://gitee.com/overmind1980/oeasypython`
---import numpy as np
def kmeans(X, k, max_iters=100, tol=1e-4):
"""
K-means聚类算法
参数:
X: 输入数据,形状为 (n_samples, n_features) 的numpy数组
k: 聚类数量
max_iters: 最大迭代次数
tol: 收敛阈值
返回:
centroids: 聚类中心
labels: 每个样本的聚类标签
"""
# 随机初始化k个聚类中心
n_samples, n_features = X.shape
centroids = X[np.random.choice(n_samples, k, replace=False)]
for _ in range(max_iters):
# 保存旧的聚类中心
old_centroids = centroids.copy()
# 计算每个样本到各个聚类中心的距离
distances = np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2))
# 为每个样本分配最近的聚类
labels = np.argmin(distances, axis=0)
# 更新聚类中心
for i in range(k):
if np.sum(labels == i) > 0:
centroids[i] = np.mean(X[labels == i], axis=0)
# 检查是否收敛
if np.sum((centroids - old_centroids)**2) < tol:
break
return centroids, labels
# 使用示例
if __name__ == "__main__":
# 生成示例数据
np.random.seed(42)
X = np.concatenate([
np.random.normal(0, 1, (100, 2)),
np.random.normal(4, 1, (100, 2)),
np.random.normal(8, 1, (100, 2))
])
# 运行K-means
k = 4
centroids, labels = kmeans(X, k)
# 打印结果
print("聚类中心:")
print(centroids)
print("\n样本标签:")
print(labels)
# 可视化结果
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', marker='x', s=200, linewidths=3)
plt.title('K-means聚类结果')
plt.show()
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。

