0

我目前正在看scikit learnpreprocessing功能。如何使用for循环在python3中使用不同的预处理函数?

我想知道是否可以遍历预定义的预处理函数列表,以便我不必为每个函数完整写出设置代码。

E.g.对于一个功能的代码:

T = preprocessing.MinMaxScaler() 
X_train = T.fit_transform(X_train) 
X_test = T.transform(X_test) 

我试图遍历一个预定义列表中,以便使用不同的预处理功能:

pre_proc = ['Normalizer','MaxAbsScaler','MinMaxScaler','KernelCenterer', 'StandardScaler'] 

    for proc in pre_proc: 
     T = 'preprocessing.'+ proc +'()' 
     X_train = T.fit_transform(X_train) 
     X_test = T.transform(X_test) 

目前,这是产生这并不奇怪的情况如下:

--> 37 X_train = T.fit_transform(X_train) 

     38 X_test = T.transform(X_test) 

     39  for i in np.arange(startpt_c,endpt_c, step_c): 

     AttributeError: 'str' object has no attribute 'fit_transform' 

我想我需要有字符串作为正确的对象类型,然后调用该方法即有它识别为一个函数。

有没有办法可以做到这一点,满足我使用循环的目标?

设置:Windows 8,64 bit机器运行Python 3通过Jupyter notebookAzure ML studio

+3

创建一个实际功能列表? 'pre_proc = [preprocessing.Normalizer,preprocessing.MaxAbsScalar,preprocessing.MinMaxScalar,...]'? –

+1

列出不像'[Normalizer(),MaxAbsScaler(),MinMaxScaler(),KernelCenterer(),...]等名称的实例。你甚至可以使用'dict'作为名字。 –

+0

此外,将循环内部的名称'X_test'和'X_train'更改为其他内容,因为它会在下次迭代循环时产生错误。 –

回答

1

问题就出在这行代码

pre_proc = ['Normalizer','MaxAbsScaler','MinMaxScaler','KernelCenterer', ... 

你在做什么这里创建列表pre_proc这基本上只是一个字符串列表中。 Python不知道你实际上是否意味着它们是功能。因此,当您尝试使用T = 'preprocessing.'+ proc +'()'时,python会抛出一个错误并说,T是一个字符串,并且没有方法,如fit_transform。因此,不要使用字符串,而要使用实际的函数名称,即不要将它们放在引号中。像这样使用它们 -

pre_proc = [preprocessing.Normalizer, preprocessing.MaxAbsScalar, preprocessing.MinMaxScalar, preprocessing.KernelCenterer, preprocessing.StandardScaler]