'How to run build a model dynamically in python?

I have a dataframe that has a column with an alogitthm and hyperparameters all in string format

it looks like this.

id   Alg
------------
1    RandomForestClassifier(max_depth=2, random_state=0)
2    LinearRegression(n_jobs=-1)
3    RandomForestClassifier(n_estimators=750)
4    ExtraTreesClassifier(criterion='entropy')

is there a way I can run the algorithm dynamically?

so my code will be something like this

for strCode in df["Alg"]:
   model = SomeFunction(strCode) # <---------------- strCode should run dynamically so model can be generated
   model.fit(X_train, y_train)


Solution 1:[1]

You might be looking for the eval() function which evaluates the passed string as a python expression.

from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier  # noqa
from sklearn.linear_model import LinearRegression  # noqa

algos = [
    "RandomForestClassifier(max_depth=2, random_state=0)",
    "LinearRegression(n_jobs=-1)",
    "RandomForestClassifier(n_estimators=750)",
    "ExtraTreesClassifier(criterion='entropy')",
]
for strCode in algos:
    model = eval(strCode)  # eval basically executes whatever string it gets
    model.fit(X_train, y_train)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S P Sharan