Last active
June 23, 2021 01:14
-
-
Save asukaminato0721/173f9af89a9fe253d1b8a0ca93c3d872 to your computer and use it in GitHub Desktop.
k-medoids without numpy, 无第三方库的实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import dist | |
from pathlib import Path | |
from random import choice, sample | |
from typing import List, Tuple | |
Point = Tuple[float, ...] | |
def kmedoids(点集: List[Point], k: int): | |
初始点集合 = sample(点集, k) | |
结果字典 = {i: [x] for i, x in enumerate(初始点集合)} | |
代表字典 = dict(enumerate(初始点集合)) | |
样本点的集合 = set(点集) - set(初始点集合) | |
for 点 in 样本点的集合: | |
最近的编号 = min(range(k), key=lambda i: dist(点, 代表字典[i])) | |
结果字典[最近的编号].append(点) | |
替换后的点 = min( | |
结果字典[最近的编号], | |
key=lambda p: sum(dist(p, pi) for pi in 结果字典[最近的编号]), | |
) | |
代表字典[最近的编号] = 替换后的点 | |
return 结果字典 | |
if __name__ == "__main__": | |
def 读取文件(): | |
with open(Path(__file__).parent.absolute() / "data.txt") as 文件: | |
yield from (tuple(map(float, 每一行.split())) for 每一行 in 文件) | |
print(kmedoids(list(读取文件()), 5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment