class HorizonTransformer(BaseEstimator, TransformerMixin): needs_refit = True y_only = True def __init__(self, horizon=2): super().__init__() if horizon < 2: raise ValueError("horizon must be greater than 1") self.horizon = horizon self.autoregressive_transformer = AutoregressiveTransformer( num_lags=self.horizon, pred_stride=1) def fit(self, X, y=None): self.autoregressive_transformer.fit(expand_dim_if_needed(X)) return self def transform(self, X, y=None, refit=False): X = expand_dim_if_needed(X) if refit: self.autoregressive_transformer.fit(X) Xt = self.autoregressive_transformer.transform(X) # The autoregressive transformer won't build lags _with_ the last element of X. # So, we have to manually tack it on here. last_non_nan_piece = np.hstack((Xt[-1, 1:], X[-1])) Xt = np.vstack( (Xt[self.horizon:, :], last_non_nan_piece, Xt[1:self.horizon, :])) return Xt def inverse_transform(self, X, y=None): Xt = np.vstack((X[-self.horizon:, :], X[:-self.horizon, :])) return self.autoregressive_transformer.inverse_transform(Xt) def fit_transform(self, X, y=None): return self.fit(X).transform(X)
class HorizonTransformer(BaseEstimator, TransformerMixin): needs_refit = True y_only = True def __init__(self, horizon=2): super().__init__() if horizon < 2: raise ValueError('horizon must be greater than 1') self.horizon = horizon self.autoregressive_transformer = AutoregressiveTransformer( num_lags=self.horizon, pred_stride=1) def fit(self, X, y=None): self.autoregressive_transformer.fit(expand_dim_if_needed(X)) return self def transform(self, X, y=None, refit=False): X = expand_dim_if_needed(X) if refit: self.autoregressive_transformer.fit(X) Xt = self.autoregressive_transformer.transform(X) # Need to move beginning of Xt to the end. Xt = np.vstack((Xt[self.horizon:, :], Xt[:self.horizon, :])) # TODO: replace beginning with nans? return Xt def inverse_transform(self, X, y=None): Xt = np.vstack((X[-self.horizon:, :], X[:-self.horizon, :])) return self.autoregressive_transformer.inverse_transform(Xt) def fit_transform(self, X, y=None): return self.fit(X).transform(X)