我下面的解决方案是基于RANSAC算法的。它是将一个数学模型(如直线)拟合到含有大量离群值的数据的方法。在
RANSAC是来自robust regression字段的一种特定方法。在
我下面的解决方案首先符合RANSAC的一条线。然后从数据集中删除靠近这条线的数据点(这与保留离群值相同),再次拟合RANSAC,删除数据等,直到只剩下很少的点。在
这种方法总是有与数据相关的参数(例如噪声级或线路的接近度)。在下面的解决方案中,MIN_SAMPLES和residual_threshold是参数,可能需要对数据结构进行一些调整:import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
MIN_SAMPLES = 3
x = np.linspace(0, 2, 100)
xs, ys = [], []
# generate points for thee lines described by a and b,
# we also add some noise:
for a, b in [(1.0, 2), (0.5, 1), (1.2, -1)]:
xs.extend(x)
ys.extend(a * x + b + .1 * np.random.randn(len(x)))
xs = np.array(xs)
ys = np.array(ys)
plt.plot(xs, ys, "r.")
colors = "rgbky"
idx = 0
while len(xs) >