-2

I try to update my classifier function with for loop, but ".i" could not be applied.

clf = XGBClassifier(base_score=None, booster=None, colsample_bylevel=None,
              colsample_bynode=None, colsample_bytree=0.5, gamma=0.1,
              gpu_id=None, importance_type='gain', interaction_constraints=None,
              learning_rate=101, max_delta_step=None, max_depth=2,
              min_child_weight=3, missing=nan, monotone_constraints=None,
              n_estimators=100, n_jobs=None, num_parallel_tree=None,
              objective='binary:logistic', random_state=None, reg_alpha=None,
              reg_lambda=None, scale_pos_weight=None, subsample=None,
              tree_method=None, validate_parameters=False, verbosity=None)


d = {'learning_rate': [0.2], 'colsample_bytree': [0.5],'gamma' : [0.3] }
m = pd.DataFrame(data=d)

parameters = ['learning_rate', 'colsample_bytree', 'gamma']

for i  in parameters:
    clf.i = m[i][0]

My expectation: Switch of parameters with new values.

AMC
  • 2,642
  • 7
  • 13
  • 35
  • _but ".i" could not be applied._ Are you getting an error? – AMC Apr 12 '20 at 20:58
  • Does this answer your question? [How do you programmatically set an attribute?](https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute) – AMC Apr 12 '20 at 20:59

3 Answers3

1

you can try to use setattr. https://docs.python.org/3/library/functions.html#setattr

in your example, you'll use:

for i  in parameters:
    setattr(clf, i, m[i][0]) 
0

You'll want to use setaddr: https://docs.python.org/3/library/functions.html#setattr

The syntax you provided was not valid, but this is why the setattr function exists. To allow you to pass a string in to represent the attribute, and return the value from the found attribute.

For example

setattr(clf, i, m[i][0])
StevenPG
  • 311
  • 4
  • 16
  • Isn't it `setattr`, not `setaddr` ? – AMC Apr 12 '20 at 21:00
  • Correct, editing my post! I'm used to using getattr, it's inconsistent throughout my whole answer. Thanks for the call-out. The documentation link is the one that is correct! – StevenPG Apr 12 '20 at 21:05
0

You can use setattr to set an object attribute:

for i  in parameters:
    setattr(clf, i, m[i][0])

For example:

class CL:
    pass

clf = CL()

parameters = ['learning_rate', 'colsample_bytree', 'gamma']

for i  in parameters:
    setattr(clf, i, 'test' + i)

print(clf.learning_rate)
# 'testlearning_rate'
Mark
  • 90,562
  • 7
  • 108
  • 148