xgboost 产生新特征,plot_tree

# coding: utf-8
# https://blog.youkuaiyun.com/zhangf666/article/details/70183788
# https://blog.youkuaiyun.com/bryan__/article/details/51769118

from sklearn.model_selection import train_test_split
from pandas import DataFrame
from sklearn import metrics
from sklearn.datasets  import make_hastie_10_2
from xgboost.sklearn import XGBClassifier
import xgboost as xgb


# (1). get datasets
X, y = make_hastie_10_2(random_state=0)
X = DataFrame(X)
y = DataFrame(y)
y.columns={"label"}
label={-1:0,1:1}
y.label=y.label.map(label)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)#划分数据集
y_train.head()


#(2).XGBoost两种接口定义
# XGBoost自带接口
params={
    'eta': 0.3,
    'max_depth':3,   
    'min_child_weight':1,
    'gamma':0.3, 
    'subsample':0.8,
    'colsample_bytree':0.8,
    'booster':'gbtree',
    'objective': 'binary:logistic',
    'nthread':12,
    'scale_pos_weight': 1,
    'lambda':1,  
    'seed':27,
    'silent':0 ,
    'eval_metric': 'auc'
}
d_train = xgb.DMatrix(X_train, label=y_train)
d_valid = xgb.DMatrix(X_test, label=y_test)
d_test = xgb.DMatrix(X_test)
watchlist = [(d_train, 'train'), (d_valid, 'valid')]

# sklearn接口
clf = XGBClassifier(
    n_estimators=30,#三十棵树
    learning_rate =0.3,
    max_depth=3,
    min_child_weight=1,
    gamma=0.3,
    subsample=0.8,
    colsample_bytree=0.8,
    objective= 'binary:logistic',
    nthread=12,
    scale_pos_weight=1,
    reg_lambda=1,
    seed=27)

model_bst = xgb.train(params, d_train, 30, watchlist, early_stopping_rounds=500, verbose_eval=10)
model_sklearn=clf.fit(X_train, y_train)

y_bst= model_bst.predict(d_test)
y_sklearn= clf.predict_proba(X_test)[:,1]

print("XGBoost_自带接口    AUC Score : %f" % metrics.roc_auc_score(y_test, y_bst))
print("XGBoost_sklearn接口 AUC Score : %f" % metrics.roc_auc_score(y_test, y_sklearn))


# (3).生成两组新特征
print("原始train大小:",X_train.shape)
print("原始test大小:",X_test.shape)

# XGBoost自带接口生成的新特征
train_new_feature= model_bst.predict(d_train, pred_leaf=True)
test_new_feature= model_bst.predict(d_test, pred_leaf=True)
train_new_feature1 = DataFrame(train_new_feature)
test_new_feature1 = DataFrame(test_new_feature)
print("新的特征集(自带接口):",train_new_feature1.shape)
print("新的测试集(自带接口):",test_new_feature1.shape)

# sklearn接口生成的新特征
train_new_feature= clf.apply(X_train)#每个样本在每颗树叶子节点的索引值
test_new_feature= clf.apply(X_test)
train_new_feature2 = DataFrame(train_new_feature)
test_new_feature2 = DataFrame(test_new_feature)
print("新的特征集(sklearn接口):",train_new_feature2.shape)
print("新的测试集(sklearn接口):",test_new_feature2.shape)  

train_new_feature1.head()
train_new_feature2.head()


# (4).基于新特征训练、预测

#用两组新的特征分别训练,预测
#用 sklearn 接口生成的新特征训练
new_feature1=clf.fit(train_new_feature1, y_train)
y_new_feature1= clf.predict_proba(test_new_feature1)[:,1]
#用 sklearn 接口生成的新特征训练
new_feature2=clf.fit(train_new_feature2, y_train)
y_new_feature2= clf.predict_proba(test_new_feature2)[:,1]

print("sklearn 接口生成的新特征预测结果 AUC Score : %f" % metrics.roc_auc_score(y_test, y_new_feature1))
print("sklearn 接口生成的新特征预测结果 AUC Score : %f" % metrics.roc_auc_score(y_test, y_new_feature2))


# (5).Plotting API画图
from xgboost import plot_tree
from xgboost import plot_importance
import matplotlib.pyplot as plt
from graphviz import Digraph
import pydot

#model_bst = xgb.train(params, d_train, 30, watchlist, early_stopping_rounds=500, verbose_eval=10)
#model_sklearn=clf.fit(X_train, y_train)

#model_bst
xgb.plot_tree(model_bst, num_trees=0)   # xgb.to_graphviz(model_bst, num_trees=0)
plot_importance(model_bst)
plt.show()

#model_sklearn:
plot_tree(model_sklearn)
plot_importance(model_sklearn)
plt.show()

