matplotlib线性回归
时间: 2024-10-18 14:01:04 浏览: 37
Matplotlib是一个强大的数据可视化库,在Python中,我们可以使用它结合Scikit-Learn创建线性回归图表。以下是一个基本的例子:
首先,确保已经安装了`matplotlib`、`numpy`和`scikit-learn`库。然后,你可以通过以下步骤创建一个线性回归图:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# 生成随机数据
X, y = make_regression(n_samples=50, n_features=1, noise=20) # 创建一条直线的数据
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练线性回归模型
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# 预测
y_pred = regressor.predict(X_test)
# 绘制原始数据点和拟合线
plt.scatter(X, y, color='blue') # 原始数据点
plt.plot(X_test, y_pred, color='red', linewidth=2) # 拟合线
# 添加标题和标签
plt.title("Linear Regression with Matplotlib")
plt.xlabel("Feature")
plt.ylabel("Target")
# 显示图形
plt.show()
阅读全文
相关推荐


















