检测多维数据中的空隙

问题描述

如何检测多维(包括一维案例)数据中的空洞?检测我的意思是找到它们的边界。

一个简单的例子:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(-1,1,(500,2))
x = x[np.apply_along_axis(lambda t: np.linalg.norm(t) > 0.5,x),:]
plt.scatter(x[:,0],x[:,1])

enter image description here

解决方法

一种简单的方法是使用直方图。

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(-1,1,(500,2))
x = x[np.apply_along_axis(lambda t: np.linalg.norm(t) > 0.5,x),:]

bins,hist = np.histogramdd(x)

th = 0
axis0_M,axis0_m = hist[0][1:][np.bitwise_or.reduce(bins<=th,axis=1)][0],hist[0][1:][np.bitwise_or.reduce(bins<=th,axis=1)][-1]
axis1_M,axis1_m = hist[1][1:][np.bitwise_or.reduce(bins<=th,axis=0)][0],hist[1][1:][np.bitwise_or.reduce(bins<=th,axis=0)][-1]

plt.vlines(x=[axis0_M,axis0_m],ymin=-x[:,0].max(),ymax=x[:,0].max())
plt.hlines(y=[axis1_M,axis1_m],xmin=-x[:,1].max(),xmax=x[:,1].max())

plt.scatter(x[:,0],x[:,1])
plt.show()

您可能可以通过调整直方图的 bin 宽度并使用不同的阈值来获得更好的结果。