我有一系列步骤(函数),需要在原始数据集上运行以准备用于建模的数据集。 我想将所有清洁步骤一个接一个地连接起来,并将每个步骤用作函数。 它类似于 sklearn Pipeline 函数,但我没有任何拟合或变换函数。
xx = [2,3,4]
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
('double', double(xx)),
('triple', triple(xx))
])
predicted = pipeline.fit(xx).predict(xx)
我尝试使用 functools 中的 reduce 和 lambda 函数 -
from functools import reduce
xx = 4
pipeline = [lambda x: x * 3, lambda x: x + 1, lambda x: x / 2]
val = reduce(lambda x, f: f(x), pipeline, xx)
print(val)
是否有更好的方法来实现这一目标 - 使代码模块化并自动运行多个数据集。截至目前,我在 Jupyter 笔记本上工作。 我总是可以添加新功能/修改功能..而不影响其他人。请提出建议。
最佳答案
看来你可以使用函数来实现这一点,虽然不那么花哨,但功能仍然强大。
假设您有几个预处理步骤,pre_step1
、pre_step2
等。您可以定义一个名为 pipeline
的函数,并提供 feed pipeline
中上一步的返回值到下一个函数。代码片段如下:
def preprocessing_step1(rawdata):
# do something here
return processed_data
def preprocessing_step2(rawdata):
# do something here
return processed_data
def preprocessing_step3(rawdata):
# do something here
return processed_data
def pipeline(rawdata):
# run steps sequentially
data = preprocessing_step1(rawdata)
data = preprocessing_step2(data)
processed_data = preprocessing_step3(data)
return processed_data
如果您觉得这有帮助,我可以向您展示如何使用 Python 中的生成器函数浏览所有数据集。
关于python - python中多个函数的顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58816620/