python

我需要在原始数据集上运行以准备用于建模的数据集的一系列步骤(函数)。 我想将所有清洗步骤一个接一个地连接起来,并希望将每个步骤用作功能。 它类似于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笔记本上工作。 我总是可以添加新功能/修改功能..而不会影响其他功能。请提出建议。

lixinnan11 回答:python

似乎您可以使用函数来实现这一目标,尽管花哨的时间更少,但功能却从未如此。

假设您有几个预处理步骤,pre_step1pre_step2等。您可以定义一个名为pipeline的函数,并将上一步的返回值提供给下一个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中的生成器函数遍历所有数据集。

本文链接:https://www.f2er.com/3118276.html

大家都在问