Skip to content

Instantly share code, notes, and snippets.

@ylogx
Last active February 16, 2024 14:25
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save ylogx/53fef94cc61d6a3e9b3eb900482f41e0 to your computer and use it in GitHub Desktop.
Save ylogx/53fef94cc61d6a3e9b3eb900482f41e0 to your computer and use it in GitHub Desktop.
XGBoost Incremental Learning
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@StudyExchange
Copy link

Refer to How can I implement incremental training for xgboost?, I have a try, then I get loss.

%%time
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import ShuffleSplit
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error as mse

boston = load_boston()
features = boston.feature_names
X = boston.data
y = boston.target

X = pd.DataFrame(X, columns=features)
y = pd.Series(y, index=X.index)


# split data into training and testing sets
rs = ShuffleSplit(test_size=0.3, n_splits=1, random_state=0)
for train_idx,test_idx in rs.split(X):  # this looks silly
    pass

train_split = round(len(train_idx) / 2)
train1_idx = train_idx[:train_split]
train2_idx = train_idx[train_split:]
X_train = X.loc[train_idx]
X_train_1 = X.loc[train1_idx]
X_train_2 = X.loc[train2_idx]
X_test = X.loc[test_idx]
y_train = y.loc[train_idx]
y_train_1 = y.loc[train1_idx]
y_train_2 = y.loc[train2_idx]
y_test = y.loc[test_idx]

xg_train_0 = xgb.DMatrix(X_train, label=y_train)
xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1)
xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2)
xg_test = xgb.DMatrix(X_test, label=y_test)

num_round = 15
verbose_eval = 5
watch_list = [(xg_test, 'xg_test')]

params = {'objective': 'reg:linear', 'verbose': False}
print('full train\t'); 
model_0 = xgb.train(params, xg_train_0, num_round, watch_list, verbose_eval=verbose_eval)
print('model 1 \t'); 
model_1 = xgb.train(params, xg_train_1, num_round, watch_list, verbose_eval=verbose_eval)
model_1.save_model('model_1.model')
print('model 2 \t'); 
model_2_v1 = xgb.train(params, xg_train_2, num_round, watch_list, verbose_eval=verbose_eval)
print('model 1+2\t, this logs show continue train, but got a test score same to model 1?'); 
model_2_v2 = xgb.train(params, xg_train_2, num_round, watch_list, verbose_eval=verbose_eval, xgb_model=model_1)

params.update({
    'process_type': 'update',
    'updater': 'refresh',
    'refresh_leaf': True,
})
print('model 1+update2\t, this logs do not show continue train, but got a best test score?'); model_2_v2_update = xgb.train(params, xg_train_2, num_round, watch_list, verbose_eval=verbose_eval, xgb_model=model_1)

print('full train\t', mse(model_0.predict(xg_test), y_test)) # benchmark
print('model 1 \t', mse(model_1.predict(xg_test), y_test))  
print('model 2 \t', mse(model_2_v1.predict(xg_test), y_test))  # "before"
print('model 1+2\t', mse(model_2_v2.predict(xg_test), y_test))  # "after"
print('model 1+update2\t', mse(model_2_v2_update.predict(xg_test), y_test))  # "after"

Output:

full train	
[0]	xg_test-rmse:16.9311
[5]	xg_test-rmse:5.36819
[10]	xg_test-rmse:4.41758
[14]	xg_test-rmse:4.28357
model 1 	
[0]	xg_test-rmse:17.078
[5]	xg_test-rmse:6.0592
[10]	xg_test-rmse:5.04216
[14]	xg_test-rmse:4.94968
model 2 	
[0]	xg_test-rmse:16.9631
[5]	xg_test-rmse:6.08084
[10]	xg_test-rmse:5.18633
[14]	xg_test-rmse:5.12085
model 1+2	, this logs show continue train, but got a test score same to model 1?
[0]	xg_test-rmse:4.72028
[5]	xg_test-rmse:4.79626
[10]	xg_test-rmse:4.96232
[14]	xg_test-rmse:4.96374
model 1+update2	, this logs do not show continue train, but got a best test score?
[0]	xg_test-rmse:17.0353
[5]	xg_test-rmse:5.0438
[10]	xg_test-rmse:3.9661
[14]	xg_test-rmse:3.91295
full train	 18.348929164523298
model 1 	 24.499370663166886
model 2 	 26.223108502105553
model 1+2	 24.63867891225536
model 1+update2	 15.311159054248336
CPU times: user 17.1 s, sys: 4.19 s, total: 21.3 s
Wall time: 3.01 s

@Venkatesh-Sreedharan
Copy link

Hey, I am not able to replicate this code as it is. How do you manage to run incremental iterative learning for the first time with the model defined as 'None'. Because xgboost {process_type:'update'} parameter does not allow building of new trees and hence in the very first iteration it breaks as does not have any trees to build upon. Am I missing something here? Please do clarify. This comes up even for one shot iterative learning.

@DataSphereX
Copy link

Hi,

I am also unable to replicate the analogy of this model, for example of a Telecom Churn prediction, as and when a new customer gets added who will I re-use the old model to train the model instead of retraining with complete data.

@karelin
Copy link

karelin commented Oct 2, 2019

Just tried the notebook (xgboost version 0.90). Unfortunately, call to xgb.train (for one shot learning) raises error "XGBoostError: [13:44:55] src/gbm/gbtree.cc:278: Check failed: model_.trees.size() < model_.trees_to_update.size() (0 vs. 0) :"

@trivialfis
Copy link

I ran the gist on master branch and it works fine. Should be fixed with new model IO routines.

@luisvivasg
Copy link

I also got the same error as Karelin. And I this the same as Venkatesh

Check failed: model_.trees.size() < model_.trees_to_update.size() (0 vs. 0) :

I saw somewhere that it is needed to add the number of trees created in the first iteration, however, I cannot get that number. And it is never added in the code above.

@c3-varun
Copy link

Same issue on XGBoost 1.4.0. Has anyone figured this out yet?

@pjbhaumik
Copy link

Hi,
I have found the solution. Per xgboost documentation, the parameter 'update' should be 'updater'... this is a mistake in the notebook above. If you fix this, then you will see the right results.

model = xgb.train({
'learning_rate': 0.007,
'updater':'refresh',
'process_type': 'update',
'refresh_leaf': True,
#'reg_lambda': 3, # L2
'reg_alpha': 3, # L1
'silent': False,
}, dtrain=xgb.DMatrix(x_tr[start:start+batch_size], y_tr[start:start+batch_size]), xgb_model=model)

@marymlucas
Copy link

marymlucas commented Jul 14, 2023

Disregard, I figured it out. I was using handle_unknown='ignore' in OneHotEncoder, but one of the features has too few of a particular category, hence the mismatch.

Thank you for this gist. How can we implement this in a pipeline?

I am unable to test on the Boston dataset as it's been removed from sklearn, but on a different dataset I get a mismatch in number of columns. Even though I use the same pipeline the saved model seems to have one less feature than the new training data and I am unable to figure out why.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment