docstr: ShapExplainer
  
  **Definitions**
  
  - A background series is a `TimeSeries` used to train the shap explainer.
  - A foreground series is a `TimeSeries` that can be explained by a shap explainer after it has been fitted.
  
  Currently, `ShapExplainer` only works with `RegressionModel` forecasting models.
  The number of explained horizons (t+1, t+2, ...) can be at most equal to `output_chunk_length` of `model`.
  
  Parameters
  ----------
  model
      A `RegressionModel` to be explained. It must be fitted first.
  background_series
      One or several series to *train* the `ShapExplainer` along with any foreground series.
      Consider using a reduced well-chosen background to reduce computation time.
      Optional if `model` was fit on a single target series. By default, it is the `series` used at fitting time.
      Mandatory if `model` was fit on multiple (list of) target series.
  background_past_covariates
      A past covariates series or list of series that the model needs once fitted.
  background_future_covariates
      A future covariates series or list of series that the model needs once fitted.
  background_num_samples
      Optionally, whether to sample a subset of the original background. Randomly picks
      `background_num_samples` training samples of the constructed training dataset
      (using ``shap.utils.sample()``).
      Generally used for faster computation, especially when `shap_method` is
      ``"kernel"`` or ``"permutation"``.
  shap_method
      Optionally, the shap method to apply. By default, an attempt is made
      to select the most appropriate method based on a pre-defined set of known models.
      internal mapping. Supported values : ``"permutation", "partition", "tree", "kernel", "sampling", "linear",
      "deep", "gradient", "additive"``.
  **kwargs
      Optionally, additional keyword arguments passed to `shap_method`.
  Examples
  --------
  >>> from darts.datasets import AirPassengersDataset
  >>> from darts.explainability.shap_explainer import ShapExplainer
  >>> from darts.models import LinearRegressionModel
  >>> series = AirPassengersDataset().load()
  >>> model = LinearRegressionModel(lags=12)
  >>> model.fit(series[:-36])
  >>> shap_explain = ShapExplainer(model)
  >>> results = shap_explain.explain()
  >>> shap_explain.summary_plot()
  >>> shap_explain.force_plot_from_ts()
