python实现xgboost回归预测95置信区间可视化
时间: 2023-09-08 14:15:02 浏览: 154
要实现xgboost回归预测的95%置信区间可视化,可以使用Python中的matplotlib库。下面是一个简单的示例代码,可以根据自己的数据进行修改和适应。
首先,导入需要的库:
```python
import numpy as np
import matplotlib.pyplot as plt
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split
```
接下来,生成一些模拟数据:
```python
# 生成模拟数据
np.random.seed(42)
X = np.linspace(-5, 5, 200).reshape(-1, 1)
y = np.sin(X) + np.random.normal(scale=0.1, size=(200, 1))
```
然后,将数据集划分为训练集和测试集:
```python
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接着,使用XGBoost进行拟合:
```python
# 使用XGBoost进行拟合
xgb = XGBRegressor(n_estimators=100, max_depth=3, learning_rate=0.1, random_state=42)
xgb.fit(X_train, y_train)
```
然后,根据测试集数据进行预测,并计算95%置信区间:
```python
# 预测值
y_pred = xgb.predict(X_test)
# 置信区间
std = np.sqrt(np.mean((y_test - y_pred) ** 2))
z = 1.96 # 95%置信区间对应的z值
lower = y_pred - z * std
upper = y_pred + z * std
```
最后,绘制预测结果及置信区间:
```python
# 绘图
plt.scatter(X_test, y_test, label="Test data")
plt.plot(X_test, y_pred, color="r", label="Prediction")
plt.fill_between(X_test.flatten(), lower, upper, color="gray", alpha=0.2, label="95% CI")
plt.legend()
plt.show()
```
运行以上代码,即可得到xgboost回归预测的95%置信区间可视化结果。