Transform a non callable function into a callable function

108 Views Asked by At

To explain: I use optuna on 5 classifier who are store in a dictionary.

To select one model, I use this:

 models={"CatBoostClassifier":CatBoostClassifier,"DecisionTreeClassifier":DecisionTreeClassifier....}
 for i in range(len(list(models))):
        model=list(models.values())[i]
        name=list(models.keys())[i]

After using optuna, I would like, for example, to transform CatBoostClassifier() into a callable function in order to write something like that:

    sampler = TPESampler(seed=1)
        study = optuna.create_study(study_name=model, direction="maximize", sampler=sampler)
        study.optimize(objective, n_trials=100)

        trial = study.best_trial

        model = model(**trial.params, verbose=False)
        model.fit(X_train, y_train)

How could I do?? This make me an callable error:

    model = model(**trial.params, verbose=False)
    TypeError: 'CatBoostClassifier' object is not callable

Thanks a lot

1

There are 1 best solutions below

5
Bill On

It looks like you want to programmatically build classifier models with parameter values from a dictionary called trial.params. Am I right?

In which case, does this work?

for name, model_class in models.items():

    ...

    model = model_class(**trial.params, verbose=False)
    model.fit(X_train, y_train)

    ...

When you execute CatBoostClassifier() it returns an instance of the class, which you then tried to call. I think what you wanted was the class itself which is CatBoostClassifier.