线性回归模型可能会受到离群值的严重影响。在某些情况下,一小部分数据可能会对估计的模型系数有很大的影响。除了淘汰离群值之外,这里利用RANSAC拟合稳健的回归模型
迭代RANSAC算法如下:
1.随机选择一定数量的样本作为内点来拟合模型。
2.用模型测试所有其他的点,把落在用户给定容限范围内的点放入内点集。
3.调整模型中使用的所有的内点。
4.用内点重新拟合模型。
5.评估模型预测结果与内点集相比较的误差。
6.如果性能达到用户定义的阈值或指定的迭代数,则终止;否则返回到步骤1。
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RANSACRegressor
import matplotlib.pyplot as plt
df = pd.read_csv('xxx\\housing.data.txt',
header=None,
sep='\s+')
df.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS',
'NOX', 'RM', 'AGE', 'DIS', 'RAD',
'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
print(df.head())
X = df[['RM']].values
y = df['MEDV'].values
ransac = RANSACRegressor(LinearRegression(),
max_trials=100, # 最大迭代次数为100
min_samples=50, # 随机选择样本的最低数量至少为50
loss='absolute_loss', # 计算拟合线和采样点之间的绝对垂直距离
residual_threshold=5.0, # 只允许与拟合线垂直距离在5个单位以内的采样点被包括在内点集
random_state=0)
ransac.fit(X, y)
inlier_mask = ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
line_X = np.arange(3, 10, 1)
line_y_ransac = ransac.predict(line_X[:, np.newaxis])
plt.scatter(X[inlier_mask], y[inlier_mask],
c='steelblue', edgecolor='white',
marker='o', label='Inliers')
plt.scatter(X[outlier_mask], y[outlier_mask],
c='limegreen', edgecolor='white',
marker='s', label='Outliers')
plt.plot(line_X, line_y_ransac, color='black', lw=2)
plt.xlabel('Average number of rooms [RM]')
plt.ylabel('Price in $1000s [MEDV]')
plt.legend(loc='upper left')
#plt.savefig('images/10_08.png', dpi=300)
plt.show()
print('Slope: %.3f' % ransac.estimator_.coef_[0])
print('Intercept: %.3f' % ransac.estimator_.intercept_)
运行结果:
CRIM ZN INDUS CHAS NOX … TAX PTRATIO B LSTAT MEDV
0 0.00632 18.0 2.31 0 0.538 … 296.0 15.3 396.90 4.98 24.0
1 0.02731 0.0 7.07 0 0.469 … 242.0 17.8 396.90 9.14 21.6
2 0.02729 0.0 7.07 0 0.469 … 242.0 17.8 392.83 4.03 34.7
3 0.03237 0.0 2.18 0 0.458 … 222.0 18.7 394.63 2.94 33.4
4 0.06905 0.0 2.18 0 0.458 … 222.0 18.7 396.90 5.33 36.2
[5 rows x 14 columns]
Slope: 10.735
Intercept: -44.089
运行结果图: