2013-06-04 02:35:25 +08:00
|
|
|
"""
|
|
|
|
|
===========================================
|
|
|
|
|
Robust linear model estimation using RANSAC
|
|
|
|
|
===========================================
|
|
|
|
|
|
|
|
|
|
In this example we see how to robustly fit a linear model to faulty data using
|
|
|
|
|
the RANSAC algorithm.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
import numpy as np
|
|
|
|
|
from matplotlib import pyplot as plt
|
|
|
|
|
|
2013-09-30 23:15:07 +08:00
|
|
|
from sklearn import linear_model, datasets
|
2013-06-04 02:35:25 +08:00
|
|
|
|
|
|
|
|
|
2013-09-30 23:15:07 +08:00
|
|
|
n_samples = 1000
|
|
|
|
|
n_outliers = 50
|
2013-06-04 02:35:25 +08:00
|
|
|
|
|
|
|
|
|
2013-09-30 23:15:07 +08:00
|
|
|
X, y, coef = datasets.make_regression(n_samples=n_samples, n_features=1,
|
|
|
|
|
n_informative=1, noise=10,
|
|
|
|
|
coef=True, random_state=0)
|
2013-06-04 02:35:25 +08:00
|
|
|
|
2013-09-30 23:15:07 +08:00
|
|
|
# Add outlier data
|
|
|
|
|
np.random.seed(0)
|
|
|
|
|
X[:n_outliers] = 3 + 0.5 * np.random.normal(size=(n_outliers, 1))
|
|
|
|
|
y[:n_outliers] = -3 + 10 * np.random.normal(size=n_outliers)
|
2013-06-04 02:35:25 +08:00
|
|
|
|
|
|
|
|
# Fit line using all data
|
|
|
|
|
model = linear_model.LinearRegression()
|
|
|
|
|
model.fit(X, y)
|
|
|
|
|
|
|
|
|
|
# Robustly fit linear model with RANSAC algorithm
|
2013-10-18 18:18:05 +08:00
|
|
|
model_ransac = linear_model.RANSACRegressor(linear_model.LinearRegression())
|
2013-09-26 22:15:59 +08:00
|
|
|
model_ransac.fit(X, y)
|
|
|
|
|
inlier_mask = model_ransac.inlier_mask_
|
2013-09-26 22:02:18 +08:00
|
|
|
outlier_mask = np.logical_not(inlier_mask)
|
2013-06-04 02:35:25 +08:00
|
|
|
|
2013-09-30 23:15:07 +08:00
|
|
|
# Predict data of estimated models
|
|
|
|
|
line_X = np.arange(-5, 5)
|
2013-06-04 02:35:25 +08:00
|
|
|
line_y = model.predict(line_X[:, np.newaxis])
|
2013-09-26 22:15:59 +08:00
|
|
|
line_y_ransac = model_ransac.predict(line_X[:, np.newaxis])
|
2013-06-04 02:35:25 +08:00
|
|
|
|
2013-09-30 23:15:07 +08:00
|
|
|
# Compare estimated coefficients
|
2014-02-02 19:52:31 +08:00
|
|
|
print("Estimated coefficients (true, normal, RANSAC):")
|
|
|
|
|
print(coef, model.coef_, model_ransac.estimator_.coef_)
|
2013-09-30 23:15:07 +08:00
|
|
|
|
2015-10-22 20:12:06 +08:00
|
|
|
lw = 2
|
|
|
|
|
plt.scatter(X[inlier_mask], y[inlier_mask], color='yellowgreen', marker='.',
|
|
|
|
|
label='Inliers')
|
|
|
|
|
plt.scatter(X[outlier_mask], y[outlier_mask], color='gold', marker='.',
|
|
|
|
|
label='Outliers')
|
|
|
|
|
plt.plot(line_X, line_y, color='navy', linestyle='-', linewidth=lw,
|
|
|
|
|
label='Linear regressor')
|
|
|
|
|
plt.plot(line_X, line_y_ransac, color='cornflowerblue', linestyle='-',
|
|
|
|
|
linewidth=lw, label='RANSAC regressor')
|
2013-09-30 23:15:07 +08:00
|
|
|
plt.legend(loc='lower right')
|
2013-06-04 02:35:25 +08:00
|
|
|
plt.show()
|