我目前正在查看scikit learn
preprocessing
个功能。
我想知道我是否可以遍历预定义的预处理功能列表,这样我就不必完整地写出每个功能的设置代码。
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 notebook
中的Azure ML studio
。{/ p>
答案 0 :(得分: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]