使用LinearRegression怎样画出线性回归后的效果图
时间: 2024-04-29 21:22:56 浏览: 9
在使用LinearRegression进行线性回归后,可以使用matplotlib库将预测结果可视化。
示例代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 生成样本数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 5, 7, 9, 11])
# 创建线性回归模型并拟合数据
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)
# 预测结果
y_pred = model.predict(x.reshape(-1, 1))
# 绘制原始数据和预测结果
plt.scatter(x, y, color='blue')
plt.plot(x, y_pred, color='red', linewidth=2)
plt.show()
```
运行后会得到一张图像,其中蓝色的点表示原始数据,红色的线表示线性回归模型的预测结果。
![linear_regression_plot](https://img-blog.csdn.net/20180930154411786?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Rlc3RpbmctYnVpbGRlcg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/75)