docstr_tok: ["ShapExplainer","*","*","Definitions","*","*","-","A","background","series","is","a","`","TimeSeries","`","used","to","train","the","shap","explainer",".","-","A","foreground","series","is","a","`","TimeSeries","`","that","can","be","explained","by","a","shap","explainer","after","it","has","been","fitted",".","Currently",",","`","ShapExplainer","`","only","works","with","`","RegressionModel","`","forecasting","models",".","The","number","of","explained","horizons","(","t+1",",","t+2",",","...",")","can","be","at","most","equal","to","`","output_chunk_length","`","of","`","model","`",".","Parameters","--","--","--","--","--","model","A","`","RegressionModel","`","to","be","explained",".","It","must","be","fitted","first",".","background_series","One","or","several","series","to","*","train","*","the","`","ShapExplainer","`","along","with","any","foreground","series",".","Consider","using","a","reduced","well-chosen","background","to","reduce","computation","time",".","Optional","if","`","model","`","was","fit","on","a","single","target","series",".","By","default",",","it","is","the","`","series","`","used","at","fitting","time",".","Mandatory","if","`","model","`","was","fit","on","multiple","(","list","of",")","target","series",".","background_past_covariates","A","past","covariates","series","or","list","of","series","that","the","model","needs","once","fitted",".","background_future_covariates","A","future","covariates","series","or","list","of","series","that","the","model","needs","once","fitted",".","background_num_samples","Optionally",",","whether","to","sample","a","subset","of","the","original","background",".","Randomly","picks","`","background_num_samples","`","training","samples","of","the","constructed","training","dataset","(","using","``","shap.utils.sample","(",")","``",")",".","Generally","used","for","faster","computation",",","especially","when","`","shap_method","`","is","``","``","kernel","''","``","or","``","``","permutation","''","``",".","shap_method","Optionally",",","the","shap","method","to","apply",".","By","default",",","an","attempt","is","made","to","select","the","most","appropriate","method","based","on","a","pre-defined","set","of","known","models",".","internal","mapping",".","Supported","values",":","``","``","permutation","''",",","``","partition","''",",","``","tree","''",",","``","kernel","''",",","``","sampling","''",",","``","linear","''",",","``","deep","''",",","``","gradient","''",",","``","additive","''","``",".","*","*","kwargs","Optionally",",","additional","keyword","arguments","passed","to","`","shap_method","`",".","Examples","--","--","--","--",">",">",">","from","darts.datasets","import","AirPassengersDataset",">",">",">","from","darts.explainability.shap_explainer","import","ShapExplainer",">",">",">","from","darts.models","import","LinearRegressionModel",">",">",">","series","=","AirPassengersDataset","(",")",".load","(",")",">",">",">","model","=","LinearRegressionModel","(","lags=12",")",">",">",">","model.fit","(","series","[",":","-36","]",")",">",">",">","shap_explain","=","ShapExplainer","(","model",")",">",">",">","results","=","shap_explain.explain","(",")",">",">",">","shap_explain.summary_plot","(",")",">",">",">","shap_explain.force_plot_from_ts","(",")"]
code: def __init__(
      self,
      model: RegressionModel,
      background_series: Optional[
          Union[TimeSeries, Sequence[TimeSeries]]
      ] = None,
      background_past_covariates: Optional[
          Union[TimeSeries, Sequence[TimeSeries]]
      ] = None,
      background_future_covariates: Optional[
          Union[TimeSeries, Sequence[TimeSeries]]
      ] = None,
      background_num_samples: Optional[int] = None,
      shap_method: Optional[str] = None,
      **kwargs,
  ):
      """ShapExplainer
  
      **Definitions**
  
      - A background series is a `TimeSeries` used to train the shap explainer.
      - A foreground series is a `TimeSeries` that can be explained by a shap explainer after it has been fitted.
  
      Currently, `ShapExplainer` only works with `RegressionModel` forecasting models.
      The number of explained horizons (t+1, t+2, ...) can be at most equal to `output_chunk_length` of `model`.
  
      Parameters
      ----------
      model
          A `RegressionModel` to be explained. It must be fitted first.
      background_series
          One or several series to *train* the `ShapExplainer` along with any foreground series.
          Consider using a reduced well-chosen background to reduce computation time.
          Optional if `model` was fit on a single target series. By default, it is the `series` used at fitting time.
          Mandatory if `model` was fit on multiple (list of) target series.
      background_past_covariates
          A past covariates series or list of series that the model needs once fitted.
      background_future_covariates
          A future covariates series or list of series that the model needs once fitted.
      background_num_samples
          Optionally, whether to sample a subset of the original background. Randomly picks
          `background_num_samples` training samples of the constructed training dataset
          (using ``shap.utils.sample()``).
          Generally used for faster computation, especially when `shap_method` is
          ``"kernel"`` or ``"permutation"``.
      shap_method
          Optionally, the shap method to apply. By default, an attempt is made
          to select the most appropriate method based on a pre-defined set of known models.
          internal mapping. Supported values : ``"permutation", "partition", "tree", "kernel", "sampling", "linear",
          "deep", "gradient", "additive"``.
      **kwargs
          Optionally, additional keyword arguments passed to `shap_method`.
      Examples
      --------
      >>> from darts.datasets import AirPassengersDataset
      >>> from darts.explainability.shap_explainer import ShapExplainer
      >>> from darts.models import LinearRegressionModel
      >>> series = AirPassengersDataset().load()
      >>> model = LinearRegressionModel(lags=12)
      >>> model.fit(series[:-36])
      >>> shap_explain = ShapExplainer(model)
      >>> results = shap_explain.explain()
      >>> shap_explain.summary_plot()
      >>> shap_explain.force_plot_from_ts()
      """
  
      # TODO
      # - Optional De-trend  if the timeseries is not stationary.
      # There would be
      # 1) a stationarity test and
      # 2) a de-trend methodology for the target. It can be for
      # example target - moving_average(input_chunk_length).
  
      if not issubclass(type(model), RegressionModel):
          raise_log(
              ValueError(
                  "Invalid `model` type. Currently, only models of type `RegressionModel` are supported."
              ),
              logger,
          )
  
      if not model.multi_models:
          raise_log(
              ValueError(
                  "Invalid `multi_models` value `False`. Currently, "
                  "ShapExplainer only supports RegressionModels "
                  "with `multi_models=True`."
              ),
              logger,
          )
  
      super().__init__(
          model=model,
          background_series=background_series,
          background_past_covariates=background_past_covariates,
          background_future_covariates=background_future_covariates,
          requires_background=True,
          requires_covariates_encoding=True,
          check_component_names=True,
          test_stationarity=True,
      )
  
      if model._is_probabilistic:
          logger.warning(
              "The model is probabilistic, but num_samples=1 will be used for explainability."
          )
  
      if shap_method is not None:
          shap_method = shap_method.upper()
          if shap_method in _ShapMethod.__members__:
              self.shap_method = _ShapMethod[shap_method]
          else:
              raise_log(
                  ValueError(
                      "Invalid `shap_method`. Please choose one value among the following: ['partition', 'tree', "
                      "'kernel', 'sampling', 'linear', 'deep', 'gradient', 'additive']."
                  )
              )
      else:
          self.shap_method = None
  
      self.explainers = _RegressionShapExplainers(
          model=self.model,
          n=self.n,
          target_components=self.target_components,
          past_covariates_components=self.past_covariates_components,
          future_covariates_components=self.future_covariates_components,
          background_series=self.background_series,
          background_past_covariates=self.background_past_covariates,
          background_future_covariates=self.background_future_covariates,
          shap_method=self.shap_method,
          background_num_samples=background_num_samples,
          **kwargs,
      )
  
imports: from enum import Enum
  from typing import Dict, NewType, Optional, Sequence, Union
  import matplotlib.pyplot
  import pandas
  import shap
  from sklearn.multioutput import MultiOutputRegressor
  from darts import TimeSeries
  from darts.explainability.explainability import _ForecastingModelExplainer
  from darts.explainability.explainability_result import ShapExplainabilityResult
  from darts.logging import get_logger, raise_if, raise_log
  from darts.models.forecasting.regression_model import RegressionModel
  from darts.utils.data.tabularization import create_lagged_prediction_data
label_desc: Use image node_id 1 to create a new ShapExplainer object from inherited base classes: _ForecastingModelExplainer with example: obj = ShapExplainer(model, background_series, background_past_covariates, background_future_covariates, background_num_samples, shap_method)