<jupyter_start><jupyter_text>K-means Clustering> 10185101210 陈俊潼K-means 聚类算法的演示。首先定义一个方便打印状态的日志类：<jupyter_code>from datetime import datetime
import os

# Logger and colors
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

class logger:
    @staticmethod
    def __log(msg, level, color=bcolors.ENDC):
        date = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
        with open("log.log", "a+") as f:
            f.write("<{} {}>: {}\n".format(date, level, msg))
        if os.name == "nt":
            print("<{} {}>: {}".format(date, level, msg))
        else:
            print("<{} {}>: {}".format(date, level, color + bcolors.BOLD + msg + bcolors.ENDC))

    @staticmethod
    def info(msg):
        logger.__log(msg, "INFO", bcolors.OKBLUE)

    @staticmethod
    def warn(msg):
        logger.__log(msg, "WARN", bcolors.HEADER)

    @staticmethod
    def error(msg):
        logger.__log(msg, "ERROR", bcolors.FAIL)<jupyter_output><empty_output><jupyter_text>初始化初始化参数，并导入必要的库。聚类所需的数据存储在 data.txt 中，每一行为坐标的 x 和 y 值，以逗号隔开。<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# HiDPI Support
mpl.rcParams['figure.dpi'] = 240

# PARAMETERS
K_MIN = 2
K_MAX = 5

# Stop condition
MAX_EPOCHS = 10
data = np.empty((0, 2), float)

with open("data.txt", "r") as f:
    lines = f.readlines()
    for oneLine in lines:
        (x, y) = oneLine.replace("\n", "").split(" ")
        data = np.append(data, np.array([[x, y]]), axis=0)<jupyter_output><empty_output><jupyter_text>定义初始化 k 个核的函数：<jupyter_code>def init_centroids(k):
    row_rand_array = np.arange(data.shape[0])
    np.random.shuffle(row_rand_array)
    cores = data[row_rand_array[0:k]]
    return cores<jupyter_output><empty_output><jupyter_text>首先对于 K = 2 的情况，随机生成两个点作为聚类中心。<jupyter_code>centroids = init_centroids(2)
plt.scatter(data[:, 0], data[:, 1])
plt.scatter(centroids[:, 0], centroids[:, 1], c='r')
plt.show()<jupyter_output><empty_output><jupyter_text>接下来开始进行聚类：<jupyter_code># get the JSAnimation import at https://github.com/jakevdp/JSAnimation
from JSAnimation import examples
examples.basic_animation()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16278046634403873, 'fraction_numerical': 0.026836779586449627, 'mean_word_length': 3.975929978118162, 'pattern_counts': {'":': 1, '<': 24, '<?xml version=': 0, '>': 25, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '344551', 'license': 'MIT', 'n_tokens_mistral': 992, 'n_tokens_neox': 963, 'n_words': 170, 'path': 'Course/ML/kmeans/.ipynb_checkpoints/kmeans-checkpoint.ipynb', 'repo_name': 'Flento/LearningRepo', 'size': '2273'}