python - AttributeError:“LGBMRegressor”对象没有属性“feature_name_”
问题描述
在使用下面的代码训练模型后,我试图获取特征名称,然后我遇到了这样的错误。
我已经检查了 lightgbm 的文档,lightgbm.LGBMRegressor 具有属性“feature_name_”,
我在 jupyter notebook 上运行它,我的 lightGBM 版本是 2.3.1
我真的不知道,谁能给我一个线索?
from lightgbm import LGBMRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
# load data
iris = load_iris()
data = iris.data
target = iris.target
# split dataset
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2)
# training
gbm = LGBMRegressor(objective='regression', num_leaves=31, learning_rate=0.05, n_estimators=20)
gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5)
# save the model
joblib.dump(gbm, 'loan_model.pkl')
# load the model
gbm = joblib.load('loan_model.pkl')
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration_)
print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5)
# importances and feature_name_
print('Feature importances:', list(gbm.feature_importances_))
print('Feature names',gbm.feature_name_)# this is where went wrong
这是错误日志
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-1-d982fd40dcd0> in <module>
32 print('Feature importances:', list(gbm.feature_importances_))
33
---> 34 print('Feature names',gbm.feature_name_)
AttributeError: 'LGBMRegressor' object has no attribute 'feature_name_'
非常感谢你!
解决方案
正如github上所说:
feature_name_ 属性最近已合并到 master 中,尚未包含在任何正式版本中。您可以从源代码下载 nightly build 或安装
请注意,为了访问功能名称,您必须向回归器传递 pandas df,而不是 numpy 数组:
data = pd.DataFrame(iris.data, columns=iris.feature_names)
因此,考虑到这一点,即使没有feature_name_
属性,您也可以这样做:
iris.feature_names
推荐阅读
- c# - 将 startupuri 更改为派生窗口类
- c# - 多线程实时时钟更新标签
- reactjs - React JS - 高阶组件,挂载时返回函数
- unix - 在 Debian Stretch 上安装 ROS 动力学时遇到问题
- c# - 模拟单元测试的管理控制器
- java - OutOfMemoryError 堆转储
- css - 我使用 CSS 线性渐变作为背景制作了这些条纹,但它们看起来并不那么清晰。无论是在桌面还是在移动屏幕上
- python-3.x - Python 如何知道所有这些 π 的变体都是同一个变量名?
- python - 将文件转换为字典以计算出现次数
- reactjs - Netlify CMS 无法更新/替换已在 Gatsby.js 中优化的图像