class_docstr: Formal representation of a linear regression from provided covariates.
  
  This model defines a time series given by a linear combination of
  covariate time series provided in a design matrix:
  
  ```python
  observed_time_series = matmul(design_matrix, weights)
  ```
  
  The design matrix has shape `[num_timesteps, num_features]`. The weights
  are treated as an unknown random variable of size `[num_features]` (both
  components also support batch shape), and are integrated over using the same
  approximate inference tools as other model parameters, i.e., generally HMC or
  variational inference.
  
  This component does not itself include observation noise; it defines a
  deterministic distribution with mass at the point
  `matmul(design_matrix, weights)`. In practice, it should be combined with
  observation noise from another component such as `tfp.sts.Sum`, as
  demonstrated below.
  
  #### Examples
  
  Given `series1`, `series2` as `Tensors` each of shape `[num_timesteps]`
  representing covariate time series, we create a regression model that
  conditions on these covariates:
  
  ```python
  regression = tfp.sts.LinearRegression(
    design_matrix=tf.stack([series1, series2], axis=-1),
    weights_prior=tfd.Normal(loc=0., scale=1.))
  ```
  
  Here we've also demonstrated specifying a custom prior, using an informative
  `Normal(0., 1.)` prior instead of the default weakly-informative prior.
  
  As a more advanced application, we might use the design matrix to encode
  holiday effects. For example, suppose we are modeling data from the month of
  December. We can combine day-of-week seasonality with special effects for
  Christmas Eve (Dec 24), Christmas (Dec 25), and New Year's Eve (Dec 31),
  by constructing a design matrix with indicators for those dates.
  
  ```python
  holiday_indicators = np.zeros([31, 3])
  holiday_indicators[23, 0] = 1  # Christmas Eve
  holiday_indicators[24, 1] = 1  # Christmas Day
  holiday_indicators[30, 2] = 1  # New Year's Eve
  
  holidays = tfp.sts.LinearRegression(design_matrix=holiday_indicators,
                                      name='holidays')
  day_of_week = tfp.sts.Seasonal(num_seasons=7,
                                 observed_time_series=observed_time_series,
                                 name='day_of_week')
  model = tfp.sts.Sum(components=[holidays, seasonal],
                      observed_time_series=observed_time_series)
  ```
  
  Note that the `Sum` component in the above model also incorporates observation
  noise, with prior scale heuristically inferred from `observed_time_series`.
  
  In these examples, we've used a single design matrix, but batching is
  also supported. If the design matrix has batch shape, the default behavior
  constructs weights with matching batch shape, which will fit a separate
  regression for each design matrix. This can be overridden by passing an
  explicit weights prior with appropriate batch shape. For example, if each
  design matrix in a batch contains features with the same semantics
  (e.g., if they represent per-group or per-observation covariates), we might
  choose to share statistical strength by fitting a single weight vector that
  broadcasts across all design matrices:
  
  ```python
  design_matrix = get_batch_of_inputs()
  design_matrix.shape  # => concat([batch_shape, [num_timesteps, num_features]])
  
  # Construct a prior with batch shape `[]` and event shape `[num_features]`,
  # so that it describes a single vector of weights.
  weights_prior = tfd.Independent(
      tfd.StudentT(df=5,
                   loc=tf.zeros([num_features]),
                   scale=tf.ones([num_features])),
      reinterpreted_batch_ndims=1)
  linear_regression = LinearRegression(design_matrix=design_matrix,
                                       weights_prior=weights_prior)
  ```
