K-Means

代码:

import copy

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (16, 9)  # 画布大小
plt.style.use('ggplot')  # 画布背景
# 显示中文设置...
plt.rcParams['font.sans-serif'] = ['SimHei'] # 替换sans-serif字体
plt.rcParams['axes.unicode_minus'] = False   # 解决坐标轴负数的负号显示问题

def distance(a, b, ax = 1):  # 按行计算两点欧氏距离
    return np.linalg.norm(a - b, ord = 2, axis = ax)
'''

'''

data = pd.read_csv('./xclara.csv')
f1 = data['V1'].values
f2 = data['V2'].values
X = np.array(list((zip(f1, f2))))  # 数据点
print("X.shape: ", X.shape)
# X.shape: (3000, 2)


K = 3
C_x = np.random.randint(0, np.max(X)-20, size=K)
C_y = np.random.randint(0, np.max(X)-20, size=K)
C = np.array(list(zip(C_x, C_y)), dtype = np.float32)  # 聚类中心
print("C.shape: ", C.shape)
# C.shape: (3, 2)

C_old = np.zeros(C.shape)
clusters = np.zeros(len(X))  # 各数据点属于的聚类中心
iteration_flag = distance(C, C_old)

tmp = 1
while iteration_flag.any() != 0 and tmp < 20:
    for i in range(len(X)):
        distances = distance(X[i], C)  # 求该点和各聚类中心的距离
        cluster = np.argmin(distances)  # argmin: Returns the indices of the minimum values along an axis.
        clusters[i] = cluster

    C_old = copy.deepcopy(C)

    for i in range(K):
        points = [X[j] for j in range(len(X)) if clusters[j] == i]
        C[i] = np.mean(points, axis = 0)

    print('循环次数 %d 次' % tmp)
    tmp += 1
    iteration_flag = distance(C, C_old)
    print("新中心与旧中心点的距离:", iteration_flag)

colors = ['r', 'g', 'b', 'y', 'c', 'm']
fig, ax = plt.subplots()

for i in range(K):
    points = np.array([X[j] for j in range(len(X)) if clusters[j] == i])
    ax.scatter(points[:, 0], points[:, 1], s = 7, c = colors[i])
ax.scatter(C[:, 0], C[:, 1], marker='*', s = 200, c = 'black')
plt.show()

效果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是丝豆呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值