aadcg
aadcg

Reputation: 142

Scikit-learn methods inside functions

I have the following function that uses a specific method of sklearn.preprocessing.

from sklearn import preprocessing
def process (data):
    method = preprocessing.MinMaxScaler()
    tranf = method.fit_transform(data)
    return tranf

What I would like to have is a function that is able to call any method from sklearn.preprocessing. It would look this.

from sklearn import preprocessing
def process (data, whichmethod):
    method = preprocessing.whichmethod()
    tranf = method.fit_transform(data)
    return tranf

Please educate me on python and apologies, since I do get the feeling that this is super simple.

Upvotes: 0

Views: 372

Answers (2)

Bob
Bob

Reputation: 1

I think the problem lies in the limitation of calling a function() by using arguments.

Solution that I can offer as below, by adding if statement; not an efficient one but serves your needs:

from sklearn import preprocessing
def process (data, whichmethod):
    If lower(whichmethod) == lower(StandardScaler):
        method = preprocessing.StandardScaler()
    If lower(whichmethod) == lower(MinMaxScaler):
        method = preprocessing.MinMaxScaler()
    If lower(whichmethod) == lower(QuantileTransformer):
        method = preprocessing.QuantileTransformer()
    #you can add if statement pairing with the class and functions that you want, as much as you need. Very tiring works. But worth it if we work all the time with sklearn.preprocessing
    # the only good thing about this code, you don't need to care about lower-upper case of function. Write minmaxscaler, Minmaxscaler, it will work. 

    tranf = method.fit_transform(data)
    return tranf

Upvotes: 0

FlyingTeller
FlyingTeller

Reputation: 20482

I think it is much easier to pass the correct object already, instead of the name in preprocessing:

from sklearn import preprocessing
def process (data, method):
    tranf = method.fit_transform(data)
    return tranf
process(data, preprocessing.MinMaxScaler()) # how you would reproduce your first example

Upvotes: 2

Related Questions