class_docstr_tok: ["Formal","representation","of","a","linear","regression","from","provided","covariates",".","This","model","defines","a","time","series","given","by","a","linear","combination","of","covariate","time","series","provided","in","a","design","matrix",":","``","`","python","observed_time_series","=","matmul","(","design_matrix",",","weights",")","``","`","The","design","matrix","has","shape","`","[","num_timesteps",",","num_features","]","`",".","The","weights","are","treated","as","an","unknown","random","variable","of","size","`","[","num_features","]","`","(","both","components","also","support","batch","shape",")",",","and","are","integrated","over","using","the","same","approximate","inference","tools","as","other","model","parameters",",","i.e.",",","generally","HMC","or","variational","inference",".","This","component","does","not","itself","include","observation","noise",";","it","defines","a","deterministic","distribution","with","mass","at","the","point","`","matmul","(","design_matrix",",","weights",")","`",".","In","practice",",","it","should","be","combined","with","observation","noise","from","another","component","such","as","`","tfp.sts.Sum","`",",","as","demonstrated","below",".","#","#","#","#","Examples","Given","`","series1","`",",","`","series2","`","as","`","Tensors","`","each","of","shape","`","[","num_timesteps","]","`","representing","covariate","time","series",",","we","create","a","regression","model","that","conditions","on","these","covariates",":","``","`","python","regression","=","tfp.sts.LinearRegression","(","design_matrix=tf.stack","(","[","series1",",","series2","]",",","axis=-1",")",",","weights_prior=tfd.Normal","(","loc=0.",",","scale=1",".",")",")","``","`","Here","we","'ve","also","demonstrated","specifying","a","custom","prior",",","using","an","informative","`","Normal","(","0.",",","1",".",")","`","prior","instead","of","the","default","weakly-informative","prior",".","As","a","more","advanced","application",",","we","might","use","the","design","matrix","to","encode","holiday","effects",".","For","example",",","suppose","we","are","modeling","data","from","the","month","of","December",".","We","can","combine","day-of-week","seasonality","with","special","effects","for","Christmas","Eve","(","Dec","24",")",",","Christmas","(","Dec","25",")",",","and","New","Year","'s","Eve","(","Dec","31",")",",","by","constructing","a","design","matrix","with","indicators","for","those","dates",".","``","`","python","holiday_indicators","=","np.zeros","(","[","31",",","3","]",")","holiday_indicators","[","23",",","0","]","=","1","#","Christmas","Eve","holiday_indicators","[","24",",","1","]","=","1","#","Christmas","Day","holiday_indicators","[","30",",","2","]","=","1","#","New","Year","'s","Eve","holidays","=","tfp.sts.LinearRegression","(","design_matrix=holiday_indicators",",","name='holidays","'",")","day_of_week","=","tfp.sts.Seasonal","(","num_seasons=7",",","observed_time_series=observed_time_series",",","name='day_of_week","'",")","model","=","tfp.sts.Sum","(","components=","[","holidays",",","seasonal","]",",","observed_time_series=observed_time_series",")","``","`","Note","that","the","`","Sum","`","component","in","the","above","model","also","incorporates","observation","noise",",","with","prior","scale","heuristically","inferred","from","`","observed_time_series","`",".","In","these","examples",",","we","'ve","used","a","single","design","matrix",",","but","batching","is","also","supported",".","If","the","design","matrix","has","batch","shape",",","the","default","behavior","constructs","weights","with","matching","batch","shape",",","which","will","fit","a","separate","regression","for","each","design","matrix",".","This","can","be","overridden","by","passing","an","explicit","weights","prior","with","appropriate","batch","shape",".","For","example",",","if","each","design","matrix","in","a","batch","contains","features","with","the","same","semantics","(","e.g.",",","if","they","represent","per-group","or","per-observation","covariates",")",",","we","might","choose","to","share","statistical","strength","by","fitting","a","single","weight","vector","that","broadcasts","across","all","design","matrices",":","``","`","python","design_matrix","=","get_batch_of_inputs","(",")","design_matrix.shape","#","=",">","concat","(","[","batch_shape",",","[","num_timesteps",",","num_features","]","]",")","#","Construct","a","prior","with","batch","shape","`","[","]","`","and","event","shape","`","[","num_features","]","`",",","#","so","that","it","describes","a","single","vector","of","weights",".","weights_prior","=","tfd.Independent","(","tfd.StudentT","(","df=5",",","loc=tf.zeros","(","[","num_features","]",")",",","scale=tf.ones","(","[","num_features","]",")",")",",","reinterpreted_batch_ndims=1",")","linear_regression","=","LinearRegression","(","design_matrix=design_matrix",",","weights_prior=weights_prior",")","``","`"]
docstr: Specify a linear regression model.
  
  Note: the statistical behavior of the regression is determined by
  the broadcasting behavior of the `weights` `Tensor`:
  
  * `weights_prior.batch_shape == []`: shares a single set of weights across
    all design matrices and observed time series. This may make sense if
    the features in each design matrix have the same semantics (e.g.,
    grouping observations by country, with per-country design matrices
    capturing the same set of national economic indicators per country).
    For applications requiring multiple samples of weights (VI, HMC),
    `weights_prior.batch_shape` should be inflated with singleton dimensions
    so that its rank is at least that of `design_matrix.batch_shape`; this
    prevents the sample dimensions from colliding with the design matrix batch
    dimensions.
  * `weights_prior.batch_shape == `design_matrix.batch_shape`: fits separate
    weights for each design matrix. If there are multiple observed time series
    for each design matrix, this shares statistical strength over those
    observations.
  * `weights_prior.batch_shape == `observed_time_series.batch_shape`: fits a
    separate regression for each individual time series.
  
  When modeling batches of time series, you should think carefully about
  which behavior makes sense, and specify `weights_prior` accordingly:
  the defaults may not do what you want!
  
  Args:
    design_matrix: float `Tensor` of shape `concat([batch_shape,
      [num_timesteps, num_features]])`. This may also optionally be
      an instance of `tf.linalg.LinearOperator`.
    weights_prior: `tfd.Distribution` representing a prior over the regression
      weights. Must have event shape `[num_features]` and batch shape
      broadcastable to the design matrix's `batch_shape`. If `None`, defaults
      to `Sample(StudentT(df=5, loc=0., scale=10.), num_features])`, a
      weakly-informative prior loosely inspired by the
      [Stan prior choice recommendations](
      https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations).
      Default value: `None`.
    name: the name of this model component.
      Default value: 'LinearRegression'.
