有没有办法自动从 XGBoost 中提取重要特征并用于预测?

如何解决有没有办法自动从 XGBoost 中提取重要特征并用于预测?


我正在尝试使用 XG Boost 开发预测模型。我的基本想法是开发一个自动预测模型,该模型使用从数据集(700 多行和 90 多列)派生的前 10 个重要特征,并将它们用于值的预测。输入数据每周更新一次,因此应该使用当前周值来预测下周的预测。 我已经从我的 XGBoost 模型中提取了重要的特征,但由于错误而无法自动化。
import xgboost as xgb
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size=0.2,random_state=100)
eval_set = [(X_train,y_train),(X_test,y_test)]
xg_reg = MyXGBRegressor(objective ='reg:squarederror',colsample_bytree = 0.3,learning_rate = 0.01,max_depth = 6,reg_alpha = 15,n_estimators = 1000,subsample = 0.5)
predictions = xg_reg.fit(X_train,early_stopping_rounds=30,eval_metric=["rmse","mae"],eval_set=eval_set,verbose=True)

上面的代码帮助我运行回归器并预测值。以下代码抛出错误

import xgboost as xgb
from xgboost import XGBRegressor

class MyXGBRegressor(XGBRegressor):
    @property
    def coef_(self):

    return None

thresholds = np.sort(xg_reg.feature_importances_)
from sklearn.feature_selection import SelectFromModel



 for thresh in thresholds:
    selection = SelectFromModel(xg_reg,threshold=thresh,prefit = True)
    selected_dataset = selection.transform(X_test)
    feature_idx = selection.get_support()
    feature_name = X.columns[feature_idx]
    selected_dataset = pd.DataFrame(selected_dataset)
    selected_dataset.columns = feature_name

错误如下:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-a42c3ed80da2> in <module>
      3 for thresh in thresholds:
      4     selection = SelectFromModel(xg_reg,prefit = True)
----> 5     selected_dataset = selection.transform(X_test)
      6 
      7 feature_idx = selection.get_support()

~\Anaconda3\lib\site-packages\sklearn\feature_selection\_base.py in transform(self,X)
     86             force_all_finite=not _safe_tags(self,key="allow_nan"),87         )
---> 88         mask = self.get_support()
     89         if not mask.any():
     90             warn("No features were selected: either the data is"

~\Anaconda3\lib\site-packages\sklearn\feature_selection\_base.py in get_support(self,indices)
     50             values are indices into the input feature vector.
     51         """
---> 52         mask = self._get_support_mask()
     53         return mask if not indices else np.where(mask)[0]
     54 

~\Anaconda3\lib\site-packages\sklearn\feature_selection\_from_model.py in _get_support_mask(self)
    186                              ' "prefit=True" while passing the fitted'
    187                              ' estimator to the constructor.')
--> 188         scores = _get_feature_importances(
    189             estimator=estimator,getter=self.importance_getter,190             transform_func='norm',norm_order=self.norm_order)

~\Anaconda3\lib\site-packages\sklearn\feature_selection\_base.py in _get_feature_importances(estimator,getter,transform_func,norm_order)
    189         return importances
    190     elif transform_func == "norm":
--> 191         if importances.ndim == 1:
    192             importances = np.abs(importances)
    193         else:

AttributeError: 'nonetype' object has no attribute 'ndim'

解决方法

问题是 coef_MyXGBRegressor 属性设置为 None。如果您使用 XGBRegressor 而不是 MyXGBRegressor,那么 SelectFromModel 将使用 feature_importances_XGBRegressor 属性并且您的代码将起作用。

import numpy as np
from xgboost import XGBRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectFromModel

# generate some data
X,y = make_regression(n_samples=1000,n_features=5,random_state=100)

# split the data
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=100)

# instantiate the model
model = XGBRegressor(objective="reg:squarederror",colsample_bytree=0.3,learning_rate=0.01,max_depth=6,reg_alpha=15,n_estimators=1000,subsample=0.5)

# fit the model
model.fit(X_train,early_stopping_rounds=30,eval_metric=["rmse","mae"],eval_set=[(X_train,y_train),(X_test,y_test)],verbose=True)

# extract the feature importances
thresholds = np.sort(model.feature_importances_)

# select the features
selection = SelectFromModel(model,threshold=thresholds[2],prefit=True)

feature_idx = selection.get_support()
print(feature_idx)
# array([ True,True,False,False])

selected_dataset = selection.transform(X_test)
print(selected_dataset.shape)
# (200,3)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?