code: def breakdown_regression_based_prediction(
      trained_model,
      x_mat,
      grouping_regex_patterns_dict,
      remainder_group_name="OTHER",
      center_components=False,
      denominator=None,
      index_values=None,
      index_col="index_col",
      plt_title="prediction breakdown",
  ):
      """Given a regression based ML model (``ml_model``) and a design matrix
      (``x_mat``), and a string based grouping rule (``grouping_regex_patterns_dict``)
      for the design matrix columnns, constructs a dataframe with columns corresponding
      to the weighted (according to ML model regression coefficient) sum of the columns in each group.
      Note that if a variable/column is already picked in a step, it will be taken
      out from the columns list and will not appear in next groups.
  
      Parameters
      ----------
      trained_model : `dict`
          A trained machine-learning model which includes items:
  
          - ml_model : `sklearn.base.BaseEstimator`
              sklearn ML estimator/model of various form.
              We require this object to have ``.coef_`` and ``.intercept`` attributes.
          - y_mean : `float`
              Observed mean of the response
          - y_std : `float`
              Observed standard deviation of the response
  
      x_mat :`pandas.DataFrame`
          Design matrix of the regression model
      grouping_regex_patterns_dict : `dict` {`str`: `str`}
          A dictionary with group names as keys and regexes as values.
          This dictinary is used to partition the columns into various groups
      remainder_group_name : `str`, default "OTHER"
          In case some columns are left and not assigned to any groups, a group
          with this name will be added to breakdown dataframe and includes the
          weighted some of the remaining columns.
      center_components : `bool`, default False
          It determines if components should be centered at their mean and the mean
          be added to the intercept. More concretely, if a componet is "x" then it will
          be mapped to "x - mean(x)"; and "mean(x)" will be added to the intercept so
          that the sum of the components remains the same.
      denominator : `str`, default None
          If not None, it will specify a way to divide the components. There are
          two options implemented:
  
          - "abs_y_mean" : `float`
              The absolute value of the observed mean of the response
          - "y_std" : `float`
              The standard deviation of the observed response
  
          This will be useful if we want to make the components scale free.
          Dividing by the absolute mean value of the response, is particularly
          useful to understand how much impact each component has for an average
          response.
  
      index_values : `list`, default None
          The values added as index which can of any types that can be used for
          plotting the x axis in plotly eg `int` or `datetime`.
          This is useful for plotting or if later this data to be joined
          with other data. For example in forecasting context timestamps can be added.
      index_col : `str`, default "index_col"
          The name of the added column to breakdown data to keep track of index
      plt_title : `str`, default "prediction breakdown"
          The title of generated plot
  
      Returns
      -------
      result : `dict`
          A dictionary with the following keys.
  
          - "breakdown_df" : `pandas.DataFrame`
              A dataframe which includes the sums for each group / component
          - "breakdown_df_with_index_col" : `pandas.DataFrame`
              Same as ``breakdown_df`` with an added column to keep track of index
          - "breakdown_fig" : `plotly.graph_objs._figure.Figure`
              plotly plot overlaying various components
          - "column_grouping_result" : `dict`
              A dictionary which includes information for the generated groups.
              See `~greykite.common.python_utils.group_strs_with_regex_patterns`
              for more details.
  
      """
      if index_values is not None:
          assert len(index_values) == len(
              x_mat
          ), "the number of indices must match the size of data"
  
      ml_model = trained_model["ml_model"]
      # The dataframe which includes the group sums
      breakdown_df = pd.DataFrame()
      ml_model_coef = ml_model.coef_
      intercept = ml_model.intercept_
      x_mat_weighted = x_mat * ml_model_coef
      data_len = len(x_mat)
      cols = list(x_mat.columns)
  
      breakdown_df["Intercept"] = np.repeat(intercept, data_len)
      if "Intercept" in cols:
          breakdown_df["Intercept"] += x_mat_weighted["Intercept"]
  
      # If Intercept appear in the columns, we remove it
      # Note that this column was utilized and added to intercept
      if "Intercept" in cols:
          del x_mat_weighted["Intercept"]
          cols.remove("Intercept")
  
      regex_patterns = list(grouping_regex_patterns_dict.values())
      group_names = list(grouping_regex_patterns_dict.keys())
  
      column_grouping_result = group_strs_with_regex_patterns(
          strings=cols, regex_patterns=regex_patterns
      )
  
      col_groups = column_grouping_result["str_groups"]
      remainder = column_grouping_result["remainder"]
  
      assert len(col_groups) == len(grouping_regex_patterns_dict)
  
      for i, group_name in enumerate(group_names):
          group_elements = col_groups[i]
          if len(group_elements) != 0:
              breakdown_df[group_name] = x_mat_weighted[
                  group_elements
              ].sum(axis=1)
          else:
              breakdown_df[group_name] = 0.0
  
      if len(remainder) != 0:
          breakdown_df[remainder_group_name] = x_mat_weighted[
              remainder
          ].sum(axis=1)
          group_names.append(remainder_group_name)
  
      if center_components:
          for col in group_names:
              col_mean = breakdown_df[col].mean()
              breakdown_df[col] += -col_mean
              breakdown_df["Intercept"] += col_mean
  
      if denominator == "abs_y_mean":
          d = abs(trained_model["y_mean"])
      elif denominator == "y_std":
          d = trained_model["y_std"]
      elif denominator is None:
          d = 1.0
      else:
          raise NotImplementedError(
              f"{denominator} is not an admissable denominator"
          )
  
      for col in group_names + ["Intercept"]:
          breakdown_df[col] /= d
  
      if index_values is None:
          index_values = range(len(breakdown_df))
  
      breakdown_df_with_index_col = breakdown_df.copy()
      breakdown_df_with_index_col[index_col] = index_values
  
      breakdown_fig = plot_multivariate(
          df=breakdown_df_with_index_col,
          x_col=index_col,
          title=plt_title,
          ylabel="component",
      )
  
      return {
          "breakdown_df": breakdown_df,
          "breakdown_df_with_index_col": breakdown_df_with_index_col,
          "breakdown_fig": breakdown_fig,
          "column_grouping_result": column_grouping_result,
      }
  