docstr_tok: ["Specify","a","linear","regression","model",".","Note",":","the","statistical","behavior","of","the","regression","is","determined","by","the","broadcasting","behavior","of","the","`","weights","`","`","Tensor","`",":","*","`","weights_prior.batch_shape","==","[","]","`",":","shares","a","single","set","of","weights","across","all","design","matrices","and","observed","time","series",".","This","may","make","sense","if","the","features","in","each","design","matrix","have","the","same","semantics","(","e.g.",",","grouping","observations","by","country",",","with","per-country","design","matrices","capturing","the","same","set","of","national","economic","indicators","per","country",")",".","For","applications","requiring","multiple","samples","of","weights","(","VI",",","HMC",")",",","`","weights_prior.batch_shape","`","should","be","inflated","with","singleton","dimensions","so","that","its","rank","is","at","least","that","of","`","design_matrix.batch_shape","`",";","this","prevents","the","sample","dimensions","from","colliding","with","the","design","matrix","batch","dimensions",".","*","`","weights_prior.batch_shape","==","`","design_matrix.batch_shape","`",":","fits","separate","weights","for","each","design","matrix",".","If","there","are","multiple","observed","time","series","for","each","design","matrix",",","this","shares","statistical","strength","over","those","observations",".","*","`","weights_prior.batch_shape","==","`","observed_time_series.batch_shape","`",":","fits","a","separate","regression","for","each","individual","time","series",".","When","modeling","batches","of","time","series",",","you","should","think","carefully","about","which","behavior","makes","sense",",","and","specify","`","weights_prior","`","accordingly",":","the","defaults","may","not","do","what","you","want","!","Args",":","design_matrix",":","float","`","Tensor","`","of","shape","`","concat","(","[","batch_shape",",","[","num_timesteps",",","num_features","]","]",")","`",".","This","may","also","optionally","be","an","instance","of","`","tf.linalg.LinearOperator","`",".","weights_prior",":","`","tfd.Distribution","`","representing","a","prior","over","the","regression","weights",".","Must","have","event","shape","`","[","num_features","]","`","and","batch","shape","broadcastable","to","the","design","matrix","'s","`","batch_shape","`",".","If","`","None","`",",","defaults","to","`","Sample","(","StudentT","(","df=5",",","loc=0.",",","scale=10",".",")",",","num_features","]",")","`",",","a","weakly-informative","prior","loosely","inspired","by","the","[","Stan","prior","choice","recommendations","]","(","https",":","\/\/github.com\/stan-dev\/stan\/wiki\/Prior-Choice-Recommendations",")",".","Default","value",":","`","None","`",".","name",":","the","name","of","this","model","component",".","Default","value",":","'LinearRegression","'","."]
code: def __init__(self, design_matrix, weights_prior=None, name=None):
      """Specify a linear regression model.
  
      Note: the statistical behavior of the regression is determined by
      the broadcasting behavior of the `weights` `Tensor`:
  
      * `weights_prior.batch_shape == []`: shares a single set of weights across
        all design matrices and observed time series. This may make sense if
        the features in each design matrix have the same semantics (e.g.,
        grouping observations by country, with per-country design matrices
        capturing the same set of national economic indicators per country).
        For applications requiring multiple samples of weights (VI, HMC),
        `weights_prior.batch_shape` should be inflated with singleton dimensions
        so that its rank is at least that of `design_matrix.batch_shape`; this
        prevents the sample dimensions from colliding with the design matrix batch
        dimensions.
      * `weights_prior.batch_shape == `design_matrix.batch_shape`: fits separate
        weights for each design matrix. If there are multiple observed time series
        for each design matrix, this shares statistical strength over those
        observations.
      * `weights_prior.batch_shape == `observed_time_series.batch_shape`: fits a
        separate regression for each individual time series.
  
      When modeling batches of time series, you should think carefully about
      which behavior makes sense, and specify `weights_prior` accordingly:
      the defaults may not do what you want!
  
      Args:
        design_matrix: float `Tensor` of shape `concat([batch_shape,
          [num_timesteps, num_features]])`. This may also optionally be
          an instance of `tf.linalg.LinearOperator`.
        weights_prior: `tfd.Distribution` representing a prior over the regression
          weights. Must have event shape `[num_features]` and batch shape
          broadcastable to the design matrix's `batch_shape`. If `None`, defaults
          to `Sample(StudentT(df=5, loc=0., scale=10.), num_features])`, a
          weakly-informative prior loosely inspired by the
          [Stan prior choice recommendations](
          https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations).
          Default value: `None`.
        name: the name of this model component.
          Default value: 'LinearRegression'.
      """
      init_parameters = dict(locals())
      with tf.name_scope(name or "LinearRegression") as name:
          if not isinstance(design_matrix, tfl.LinearOperator):
              design_matrix = tfl.LinearOperatorFullMatrix(
                  tf.convert_to_tensor(
                      value=design_matrix, name="design_matrix"
                  ),
                  name="design_matrix_linop",
              )
  
          if (
              tf.compat.dimension_value(design_matrix.shape[-1])
              is not None
          ):
              num_features = design_matrix.shape[-1]
          else:
              num_features = design_matrix.shape_tensor()[-1]
  
          # Default to a weakly-informative StudentT(df=5, 0., 10.) prior.
          if weights_prior is None:
              if design_matrix.batch_shape.is_fully_defined():
                  design_matrix_batch_shape_ = design_matrix.batch_shape
              else:
                  design_matrix_batch_shape_ = (
                      design_matrix.batch_shape_tensor()
                  )
              dtype = design_matrix.dtype
              weights_prior = student_t.StudentT(
                  df=tf.constant(5, dtype=dtype),
                  loc=tf.zeros(design_matrix_batch_shape_, dtype=dtype),
                  scale=tf.constant(10, dtype=dtype)
                  * tf.ones([], dtype=dtype),
              )
          # Sugar: if prior is static scalar, lift it to a prior on feature vectors.
          if weights_prior.event_shape.ndims == 0:
              weights_prior = sample.Sample(
                  weights_prior, sample_shape=[num_features]
              )
  
          tf.debugging.assert_same_float_dtype(
              [design_matrix, weights_prior]
          )
  
          self._design_matrix = design_matrix
  
          super(LinearRegression, self).__init__(
              parameters=[
                  Parameter(
                      name="weights",
                      prior=weights_prior,
                      # If the weights prior has constrained support, then we'd like
                      # to avoid considering invalid weights at inference time. For
                      # example, an Exponential prior should only see nonnegative
                      # weights. For now, we enforce this using the prior's default
                      # bijector. Given sufficient motivation we might consider
                      # adding a `weights_constraining_bijector` argument
                      # to customize the bijector choice, analogous to
                      # `sts.Autoregressive.coef_constraining_bijector`.
                      bijector=(
                          weights_prior.experimental_default_event_space_bijector()
                      ),
                  ),
              ],
              latent_size=0,
              init_parameters=init_parameters,
              name=name,
          )
  
imports: import tensorflow.compat.v2
  from tensorflow_probability.python.bijectors import identity
  from tensorflow_probability.python.bijectors import softplus
  from tensorflow_probability.python.distributions import half_normal
  from tensorflow_probability.python.distributions import independent
  from tensorflow_probability.python.distributions import inverse_gamma
  from tensorflow_probability.python.distributions import linear_gaussian_ssm
  from tensorflow_probability.python.distributions import mvn_diag
  from tensorflow_probability.python.distributions import normal
  from tensorflow_probability.python.distributions import sample
  from tensorflow_probability.python.distributions import student_t
  from tensorflow_probability.python.internal import distribution_util
  from tensorflow_probability.python.internal import dtype_util
  from tensorflow_probability.python.sts.structural_time_series import Parameter
  from tensorflow_probability.python.sts.structural_time_series import StructuralTimeSeries
label_desc: Use image node_id 1 to create a new LinearRegression object from inherited base classes: StructuralTimeSeries with example: obj = LinearRegression(design_matrix, weights_prior, name)