Skip to main content
 首页 » 编程设计

python之使用 xgboost 算法预测值

2024年11月01日10daizhj

我已经使用 Xgboost 编写了波士顿房价的代码 这是代码

import treelite 
import xgboost 
from sklearn.datasets import load_boston 
import treelite.runtime     # runtime module 
 
X, y = load_boston(return_X_y=True) 
print('dimensions of X = {}'.format(X.shape)) 
print('dimensions of y = {}'.format(y.shape)) 
 
dtrain = xgboost.DMatrix(X, label=y) 
params = {'max_depth':3, 'eta':1, 'silent':1, 'objective':'reg:linear', 
          'eval_metric':'rmse'} 
bst = xgboost.train(params, dtrain, 20, [(dtrain, 'train')]) 
 
bst.save_model('bst1.model') 
 
bst = xgboost.Booster({'nthread':4}) #init model 
bst.load_model("bst1.model") # load data 
 
#Now I want to make prediction using above model 
 
(Pdb) bst.predict(X,10,20) 
*** AttributeError: 'numpy.ndarray' object has no attribute 'feature_names' 
(Pdb) bst.predict(10,20) 
*** AttributeError: 'int' object has no attribute 'feature_names' 
(Pdb) 

对输入值 10 和 20 进行预测的正确方法是什么?

编辑

在接受了 Adji 的建议之后

(Pdb) bst.predict([[10,20]]) 
*** AttributeError: 'list' object has no attribute 'feature_names' 
(Pdb) bst.predict([10,20]) 
*** AttributeError: 'list' object has no attribute 'feature_names' 

请您参考如下方法:

我觉得你应该尝试改变

10,20 到一个矩阵,或者

[[10,20]](遵循xgb.Dmatrix(...)结果的格式)