W3School TIY Editor

  • W3School 在线教程
  • 改变方向
  • 暗黑模式
​x
 
# 这三行代码使编译器能够绘图:
import sys
import matplotlib
matplotlib.use('Agg')
​
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
​
# 定义样本数据:
x = [4, 5, 10, 4, 3, 11, 14, 6, 10, 12]
y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]
​
# 组合数据并初始化惯性值列表:
data = list(zip(x, y))
inertias = []  # 存储不同聚类数对应的惯性值
​
# 测试 1 到 10 个聚类数的情况:
for i in range(1, 11):
    kmeans = KMeans(n_clusters=i)  # 创建 K-means 模型
    kmeans.fit(data)  # 训练模型
    inertias.append(kmeans.inertia_)  # 记录当前惯性值
​
# 绘制肘部法则曲线:
plt.plot(range(1,11), inertias, marker='o')
plt.title('肘部法则(Elbow method)')
plt.xlabel('聚类数量')
plt.ylabel('惯性值(Inertia)')
plt.show()
​
# 这两行代码使编译器能够输出图形:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()