python,分别训练线性回归、回归决策树,预测对比,使用1000个【0.0,10】之间的数据,让模型预测,画出预测值线图
时间: 2024-11-15 12:27:18 浏览: 6
在Python中,我们可以使用两个流行的机器学习库来训练线性回归和回归决策树模型:scikit-learn (sklearn) 和 matplotlib 来绘制预测值线图。以下是简单的步骤:
1. **导入所需的库**:
```python
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
import matplotlib.pyplot as plt
```
2. **生成随机数据**:
```python
# 生成1000个0.0到10之间的随机数作为特征X和目标值y
np.random.seed(42)
X = np.random.rand(1000, 1) * 10
y = 5 + 2 * X + np.random.randn(1000, 1).astype(np.float64) # 线性关系加上噪声
```
3. **拆分数据集(训练集和测试集)**:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. **训练线性回归模型**:
```python
lin_reg = LinearRegression()
lin_reg.fit(X_train, y_train)
```
5. **训练回归决策树模型**:
```python
tree_reg = DecisionTreeRegressor(random_state=42)
tree_reg.fit(X_train, y_train)
```
6. **预测并画图**:
```python
# 预测值
lin_predictions = lin_reg.predict(X_test)
tree_predictions = tree_reg.predict(X_test)
# 绘制线图
plt.figure(figsize=(8, 6))
plt.scatter(X_test, y_test, label='实际值')
plt.plot(X_test, lin_predictions, color='blue', linewidth=2, linestyle='-', label='线性回归预测')
plt.plot(X_test, tree_predictions, color='green', marker='o', markersize=4, linestyle=':', label='决策树预测')
plt.xlabel('输入值')
plt.ylabel('预测值')
plt.legend()
plt.title('线性回归与决策树预测比较')
plt.show()
```
阅读全文