Creating custom instantiation

Viewed 35

I'm trying to instantiate an object in a custom form, something like this:

from sklearn.linear_model import LinearRegression
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge

class instance:

  def custom_instanciation(self, estimator=None):
    estimator1 = estimator
    print(estimator1)
    print(type(estimator1))

    estimator2 = f"{estimator}"
    print(estimator1)
    print(type(estimator1))

    estimator3 = LinearRegression()
    print(estimator3)
    print(type(estimator3))

Input:

i = instance()
i.custom_instanciation(estimator="LinearRegression()")

OUTPUT:

LinearRegression()
<class 'str'>
LinearRegression()
<class 'str'>
LinearRegression()
<class 'sklearn.linear_model._base.LinearRegression'>

See that only in the last case it works, where, I'm not using what was passed to the method - "LinearRegression"

2 Answers

You can use getattr() function and the name of your module obtained from the sys library to achieve that:

from sklearn.linear_model import LinearRegression
from sklearn.linear_model import ElasticNet
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
import sys

class instance:

  def custom_instanciation(self, estimator=None):
    estimator1 = estimator
    print(estimator1)
    print(type(estimator1))

i = instance()
i.custom_instanciation(estimator=getattr(sys.modules[__name__], "LinearRegression"))

I think you want to pass LinearRegression itself, not a string, as the argument, and let the method call whatever class is passed.

def custom_instantation(self, estimator_class):
    estimator = estimator_class()

Then

i = instance()
i.custom_instanciation(estimator=LinearRegression)
Related