shr*_*dal -1 python random cluster-analysis machine-learning
假设我想取 4 个点簇。每个集群可以在给定的一组 xy 坐标内。簇内的每个点都是随机生成的点。
这些聚类将作为我的 K-Means 聚类问题的输入。我如何使用 Python 做到这一点?
这可能会给你一些想法:
from random import random
import math
def rand_cluster(n,c,r):
"""returns n random points in disk of radius r centered at c"""
x,y = c
points = []
for i in range(n):
theta = 2*math.pi*random()
s = r*random()
points.append((x+s*math.cos(theta), y+s*math.sin(theta)))
return points
Run Code Online (Sandbox Code Playgroud)
此功能可以通过多种方式使用,例如:
def rand_clusters(k,n,r, a,b,c,d):
"""return k clusters of n points each in random disks of radius r
where the centers of the disk are chosen randomly in [a,b]x[c,d]"""
clusters = []
for _ in range(k):
x = a + (b-a)*random()
y = c + (d-c)*random()
clusters.extend(rand_cluster(n,(x,y),r))
return clusters
Run Code Online (Sandbox Code Playgroud)
一个典型的所有看起来像
clusters = rand_clusters(4,50,0.3,0,1,0,1)
Run Code Online (Sandbox Code Playgroud)
这将生成 4 个半径为 50 的簇,0.3其中心在单位正方形中随机选择。典型运行的要点: