python 回归分析LinearRegression判断异常数据,并输出离回归曲线最远的点及对应的距离
时间: 2024-03-27 11:35:02 浏览: 7
使用 `sklearn` 中的 `LinearRegression` 可以进行线性回归,并且也可以用来检测异常值。具体实现方法如下:
```python
from sklearn.linear_model import LinearRegression
import numpy as np
# 生成随机数据
np.random.seed(1234)
x = np.random.normal(0, 1, 50)
y = 2*x + np.random.normal(0, 1, 50)
# 训练模型
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)
# 预测结果
y_pred = model.predict(x.reshape(-1, 1))
# 计算每个数据点到回归曲线的距离
resid = y - y_pred
stdev_residuals = np.std(resid)
distance = np.abs(resid) / stdev_residuals
# 找到离回归曲线最远的点及对应的距离
max_distance_index = np.argmax(distance)
max_distance = distance[max_distance_index]
max_distance_x = x[max_distance_index]
max_distance_y = y[max_distance_index]
# 输出结果
print("离回归曲线最远的点是 ({}, {}), 距离为 {}".format(max_distance_x, max_distance_y, max_distance))
```
以上代码将输出离回归曲线最远的点及对应的距离。需要注意的是,这只是一个简单的示例代码,实际应用中还需要根据具体情况对数据进行预处理。