'''
画图时出现关于 GraphViz 错误,windows system
0. Install python graphviz package: pip install graphviz
1. Download and install graphviz-2.38.msi https://graphviz.gitlab.io/_pages/Download/Download_windows.html
2. Set the path variable
Control Panel > System and Security > System > Advanced System Settings > Environment Variables > Path > Edit add 'C:\Program Files (x86)\Graphviz2.38\bin'
Add C:\Program Files (x86)\Graphviz2.38\bin to User path
Add C:\Program Files (x86)\Graphviz2.38\bin\dot.exe to System Path
3. Restart your currently running application that requires the path

参考:
https://stackoverflow.com/questions/18438997/why-is-pydot-unable-to-find-graphvizs-executables-in-windows-8
https://stackoverflow.com/questions/35064304/runtimeerror-make-sure-the-graphviz-executables-are-on-your-systems-path-aft
'''
<think>好的,我现在需要帮用户解决如何用matplotlib和xgboostplot_importance方法绘制基于gain的特征重要性图表的问题。首先,我得回忆一下xgboost的相关知识。XGBoost有一个plot_importance函数,可以用来可视化特征的重要性。用户提到要基于gain,也就是信息增益,所以需要确认plot_importance的参数设置是否正确。 我记得plot_importance的默认参数是'weight',也就是使用特征被用来分裂的次数。要改成gain的话,需要显式设置参数importance_type='gain'。不过,可能还需要在训练模型的时候确保记录了gain的信息。例如,在训练XGBoost模型时,是否需要在参数中设置什么?通常来说,XGBoost默认会计算这些指标,只要在训练时启相应的选项。 然后,用户想用matplotlib来调整图表。虽然plot_importance本身会返回一个matplotlib的axis对象,但可能需要手动调整图表样式,比如字体大小、图形尺寸等。用户提供的示例代码可能需要导入必要的库,比如xgboost,matplotlib,以及加载数据、训练模型的部分。 接下来,我需要参考用户提供的引用内容。引用[2]提到使用xgb.plot_tree来可视化树的结构,而引用[1]和[3]涉及特征重要性的其他方法,比如permutation importance和ALE plots。但这里用户明确需要的是xgboostplot_importance方法,所以重点应该放在这上面。 可能的步骤是:加载数据,训练XGBoost模型,调用plot_importance并设置importance_type为'gain',然后用matplotlib调整图表。需要注意的是,可能需要先安装xgboost库,并确保版本支持该参数。 另外,用户可能遇到的常见问题包括:特征名称没有正确显示,图表样式不符合预期,或者gain值没有正确计算。因此,在示例代码中,应该展示如何设置特征名称,如何调整图表的大小、标题、标签等。 例如,在加载数据后,分割成训练集和测试集,训练模型时可能需要设置objective参数,比如回归任务用'reg:squarederror',分类用'binary:logistic'。然后,在plot_importance的时候,指定importance_type='gain',并传入训练好的模型。最后,使用matplotlib的plt.show()来显示图表。 可能还需要注意,plot_importance返回的轴对象可以进一步用matplotlib的方法调整,比如设置标题,调整子图布局,或者保存图像为文件。 现在,我需要整理这些思路,写出一个结构清晰的步骤说明,并提供示例代码,确保代码中正确使用参数,并且处理了特征名称等问题。同时,根据用户的要求,生成相关问题,比如关于其他重要性类型,调整图表样式,或者处理相关特征的问题。</think>### 使用XGBoost和Matplotlib绘制特征重要性图(基于Gain) #### 1. 数据准备与模型训练 首先加载数据集并训练XGBoost模型。以Iris数据集为例: ```python import xgboost as xgb from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # 加载数据 iris = load_iris() X, y = iris.data, iris.target feature_names = iris.feature_names # 拆分数据集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 训练模型(显式启用特征重要性计算) model = xgb.XGBClassifier(objective='multi:softprob') model.fit(X_train, y_train) ``` #### 2. 绘制特征重要性图 使用`plot_importance`方法并指定`importance_type='gain'`: ```python # 创建画布 fig, ax = plt.subplots(figsize=(10, 6)) # 绘制图表 xgb.plot_importance( model, ax=ax, importance_type='gain', # 关键参数 title='Feature Importance (Gain)', xlabel='Gain', show_values=False, height=0.8, color='#1f77b4', grid=False ) # 设置特征名称 ax.set_yticklabels(feature_names) # 调整布局 plt.tight_layout() plt.show() ``` #### 3. 关键参数说明 - `importance_type`: 支持`weight`(分裂次数)、`gain`(平均增益)、`cover`(样本覆盖度) - `max_num_features`: 控制显示的特征数量(默认显示全部) - `show_values`: 是否显示具体数值 - `title/xlabel`: 自定义标题和坐标轴标签 #### 4. 输出结果解读 图表将显示特征按信息增益排序的结果,条形长度表示该特征在树分裂时带来的平均信息增益值[^2]。 ![示例图表](https://via.placeholder.com/800x400.png?text=Feature+Importance+Chart+Example)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值