西皮:沃罗诺图细胞似乎是从nowh产生的

2024-03-29 14:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究Lloyd iteration,一种在空间中分布点的迭代算法。在每次迭代中,Lloyd算法将每个输入点建立在自己的Voronoi单元中的Voronoi映射,然后将每个点集中在自己的Voronoi单元中。你知道吗

不过,我在Scipy的Voronoi实现中看到了一些奇怪的行为:似乎某些点在某些迭代中不知从何而来地具体化了。下面的图片捕捉到了这种行为。如果仔细观察,您将看到两个新的点和单元出现在地图的中心,在以下几次迭代中:

enter image description here

以下是用于生成Voronoi分布的代码:

from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
import numpy as np
import umap, os

def find_centroid(verts):
  '''Return the centroid of a polygon described by `verts`'''
  area = 0
  x = 0
  y = 0
  for i in range(len(verts)-1):
    step = (verts[i, 0] * verts[i+1, 1]) - (verts[i+1, 0] * verts[i, 1])
    area += step
    x += (verts[i, 0] + verts[i+1, 0]) * step
    y += (verts[i, 1] + verts[i+1, 1]) * step
  if area == 0: area += 0.01
  return np.array([  (1/(3*area))*x,  (1/(3*area))*y  ])

def lloyd_iterate(X):
  voronoi = Voronoi(X, qhull_options='Qbb Qc Qx')
  centroids = []
  for i in voronoi.regions:
    region = voronoi.vertices[i + [i[0]]]
    centroids.append( find_centroid( region ) )
  return np.array(centroids)

def plot(X, name):
  '''Plot the Voronoi map of 2D numpy array X'''
  v = Voronoi(X, qhull_options='Qbb Qc Qx')
  plot = voronoi_plot_2d(v, show_vertices=False, line_colors='y', line_alpha=0.5, point_size=5)
  plot.set_figheight(14)
  plot.set_figwidth(20)
  plt.axis([-10, 10, -10, 10])
  if not os.path.exists('plots'): os.makedirs('plots')
  plot.savefig( 'plots/' + str(name) + '.png' )

# get 1000 observations in two dimensions and plot their Voronoi map
X = np.random.rand(1000, 4)
X = umap.UMAP().fit_transform(X)
plot(X, 0)

# run several iterations, plotting each result
for i in range(20):
  X = lloyd_iterate(X)
  plot(X, i)

是我忽略了什么,还是这里发生了什么有趣的事情?其他人能提供的任何见解都将不胜感激。你知道吗


Tags: inimportforplotosdefstepnp