您好,关于 sklearn.Pipeline 的两个时间序列自定义转换器的问题

Hello, two questions about sklearn.Pipeline with custom transformer for timeseries

我应该如何修改下面的代码以使其工作:

目标,预测 = pipe.fit_predict(df)

编辑:

target, predicted = pipe.fit_transform(df, df)

我的代码:

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
from sklearn.pipeline import Pipeline 
np.random.seed(1)

rows,cols = 100,1
data = np.random.randint(100, size = (rows,cols))
tidx = pd.date_range('2019-01-01', periods=rows, freq='20min') 
df = pd.DataFrame(data, columns=['num_orders'], index=tidx)
      


class MakeFeatures(BaseEstimator, TransformerMixin):

def __init__(self, X, y = None, max_lag = None, rolling_mean_day = None, rolling_mean_month = None):
    self.X = X.resample('1H').sum()
    self.max_lag = max_lag
    self.rolling_mean_day = rolling_mean_day
    self.rolling_mean_month = rolling_mean_month
        
def fit(self, X, y = None):
    return self

def transform(self, X, y = None):
    data = pd.DataFrame(index = self.X.index)
    data['num_orders'] = self.X['num_orders']
    data['year'] = self.X.index.year
    data['month'] = self.X.index.month
    data['day'] = self.X.index.day
    data['dayofweek'] = self.X.index.dayofweek
    
    data['detrend'] = self.X.shift() - self.X
    
    if self.max_lag:
        for lag in range(1, self.max_lag + 1):
            data['lag_{}'.format(lag)] = data['detrend'].shift(lag)
    if self.rolling_mean_day:
        data['rolling_mean_24'] = data.detrend.shift().rolling(self.rolling_mean_day).mean()
    
    if self.rolling_mean_month:
        data['rolling_mean_24'] = data['detrend'].shift().rolling(self.rolling_mean_month).mean()
    
    if data['year'].mean() == data['year'][1]:
        data = data.drop('year', axis = 1)
    
    data = data.dropna()
    
    y = data.num_orders
    data = data.drop('num_orders', 1)
    
    return data, y

pipe = Pipeline([
                ('features', MakeFeatures(df, df, 2 , 24)),
                ('scaler', StandardScaler())  
    ])

target, predicted = pipe.fit_transform(df, df)  # where ‘Target’ is y - the output from the Class

输出:

ValueError: could not broadcast input array from shape (9,7) into shape (9).

Pipeline 中的每个函数都工作正常。

我可以 运行 MakeFeatures(df, df)StandardScaler().fit_transform(df, df)没问题。

我可以将MakeFeatures(df,df)的乘积插入到StandardScaler中,没有出错。

你不能使用

target, predicted = pipe.fit_predict(df)

使用您定义的管道,因为 fit_predict() 方法只能在估计器也实现了这样的方法的情况下使用。 Reference in documentation

Valid only if the final estimator implements fit_predict.

此外,它只会 return 预测,所以你不能使用 target,predicted = 但应该使用 predicted =

你遇到了错误

ValueError: setting an array element with a sequence.

因为您提供 StandardScaler() 一个 pandas.TimeSeries

这是因为在您的方法调用 pipe.fit_predict(df) 中,您只向管道提供了 'X' 而不是 'y'。这对于管道“MakeFeatures”的第一个组件很好,因为它接受 'X' 和 returns 'data' 和 'y',但在管道中 'y' 将不会被使用,因为 'y' 必须在 fit_predict() 调用的开头定义。

在此处查看该方法的文档:https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline.fit_predict

它声明 'y' 参数

Training targets. Must fulfill label requirements for all steps of the pipeline.

因此 'y' 将用作管道所有部分的 'y',但您的未定义,因此 None.

因此,您当前的管道基本上发生的情况是:

makeF = MakeFeatures(df, 2 , 24)
transformed_df = makeF.fit_transform(df)

sc = StandardScaler()
sc.fit(transformed_df)

并导致 ValueError: setting an array element with a sequence.

所以我建议您像这样更新代码:

import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
from sklearn.pipeline import Pipeline 
from sklearn.preprocessing import StandardScaler 
from sklearn.linear_model import LinearRegression

np.random.seed(1)

rows,cols = 100,1
data = np.random.randint(100, size = (rows,cols))
tidx = pd.date_range('2019-01-01', periods=rows, freq='20min') 
df = pd.DataFrame(data, columns=['num_orders'], index=tidx)
      
class MakeFeatures(BaseEstimator, TransformerMixin):

  def __init__(self, X, max_lag = None, rolling_mean_day = None, rolling_mean_month = None):
      self.X = X.resample('1H').sum()
      self.max_lag = max_lag
      self.rolling_mean_day = rolling_mean_day
      self.rolling_mean_month = rolling_mean_month
          
  def fit(self, X):
      return self

  def transform(self, X):
      data = pd.DataFrame(index = self.X.index)
      data['num_orders'] = self.X['num_orders']
      data['year'] = self.X.index.year
      data['month'] = self.X.index.month
      data['day'] = self.X.index.day
      data['dayofweek'] = self.X.index.dayofweek
      
      data['detrend'] = self.X.shift() - self.X
      
      if self.max_lag:
          for lag in range(1, self.max_lag + 1):
              data['lag_{}'.format(lag)] = data['detrend'].shift(lag)
      if self.rolling_mean_day:
          data['rolling_mean_24'] = data.detrend.shift().rolling(self.rolling_mean_day).mean()
      
      if self.rolling_mean_month:
          data['rolling_mean_24'] = data['detrend'].shift().rolling(self.rolling_mean_month).mean()
      
      if data['year'].mean() == data['year'][1]:
          data = data.drop('year', axis = 1)
      
      data = data.dropna()
      
      y = data.num_orders
      data = data.drop('num_orders', 1)
      
      return data, list(y)

pipe = Pipeline([
                 ('scaler', StandardScaler()),
                ('Model' , LinearRegression())
      ])

makeF = MakeFeatures(df, 2 , 24)
makeF.fit(df)
data,y = makeF.transform(df)
pipe.fit(data,y)  # where ‘Target’ is y - the output from the Class

然后您可以使用您的管道来预测您的数据并评估性能,例如 r2_score:

from sklearn.metrics import r2_score

predictions = pipe.predict(data)
r2_score(y,predictions)