imports: import random
  import re
  import traceback
  import warnings
  from typing import Dict
  from typing import List
  from typing import Optional
  import matplotlib
  import numpy
  import pandas
  import patsy
  import scipy
  import statsmodels.api
  from pandas.plotting import register_matplotlib_converters
  from sklearn.ensemble import GradientBoostingRegressor
  from sklearn.ensemble import RandomForestRegressor
  from sklearn.linear_model import ElasticNetCV
  from sklearn.linear_model import LarsCV
  from sklearn.linear_model import LassoCV
  from sklearn.linear_model import LassoLarsCV
  from sklearn.linear_model import RidgeCV
  from sklearn.linear_model import SGDRegressor
  from greykite.algo.common.l1_quantile_regression import QuantileRegression
  from greykite.algo.uncertainty.conditional.conf_interval import conf_interval
  from greykite.algo.uncertainty.conditional.conf_interval import predict_ci
  from greykite.common.constants import RESIDUAL_COL
  from greykite.common.constants import R2_null_model_score
  from greykite.common.evaluation import calc_pred_err
  from greykite.common.evaluation import r2_null_model_score
  from greykite.common.features.normalize import normalize_df
  from greykite.common.logging import LoggingLevelEnum
  from greykite.common.logging import log_message
  from greykite.common.python_utils import group_strs_with_regex_patterns
  from greykite.common.viz.timeseries_plotting import plot_multivariate
  import matplotlib.pyplot
label_desc: Use image node_id 9 for calling a global function with example usage: breakdown_regression_based_prediction(trained_model, x_mat, grouping_regex_patterns_dict, remainder_group_name, center_components, denominator, index_values, index_col, plt_title) and returns: dict