0
点赞
收藏
分享

微信扫一扫

K-Means

流计算Alink 2022-03-30 阅读 39

代码:

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()

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

举报

相关推荐

0 条评论