module 'xgboost' has no attribute 'DMatrix'
Asked Answered
B

3

5

I pulled some ML code that ran on kaggle (linux) and tried to run it in a jupyter notebook on a windows machine. Here is the code (some of it):

##### RUN XGBOOST
import xgboost as xgb

print("\nSetting up data for XGBoost ...")
# xgboost params
xgb_params = {
    'eta': 0.037,
    'max_depth': 5,
    'subsample': 0.80,
    'objective': 'reg:linear',
    'eval_metric': 'mae',
    'lambda': 0.8,   
    'alpha': 0.4, 
    'base_score': y_mean,
    'silent': 1
}

#### These lines were causing the folloing error on 9/1/2017:
# AttributeError: module 'xgboost' has no attribute 'DMatrix'
dtrain = xgb.DMatrix(x_train.values, y_train.values)
dtest = xgb.DMatrix(x_test)

num_boost_rounds = 250
print("num_boost_rounds="+str(num_boost_rounds))

# train model
print( "\nTraining XGBoost ...")
model = xgb.train(dict(xgb_params, silent=1), dtrain, 
num_boost_round=num_boost_rounds)

print( "\nPredicting with XGBoost ...")
xgb_pred1 = model.predict(dtest)

print( "\nFirst XGBoost predictions:" )
print(pd.DataFrame(xgb_pred1).head())

Received the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-a63b74bc35c6> in <module>()
     17 #### These lines were causing the folloing error on 9/1/2017:
     18 # AttributeError: module 'xgboost' has no attribute 'DMatrix'
---> 19 dtrain = xgb.DMatrix(x_train.values, y_train.values)
     20 dtest = xgb.DMatrix(x_test)
     21 

AttributeError: module 'xgboost' has no attribute 'DMatrix'

This is odd because I pull xgboost models from linux machines to windows all the time. I can not find any info on how to fix on the internet, so I am wondering if anyone knows how to fix?

Bastogne answered 2/9, 2017 at 5:26 Comment(1)
While the code looks intact to me, I have a question - what is the role of xgb.Dmatrix() here?Prodrome
T
8

We probably have the same problem.

I solved it by telling Python explicitly where to find xgboost library.

The reason is that I have more than one scripts with the name xgboost.py. Python might have imported one of them mistakenly, so that it cannot find the definition of 'DMatrix'.

Here is the command I used:

export PYTHONPATH=~/xgboost/python-package

You should change '~/xgboost/python-package' into the folder where your /xgboost/python-package/setup.py file located.

Transfinite answered 31/10, 2017 at 13:52 Comment(0)
S
1

If your file's name is xgboost, change its name.

Subcartilaginous answered 24/10, 2023 at 13:54 Comment(0)
C
0

Intrestingly but it is really easy;

import xgboost as xgb
Courtnay answered 18/4, 2022 at 21:21 Comment(1)
interesting, simple and effortless answerSwill

© 2022 - 2024 — McMap. All rights reserved.