使用xgboost绘制特征重要性

当我绘制特征重要性时,得到的是一个混乱的图表。我有超过7000个变量。我知道内置函数只选择最重要的变量,但最终的图表难以阅读。这是我完整的代码:

import numpy as npimport pandas as pddf = pd.read_csv('ricerice.csv')array=df.valuesX = array[:,0:7803]Y = array[:,7804]from xgboost import XGBClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scoreseed=0test_size=0.30X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=test_size, random_state=seed)from xgboost import XGBClassifiermodel = XGBClassifier()model.fit(X, Y)import matplotlib.pyplot as pltfrom matplotlib import pyplotfrom xgboost import plot_importancefig1=plt.gcf()plot_importance(model)plt.draw()fig1.savefig('xgboost.png', figsize=(50, 40), dpi=1000)

尽管图表尺寸很大,但图表仍然难以辨认。 xgboost feature importance plot


回答:

有几个要点需要注意:

  1. 要拟合模型,你应该使用训练数据集(X_train, y_train),而不是整个数据集(X, y)。
  2. 你可以使用plot_importance()函数的max_num_features参数来只显示前max_num_features个特征(例如前10个)。

通过对你的代码进行上述修改,并使用一些随机生成的数据,代码和输出如下所示:

import numpy as np# generate some random data for demonstration purpose, use your original dataset hereX = np.random.rand(1000,100)     # 1000 x 100 datay = np.random.rand(1000).round() # 0, 1 labelsfrom xgboost import XGBClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scoreseed=0test_size=0.30X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=test_size, random_state=seed)from xgboost import XGBClassifiermodel = XGBClassifier()model.fit(X_train, y_train)import matplotlib.pylab as pltfrom matplotlib import pyplotfrom xgboost import plot_importanceplot_importance(model, max_num_features=10) # top 10 most important featuresplt.show()

enter image description here

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注