Search code examples
pythonscikit-learnpython-importcode-readability

Import module based on string


I get a string (model_name) that is indicating what model should be used, For example LinearRegression or RANSACRegression.

So for example if model_name=="LinearRegression", I would need to import this module and to assign it to the model like this:

from sklearn.linear_model import LinearRegression 
model=LinearRegression()

same if model_name=="RANSACRegression":

from sklearn.linear_model import RANSACRegression 
model=RANSACRegression()

one can assume that all the models I get are in sklearn.linear_model.

Is there a good way to assign the model, without an ugly if...else?

I've looked into importlib - but didn't find a good way to use it in my case.


Solution

  • Well, I found something that works, don't know if it is the best or cleanest solution, but better then if...else:

    linear_model=getattr(__import__('sklearn'),'linear_model')
    curr_method=getattr(linear_model,model_name)
    model=curr_method()