如何使用 for 循环在 python3 中使用不同的预处理函数?
How to use different preprocessing functions in python3 using a for loop?
我目前正在查看 scikit learn
的 preprocessing
函数。
我想知道我是否可以遍历预定义的预处理函数列表,这样我就不必为每个函数写出完整的设置代码。
例如一个函数的代码:
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'
我想我需要将字符串作为正确的对象类型,然后调用该方法,即将它识别为一个函数。
有没有一种方法可以满足我 objective 使用循环的需求?
设置:Windows 8
、64 bit
机器 运行 Python 3
通过 Azure ML studio
中的 Jupyter notebook
。
问题出在你这行代码
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]
我目前正在查看 scikit learn
的 preprocessing
函数。
我想知道我是否可以遍历预定义的预处理函数列表,这样我就不必为每个函数写出完整的设置代码。
例如一个函数的代码:
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'
我想我需要将字符串作为正确的对象类型,然后调用该方法,即将它识别为一个函数。
有没有一种方法可以满足我 objective 使用循环的需求?
设置:Windows 8
、64 bit
机器 运行 Python 3
通过 Azure ML studio
中的 Jupyter notebook
。
问题出在你这行代码
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]