API references
LightGBMLSS - An extension of LightGBM to probabilistic forecasting
datasets
LightGBMLSS - An extension of LightGBM to probabilistic forecasting
data_loader
load_simulated_gaussian_data()
Returns train/test dataframe of a simulated example.
Contains the following columns
y int64: response x int64: x-feature X1:X10 int64: random noise features
Source code in lightgbmlss/datasets/data_loader.py
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
load_simulated_studentT_data()
Returns train/test dataframe of a simulated example.
Contains the following columns
y int64: response x int64: x-feature X1:X10 int64: random noise features
Source code in lightgbmlss/datasets/data_loader.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
distributions
LightGBMLSS - An extension of LightGBM to probabilistic forecasting
Beta
Beta
Bases: DistributionClass
Beta distribution class.
Distributional Parameters
concentration1: torch.Tensor 1st concentration parameter of the distribution (often referred to as alpha). concentration0: torch.Tensor 2nd concentration parameter of the distribution (often referred to as beta).
Source
https://pytorch.org/docs/stable/distributions.html#beta
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Beta.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Cauchy
Cauchy
Bases: DistributionClass
Cauchy distribution class.
Distributional Parameters
loc: torch.Tensor Mode or median of the distribution. scale: torch.Tensor Half width at half maximum.
Source
https://pytorch.org/docs/stable/distributions.html#cauchy
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Cauchy.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Expectile
Expectile
Bases: DistributionClass
Expectile distribution class.
Distributional Parameters
expectile: List List of specified expectiles.
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". expectiles: List List of expectiles in increasing order. penalize_crossing: bool Whether to include a penalty term to discourage crossing of expectiles.
Source code in lightgbmlss/distributions/Expectile.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
Expectile_Torch
Bases: Distribution
PyTorch implementation of expectiles.
Arguments
expectiles : List[torch.Tensor] List of expectiles. penalize_crossing : bool Whether to include a penalty term to discourage crossing of expectiles.
Source code in lightgbmlss/distributions/Expectile.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
|
log_prob(value, tau)
Returns the log of the probability density function evaluated at value
.
Arguments
value : torch.Tensor Response for which log probability is to be calculated. tau : List[torch.Tensor] List of asymmetry parameters.
Returns
torch.Tensor
Log probability of value
.
Source code in lightgbmlss/distributions/Expectile.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
|
expectile_norm(tau=0.5, m=0, sd=1)
Calculates expectiles from Normal distribution for given tau values. For more details and distributions see https://rdrr.io/cran/expectreg/man/enorm.html
Arguments
tau : np.ndarray Vector of expectiles from the respective distribution. m : np.ndarray Mean of the Normal distribution. sd : np.ndarray Standard deviation of the Normal distribution.
Returns
np.ndarray
Source code in lightgbmlss/distributions/Expectile.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
|
expectile_pnorm(tau=0.5, m=0, sd=1)
Normal Expectile Distribution Function. For more details and distributions see https://rdrr.io/cran/expectreg/man/enorm.html
Arguments
tau : np.ndarray Vector of expectiles from the respective distribution. m : np.ndarray Mean of the Normal distribution. sd : np.ndarray Standard deviation of the Normal distribution.
Returns
tau : np.ndarray Expectiles from the Normal distribution.
Source code in lightgbmlss/distributions/Expectile.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
|
Gamma
Gamma
Bases: DistributionClass
Gamma distribution class.
Distributional Parameters
concentration: torch.Tensor shape parameter of the distribution (often referred to as alpha) rate: torch.Tensor rate = 1 / scale of the distribution (often referred to as beta)
Source
https://pytorch.org/docs/stable/distributions.html#gamma
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Gamma.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Gaussian
Gaussian
Bases: DistributionClass
Gaussian distribution class.
Distributional Parameters
loc: torch.Tensor Mean of the distribution (often referred to as mu). scale: torch.Tensor Standard deviation of the distribution (often referred to as sigma).
Source
https://pytorch.org/docs/stable/distributions.html#normal
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Gaussian.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Gumbel
Gumbel
Bases: DistributionClass
Gumbel distribution class.
Distributional Parameters
loc: torch.Tensor Location parameter of the distribution. scale: torch.Tensor Scale parameter of the distribution.
Source
https://pytorch.org/docs/stable/distributions.html#gumbel
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Gumbel.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Laplace
Laplace
Bases: DistributionClass
Laplace distribution class.
Distributional Parameters
loc: torch.Tensor Mean of the distribution. scale: torch.Tensor Scale of the distribution.
Source
https://pytorch.org/docs/stable/distributions.html#laplace
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Laplace.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
LogNormal
LogNormal
Bases: DistributionClass
LogNormal distribution class.
Distributional Parameters
loc: torch.Tensor Mean of log of distribution. scale: torch.Tensor Standard deviation of log of the distribution.
Source
https://pytorch.org/docs/stable/distributions.html#lognormal
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/LogNormal.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Mixture
Mixture
Bases: MixtureDistributionClass
Mixture-Density distribution class.
Implements a mixture-density distribution for univariate targets, where all components are from different parameterizations of the same distribution-type. A mixture-density distribution is a concept used to model a complex distribution that arises from combining multiple simpler distributions. The Mixture-Density distribution is parameterized by a categorical selecting distribution (over M components) and M-component distributions. For more information on the Mixture-Density distribution, see:
Bishop, C. M. (1994). Mixture density networks. Technical Report NCRG/4288, Aston University, Birmingham, UK.
Distributional Parameters
Inherits the distributional parameters from the component distributions.
Source
https://pytorch.org/docs/stable/distributions.html#mixturesamefamily
Parameters
component_distribution: torch.distributions.Distribution Distribution class for the components of the mixture distribution. Has to be one of the available univariate distributions of the package. M: int Number of components in the mixture distribution. hessian_mode: str Mode for computing the Hessian. Must be one of the following:
- "individual": Each parameter is treated as a separate tensor. As a result, the Hessian corresponds to the
second-order derivative with respect to that specific parameter only. The resulting Hessians capture the
curvature of the loss w.r.t. each individual parameter. This is usually more runtime intensive, but can
be more accurate.
- "grouped": Each tensor contains all parameters for a specific parameter-type, e.g., for a Gaussian-Mixture
with M=2, loc=[loc_1, loc_2], scale=[scale_1, scale_2], and mix_prob=[mix_prob_1, mix_prob_2]. When
computing the Hessian, the derivatives for all parameters in the respective tensor are calculated jointly.
The resulting Hessians capture the curvature of the loss w.r.t. the entire parameter-type. This is usually
less runtime intensive, but can be less accurate.
tau: float, non-negative scalar temperature. The Gumbel-softmax distribution is a continuous distribution over the simplex, which can be thought of as a "soft" version of a categorical distribution. It’s a way to draw samples from a categorical distribution in a differentiable way. The motivation behind using the Gumbel-Softmax is to make the discrete sampling process of categorical variables differentiable, which is useful in gradient-based optimization problems. To sample from a Gumbel-Softmax distribution, one would use the Gumbel-max trick: add a Gumbel noise to logits and apply the softmax. Formally, given a vector z, the Gumbel-softmax function s(z,tau)_i for a component i at temperature tau is defined as:
s(z,tau)_i = frac{e^{(z_i + g_i) / tau}}{sum_{j=1}^M e^{(z_j + g_j) / tau}}
where g_i is a sample from the Gumbel(0, 1) distribution. The parameter tau (temperature) controls the sharpness
of the output distribution. As tau approaches 0, the mixing probabilities become more discrete, and as tau
approaches infty, the mixing probabilities become more uniform. For more information we refer to
Jang, E., Gu, Shixiang and Poole, B. "Categorical Reparameterization with Gumbel-Softmax", ICLR, 2017.
Source code in lightgbmlss/distributions/Mixture.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
NegativeBinomial
NegativeBinomial
Bases: DistributionClass
NegativeBinomial distribution class.
Distributional Parameters
total_count: torch.Tensor Non-negative number of negative Bernoulli trials to stop. probs: torch.Tensor Event probabilities of success in the half open interval [0, 1). logits: torch.Tensor Event log-odds for probabilities of success.
Source
https://pytorch.org/docs/stable/distributions.html#negativebinomial
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn_total_count: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential), "softplus" (softplus) or "relu" (rectified linear unit). response_fn_probs: str Response function for transforming the distributional parameters to the correct support. Options are "sigmoid" (sigmoid). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/NegativeBinomial.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
Poisson
Poisson
Bases: DistributionClass
Poisson distribution class.
Distributional Parameters
rate: torch.Tensor Rate parameter of the distribution (often referred to as lambda).
Source
https://pytorch.org/docs/stable/distributions.html#poisson
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential), "softplus" (softplus) or "relu" (rectified linear unit). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/Poisson.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
|
SplineFlow
SplineFlow
Bases: NormalizingFlowClass
Spline Flow class.
The spline flow is a normalizing flow based on element-wise rational spline bijections of linear and quadratic order (Durkan et al., 2019; Dolatabadi et al., 2020). Rational splines are functions that are comprised of segments that are the ratio of two polynomials. Rational splines offer an excellent combination of functional flexibility whilst maintaining a numerically stable inverse.
For more details, see: - Durkan, C., Bekasov, A., Murray, I. and Papamakarios, G. Neural Spline Flows. NeurIPS 2019. - Dolatabadi, H. M., Erfani, S. and Leckie, C., Invertible Generative Modeling using Linear Rational Splines. AISTATS 2020.
Source
https://docs.pyro.ai/en/stable/distributions.html#pyro.distributions.transforms.Spline
Arguments
target_support: str The target support. Options are - "real": [-inf, inf] - "positive": [0, inf] - "positive_integer": [0, 1, 2, 3, ...] - "unit_interval": [0, 1] count_bins: int The number of segments comprising the spline. bound: float The quantity "K" determining the bounding box, [-K,K] x [-K,K] of the spline. By adjusting the "K" value, you can control the size of the bounding box and consequently control the range of inputs that the spline transform operates on. Larger values of "K" will result in a wider valid range for the spline transformation, while smaller values will restrict the valid range to a smaller region. Should be chosen based on the range of the data. order: str The order of the spline. Options are "linear" or "quadratic". stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD" or "L2". loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/SplineFlow.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
|
StudentT
StudentT
Bases: DistributionClass
Student-T Distribution Class
Distributional Parameters
df: torch.Tensor Degrees of freedom. loc: torch.Tensor Mean of the distribution. scale: torch.Tensor Scale of the distribution.
Source
https://pytorch.org/docs/stable/distributions.html#studentt
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/StudentT.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|
Weibull
Weibull
Bases: DistributionClass
Weibull distribution class.
Distributional Parameters
scale: torch.Tensor Scale parameter of distribution (lambda). concentration: torch.Tensor Concentration parameter of distribution (k/shape).
Source
https://pytorch.org/docs/stable/distributions.html#weibull
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/Weibull.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
ZABeta
ZABeta
Bases: DistributionClass
Zero-Adjusted Beta distribution class.
The zero-adjusted Beta distribution is similar to the Beta distribution but allows zeros as y values.
Distributional Parameters
concentration1: torch.Tensor 1st concentration parameter of the distribution (often referred to as alpha). concentration0: torch.Tensor 2nd concentration parameter of the distribution (often referred to as beta). gate: torch.Tensor Probability of zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/ZABeta.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
ZAGamma
ZAGamma
Bases: DistributionClass
Zero-Adjusted Gamma distribution class.
The zero-adjusted Gamma distribution is similar to the Gamma distribution but allows zeros as y values.
Distributional Parameters
concentration: torch.Tensor shape parameter of the distribution (often referred to as alpha) rate: torch.Tensor rate = 1 / scale of the distribution (often referred to as beta) gate: torch.Tensor Probability of zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L150
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/ZAGamma.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
ZALN
ZALN
Bases: DistributionClass
Zero-Adjusted LogNormal distribution class.
The zero-adjusted Log-Normal distribution is similar to the Log-Normal distribution but allows zeros as y values.
Distributional Parameters
loc: torch.Tensor Mean of log of distribution. scale: torch.Tensor Standard deviation of log of the distribution. gate: torch.Tensor Probability of zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L150
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential) or "softplus" (softplus). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/ZALN.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
ZINB
ZINB
Bases: DistributionClass
Zero-Inflated Negative Binomial distribution class.
Distributional Parameters
total_count: torch.Tensor Non-negative number of negative Bernoulli trials to stop. probs: torch.Tensor Event probabilities of success in the half open interval [0, 1). gate: torch.Tensor Probability of extra zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L150
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn_total_count: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential), "softplus" (softplus) or "relu" (rectified linear unit). response_fn_probs: str Response function for transforming the distributional parameters to the correct support. Options are "sigmoid" (sigmoid). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/ZINB.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
ZIPoisson
ZIPoisson
Bases: DistributionClass
Zero-Inflated Poisson distribution class.
Distributional Parameters
rate: torch.Tensor Rate parameter of the distribution (often referred to as lambda). gate: torch.Tensor Probability of extra zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L121
Parameters
stabilization: str Stabilization method for the Gradient and Hessian. Options are "None", "MAD", "L2". response_fn: str Response function for transforming the distributional parameters to the correct support. Options are "exp" (exponential), "softplus" (softplus) or "relu" (rectified linear unit). loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/ZIPoisson.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
distribution_utils
DistributionClass
Generic class that contains general functions for univariate distributions.
Arguments
distribution: torch.distributions.Distribution PyTorch Distribution class. univariate: bool Whether the distribution is univariate or multivariate. discrete: bool Whether the support of the distribution is discrete or continuous. n_dist_param: int Number of distributional parameters. stabilization: str Stabilization method. param_dict: Dict[str, Any] Dictionary that maps distributional parameters to their response scale. distribution_arg_names: List List of distributional parameter names. loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function. tau: List List of expectiles. Only used for Expectile distributon. penalize_crossing: bool Whether to include a penalty term to discourage crossing of expectiles. Only used for Expectile distribution.
Source code in lightgbmlss/distributions/distribution_utils.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 |
|
calculate_start_values(target, max_iter=50)
Function that calculates the starting values for each distributional parameter.
Arguments
target: np.ndarray Data from which starting values are calculated. max_iter: int Maximum number of iterations.
Returns
loss: float Loss value. start_values: np.ndarray Starting values for each distributional parameter.
Source code in lightgbmlss/distributions/distribution_utils.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
|
compute_gradients_and_hessians(loss, predt, weights)
Calculates gradients and hessians.
Output gradients and hessians have shape (n_samples*n_outputs, 1).
Arguments:
loss: torch.Tensor Loss. predt: torch.Tensor List of predicted parameters. weights: np.ndarray Weights.
Returns:
grad: torch.Tensor Gradients. hess: torch.Tensor Hessians.
Source code in lightgbmlss/distributions/distribution_utils.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
|
crps_score(y, yhat_dist)
Function that calculates the Continuous Ranked Probability Score (CRPS) for a given set of predicted samples.
Parameters
y: torch.Tensor Response variable of shape (n_observations,1). yhat_dist: torch.Tensor Predicted samples of shape (n_samples, n_observations).
Returns
crps: torch.Tensor CRPS score.
References
Gneiting, Tilmann & Raftery, Adrian. (2007). Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association. 102. 359-378.
Source
https://github.com/elephaint/pgbm/blob/main/pgbm/torch/pgbm_dist.py#L549
Source code in lightgbmlss/distributions/distribution_utils.py
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
|
dist_select(target, candidate_distributions, max_iter=100, plot=False, figure_size=(10, 5))
Function that selects the most suitable distribution among the candidate_distributions for the target variable, based on the NegLogLikelihood (lower is better).
Parameters
target: np.ndarray Response variable. candidate_distributions: List List of candidate distributions. max_iter: int Maximum number of iterations for the optimization. plot: bool If True, a density plot of the actual and fitted distribution is created. figure_size: tuple Figure size of the density plot.
Returns
fit_df: pd.DataFrame Dataframe with the loss values of the fitted candidate distributions.
Source code in lightgbmlss/distributions/distribution_utils.py
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 |
|
draw_samples(predt_params, n_samples=1000, seed=123)
Function that draws n_samples from a predicted distribution.
Arguments
predt_params: pd.DataFrame pd.DataFrame with predicted distributional parameters. n_samples: int Number of sample to draw from predicted response distribution. seed: int Manual seed.
Returns
pred_dist: pd.DataFrame DataFrame with n_samples drawn from predicted response distribution.
Source code in lightgbmlss/distributions/distribution_utils.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
|
get_params_loss(predt, target, start_values, requires_grad=False)
Function that returns the predicted parameters and the loss.
Arguments
predt: np.ndarray Predicted values. target: torch.Tensor Target values. start_values: List Starting values for each distributional parameter. requires_grad: bool Whether to add to the computational graph or not.
Returns
predt: torch.Tensor Predicted parameters. loss: torch.Tensor Loss value.
Source code in lightgbmlss/distributions/distribution_utils.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
|
loss_fn_start_values(params, target)
Function that calculates the loss for a given set of distributional parameters. Only used for calculating the loss for the start values.
Parameter
params: torch.Tensor Distributional parameters. target: torch.Tensor Target values.
Returns
loss: torch.Tensor Loss value.
Source code in lightgbmlss/distributions/distribution_utils.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
|
metric_fn(predt, data)
Function that evaluates the predictions using the negative log-likelihood.
Arguments
predt: np.ndarray Predicted values. data: lgb.Dataset Data used for training.
Returns
name: str Name of the evaluation metric. nll: float Negative log-likelihood. is_higher_better: bool Whether a higher value of the metric is better or not.
Source code in lightgbmlss/distributions/distribution_utils.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
|
objective_fn(predt, data)
Function to estimate gradients and hessians of distributional parameters.
Arguments
predt: np.ndarray Predicted values. data: lgb.DMatrix Data used for training.
Returns
grad: np.ndarray Gradient. hess: np.ndarray Hessian.
Source code in lightgbmlss/distributions/distribution_utils.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
|
predict_dist(booster, data, start_values, pred_type='parameters', n_samples=1000, quantiles=[0.1, 0.5, 0.9], seed=123)
Function that predicts from the trained model.
Arguments
booster : lgb.Booster Trained model. data : pd.DataFrame Data to predict from. start_values : np.ndarray. Starting values for each distributional parameter. pred_type : str Type of prediction: - "samples" draws n_samples from the predicted distribution. - "quantiles" calculates the quantiles from the predicted distribution. - "parameters" returns the predicted distributional parameters. - "expectiles" returns the predicted expectiles. n_samples : int Number of samples to draw from the predicted distribution. quantiles : List[float] List of quantiles to calculate from the predicted distribution. seed : int Seed for random number generator used to draw samples from the predicted distribution.
Returns
pred : pd.DataFrame Predictions.
Source code in lightgbmlss/distributions/distribution_utils.py
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 |
|
stabilize_derivative(input_der, type='MAD')
Function that stabilizes Gradients and Hessians.
As LightGBMLSS updates the parameter estimates by optimizing Gradients and Hessians, it is important that these are comparable in magnitude for all distributional parameters. Due to imbalances regarding the ranges, the estimation might become unstable so that it does not converge (or converge very slowly) to the optimal solution. Another way to improve convergence might be to standardize the response variable. This is especially useful if the range of the response differs strongly from the range of the Gradients and Hessians. Both, the stabilization and the standardization of the response are not always advised but need to be carefully considered. Source: https://github.com/boost-R/gamboostLSS/blob/7792951d2984f289ed7e530befa42a2a4cb04d1d/R/helpers.R#L173
Parameters
input_der : torch.Tensor Input derivative, either Gradient or Hessian. type: str Stabilization method. Can be either "None", "MAD" or "L2".
Returns
stab_der : torch.Tensor Stabilized Gradient or Hessian.
Source code in lightgbmlss/distributions/distribution_utils.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 |
|
flow_utils
NormalizingFlowClass
Generic class that contains general functions for normalizing flows.
Arguments
base_dist: torch.distributions.Distribution PyTorch Distribution class. Currently only Normal is supported. flow_transform: Transform Specify the normalizing flow transform. count_bins: Optional[int] The number of segments comprising the spline. Only used if flow_transform is Spline. bound: Optional[float] The quantity "K" determining the bounding box, [-K,K] x [-K,K] of the spline. By adjusting the "K" value, you can control the size of the bounding box and consequently control the range of inputs that the spline transform operates on. Larger values of "K" will result in a wider valid range for the spline transformation, while smaller values will restrict the valid range to a smaller region. Should be chosen based on the range of the data. Only used if flow_transform is Spline. order: Optional[str] The order of the spline. Options are "linear" or "quadratic". Only used if flow_transform is Spline. n_dist_param: int Number of parameters. param_dict: Dict[str, Any] Dictionary that maps parameters to their response scale. distribution_arg_names: List List of distributional parameter names. target_transform: Transform Specify the target transform. discrete: bool Whether the target is discrete or not. univariate: bool Whether the distribution is univariate or multivariate. stabilization: str Stabilization method. Options are "None", "MAD" or "L2". loss_fn: str Loss function. Options are "nll" (negative log-likelihood) or "crps" (continuous ranked probability score). Note that if "crps" is used, the Hessian is set to 1, as the current CRPS version is not twice differentiable. Hence, using the CRPS disregards any variation in the curvature of the loss function.
Source code in lightgbmlss/distributions/flow_utils.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 |
|
calculate_start_values(target, max_iter=50)
Function that calculates starting values for each parameter.
Arguments
target: np.ndarray Data from which starting values are calculated. max_iter: int Maximum number of iterations.
Returns
loss: float Loss value. start_values: np.ndarray Starting values for each parameter.
Source code in lightgbmlss/distributions/flow_utils.py
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
|
compute_gradients_and_hessians(loss, predt, weights)
Calculates gradients and hessians.
Output gradients and hessians have shape (n_samples*n_outputs, 1).
Arguments:
loss: torch.Tensor Loss. predt: torch.Tensor List of predicted parameters. weights: np.ndarray Weights.
Returns:
grad: torch.Tensor Gradients. hess: torch.Tensor Hessians.
Source code in lightgbmlss/distributions/flow_utils.py
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 |
|
create_spline_flow(input_dim=None)
Function that constructs a Normalizing Flow.
Arguments
input_dim: int Input dimension.
Returns
spline_flow: Transform Normalizing Flow.
Source code in lightgbmlss/distributions/flow_utils.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
|
crps_score(y, yhat_dist)
Function that calculates the Continuous Ranked Probability Score (CRPS) for a given set of predicted samples.
Arguments
y: torch.Tensor Response variable of shape (n_observations,1). yhat_dist: torch.Tensor Predicted samples of shape (n_samples, n_observations).
Returns
crps: torch.Tensor CRPS score.
References
Gneiting, Tilmann & Raftery, Adrian. (2007). Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association. 102. 359-378.
Source
https://github.com/elephaint/pgbm/blob/main/pgbm/torch/pgbm_dist.py#L549
Source code in lightgbmlss/distributions/flow_utils.py
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 |
|
draw_samples(predt_params, n_samples=1000, seed=123)
Function that draws n_samples from a predicted distribution.
Arguments
predt_params: pd.DataFrame pd.DataFrame with predicted distributional parameters. n_samples: int Number of sample to draw from predicted response distribution. seed: int Manual seed.
Returns
pred_dist: pd.DataFrame DataFrame with n_samples drawn from predicted response distribution.
Source code in lightgbmlss/distributions/flow_utils.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
|
flow_select(target, candidate_flows, max_iter=100, plot=False, figure_size=(10, 5))
Function that selects the most suitable normalizing flow specification among the candidate_flow for the target variable, based on the NegLogLikelihood (lower is better).
Parameters
target: np.ndarray Response variable. candidate_flows: List List of candidate normalizing flow specifications. max_iter: int Maximum number of iterations for the optimization. plot: bool If True, a density plot of the actual and fitted distribution is created. figure_size: tuple Figure size of the density plot.
Returns
fit_df: pd.DataFrame Dataframe with the loss values of the fitted normalizing flow.
Source code in lightgbmlss/distributions/flow_utils.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 |
|
get_params_loss(predt, target, start_values, requires_grad=False)
Function that returns the predicted parameters and the loss.
Arguments
predt: np.ndarray Predicted values. target: torch.Tensor Target values. start_values: List Starting values for each parameter.
Returns
predt: torch.Tensor Predicted parameters. loss: torch.Tensor Loss value.
Source code in lightgbmlss/distributions/flow_utils.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
|
metric_fn(predt, data)
Function that evaluates the predictions using the specified loss function.
Arguments
predt: np.ndarray Predicted values. data: lgb.Dataset Data used for training.
Returns
name: str Name of the evaluation metric. loss: float Loss value.
Source code in lightgbmlss/distributions/flow_utils.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
|
objective_fn(predt, data)
Function to estimate gradients and hessians of normalizing flow parameters.
Arguments
predt: np.ndarray Predicted values. data: lgb.Dataset Data used for training.
Returns
grad: np.ndarray Gradient. hess: np.ndarray Hessian.
Source code in lightgbmlss/distributions/flow_utils.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
|
predict_dist(booster, data, start_values, pred_type='parameters', n_samples=1000, quantiles=[0.1, 0.5, 0.9], seed=123)
Function that predicts from the trained model.
Arguments
booster : lgb.Booster Trained model. start_values : np.ndarray Starting values for each distributional parameter. data : pd.DataFrame Data to predict from. pred_type : str Type of prediction: - "samples" draws n_samples from the predicted distribution. - "quantiles" calculates the quantiles from the predicted distribution. - "parameters" returns the predicted distributional parameters. - "expectiles" returns the predicted expectiles. n_samples : int Number of samples to draw from the predicted distribution. quantiles : List[float] List of quantiles to calculate from the predicted distribution. seed : int Seed for random number generator used to draw samples from the predicted distribution.
Returns
pred : pd.DataFrame Predictions.
Source code in lightgbmlss/distributions/flow_utils.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
|
replace_parameters(params, flow_dist)
Replace parameters with estimated ones.
Arguments
params: torch.Tensor Estimated parameters. flow_dist: Transform Normalizing Flow.
Returns
params_list: List List of estimated parameters. flow_dist: Transform Normalizing Flow with estimated parameters.
Source code in lightgbmlss/distributions/flow_utils.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
|
stabilize_derivative(input_der, type='MAD')
Function that stabilizes Gradients and Hessians.
Since parameters are estimated by optimizing Gradients and Hessians, it is important that these are comparable in magnitude for all parameters. Due to imbalances regarding the ranges, the estimation might become unstable so that it does not converge (or converge very slowly) to the optimal solution. Another way to improve convergence might be to standardize the response variable. This is especially useful if the range of the response differs strongly from the range of the Gradients and Hessians. Both, the stabilization and the standardization of the response are not always advised but need to be carefully considered.
Source
https://github.com/boost-R/gamboostLSS/blob/7792951d2984f289ed7e530befa42a2a4cb04d1d/R/helpers.R#L173
Arguments
input_der : torch.Tensor Input derivative, either Gradient or Hessian. type: str Stabilization method. Can be either "None", "MAD" or "L2".
Returns
stab_der : torch.Tensor Stabilized Gradient or Hessian.
Source code in lightgbmlss/distributions/flow_utils.py
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
|
mixture_distribution_utils
MixtureDistributionClass
Generic class that contains general functions for mixed-density distributions.
Arguments
distribution: torch.distributions.Distribution PyTorch Distribution class. M: int Number of components in the mixture distribution. temperature: float Temperature for the Gumbel-Softmax distribution. hessian_mode: str Mode for computing the Hessian. Must be one of the following:
- "individual": Each parameter is treated as a separate tensor. As a result, when the Hessian is calculated
for each gradient element, this corresponds to the second derivative with respect to that specific tensor
element only. This means the resulting Hessians capture the curvature of the loss w.r.t. each individual
parameter. This is usually more runtime intensive, but can also be more accurate.
- "grouped": Each parameter is a tensor containing all values for a specific parameter type,
e.g., loc, scale, or mixture probabilities for a Gaussian Mixture. When computing the Hessian for each
gradient element, the Hessian matrix for all the values in the respective tensor are calculated together.
The resulting Hessians capture the curvature of the loss w.r.t. the entire parameter type tensor. This is
usually less runtime intensive, but can be less accurate.
univariate: bool Whether the distribution is univariate or multivariate. discrete: bool Whether the support of the distribution is discrete or continuous. n_dist_param: int Number of distributional parameters. stabilization: str Stabilization method. param_dict: Dict[str, Any] Dictionary that maps distributional parameters to their response scale. distribution_arg_names: List List of distributional parameter names. loss_fn: str Loss function. Options are "nll" (negative log-likelihood).
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 |
|
calculate_start_values(target, max_iter=50)
Function that calculates the starting values for each distributional parameter.
Arguments
target: np.ndarray Data from which starting values are calculated. max_iter: int Maximum number of iterations.
Returns
loss: float Loss value. start_values: np.ndarray Starting values for each distributional parameter.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
|
compute_gradients_and_hessians(loss, predt, weights)
Calculates gradients and hessians.
Output gradients and hessians have shape (n_samples*n_outputs, 1).
Arguments:
loss: torch.Tensor Loss. predt: torch.Tensor List of predicted parameters. weights: np.ndarray Weights.
Returns:
grad: torch.Tensor Gradients. hess: torch.Tensor Hessians.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
|
create_mixture_distribution(params)
Function that creates a mixture distribution.
Arguments
params: torch.Tensor Distributional parameters.
Returns
dist: torch.distributions.Distribution Mixture distribution.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
|
dist_select(target, candidate_distributions, max_iter=100, plot=False, figure_size=(8, 5))
Function that selects the most suitable distribution among the candidate_distributions for the target variable, based on the NegLogLikelihood (lower is better).
Parameters
target: np.ndarray Response variable. candidate_distributions: List List of candidate distributions. max_iter: int Maximum number of iterations for the optimization. plot: bool If True, a density plot of the actual and fitted distribution is created. figure_size: tuple Figure size of the density plot.
Returns
fit_df: pd.DataFrame Dataframe with the loss values of the fitted candidate distributions.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 |
|
draw_samples(predt_params, n_samples=1000, seed=123)
Function that draws n_samples from a predicted distribution.
Arguments
predt_params: pd.DataFrame pd.DataFrame with predicted distributional parameters. n_samples: int Number of sample to draw from predicted response distribution. seed: int Manual seed.
Returns
pred_dist: pd.DataFrame DataFrame with n_samples drawn from predicted response distribution.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 |
|
get_params_loss(predt, target, start_values, requires_grad=False)
Function that returns the predicted parameters and the loss.
Arguments
predt: np.ndarray Predicted values. target: torch.Tensor Target values. start_values: List Starting values for each distributional parameter. requires_grad: bool Whether to add to the computational graph or not.
Returns
predt: torch.Tensor Predicted parameters. loss: torch.Tensor Loss value.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
|
loss_fn_start_values(params, target)
Function that calculates the loss for a given set of distributional parameters. Only used for calculating the loss for the start values.
Parameter
params: torch.Tensor Distributional parameters. target: torch.Tensor Target values.
Returns
loss: torch.Tensor Loss value.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
|
metric_fn(predt, data)
Function that evaluates the predictions using the negative log-likelihood.
Arguments
predt: np.ndarray Predicted values. data: lgb.Dataset Data used for training.
Returns
name: str Name of the evaluation metric. nll: float Negative log-likelihood. is_higher_better: bool Whether a higher value of the metric is better or not.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
|
objective_fn(predt, data)
Function to estimate gradients and hessians of distributional parameters.
Arguments
predt: np.ndarray Predicted values. data: lgb.DMatrix Data used for training.
Returns
grad: np.ndarray Gradient. hess: np.ndarray Hessian.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
|
predict_dist(booster, data, start_values, pred_type='parameters', n_samples=1000, quantiles=[0.1, 0.5, 0.9], seed=123)
Function that predicts from the trained model.
Arguments
booster : lgb.Booster Trained model. data : pd.DataFrame Data to predict from. start_values : np.ndarray. Starting values for each distributional parameter. pred_type : str Type of prediction: - "samples" draws n_samples from the predicted distribution. - "quantiles" calculates the quantiles from the predicted distribution. - "parameters" returns the predicted distributional parameters. n_samples : int Number of samples to draw from the predicted distribution. quantiles : List[float] List of quantiles to calculate from the predicted distribution. seed : int Seed for random number generator used to draw samples from the predicted distribution.
Returns
pred : pd.DataFrame Predictions.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 |
|
stabilize_derivative(input_der, type='MAD')
Function that stabilizes Gradients and Hessians.
As LightGBMLSS updates the parameter estimates by optimizing Gradients and Hessians, it is important that these are comparable in magnitude for all distributional parameters. Due to imbalances regarding the ranges, the estimation might become unstable so that it does not converge (or converge very slowly) to the optimal solution. Another way to improve convergence might be to standardize the response variable. This is especially useful if the range of the response differs strongly from the range of the Gradients and Hessians. Both, the stabilization and the standardization of the response are not always advised but need to be carefully considered. Source: https://github.com/boost-R/gamboostLSS/blob/7792951d2984f289ed7e530befa42a2a4cb04d1d/R/helpers.R#L173
Parameters
input_der : torch.Tensor Input derivative, either Gradient or Hessian. type: str Stabilization method. Can be either "None", "MAD" or "L2".
Returns
stab_der : torch.Tensor Stabilized Gradient or Hessian.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 |
|
get_component_distributions()
Function that returns component distributions for creating a mixing distribution.
Arguments
None
Returns
distns: List List of all available distributions.
Source code in lightgbmlss/distributions/mixture_distribution_utils.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
zero_inflated
ZeroAdjustedBeta
Bases: ZeroInflatedDistribution
A Zero-Adjusted Beta distribution.
Parameter
concentration1: torch.Tensor 1st concentration parameter of the distribution (often referred to as alpha). concentration0: torch.Tensor 2nd concentration parameter of the distribution (often referred to as beta). gate: torch.Tensor Probability of zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py
Source code in lightgbmlss/distributions/zero_inflated.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
ZeroAdjustedGamma
Bases: ZeroInflatedDistribution
A Zero-Adjusted Gamma distribution.
Parameter
concentration: torch.Tensor shape parameter of the distribution (often referred to as alpha) rate: torch.Tensor rate = 1 / scale of the distribution (often referred to as beta) gate: torch.Tensor Probability of zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py
Source code in lightgbmlss/distributions/zero_inflated.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
|
ZeroAdjustedLogNormal
Bases: ZeroInflatedDistribution
A Zero-Adjusted Log-Normal distribution.
Parameter
loc: torch.Tensor Mean of log of distribution. scale: torch.Tensor Standard deviation of log of the distribution. gate: torch.Tensor Probability of zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py
Source code in lightgbmlss/distributions/zero_inflated.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|
ZeroInflatedDistribution
Bases: TorchDistribution
Generic Zero Inflated distribution.
This can be used directly or can be used as a base class as e.g. for
:class:ZeroInflatedPoisson
and :class:ZeroInflatedNegativeBinomial
.
Parameters
gate : torch.Tensor Probability of extra zeros given via a Bernoulli distribution. base_dist : torch.distributions.Distribution The base distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L18
Source code in lightgbmlss/distributions/zero_inflated.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
|
ZeroInflatedNegativeBinomial
Bases: ZeroInflatedDistribution
A Zero Inflated Negative Binomial distribution.
Parameter
total_count: torch.Tensor Non-negative number of negative Bernoulli trial. probs: torch.Tensor Event probabilities of success in the half open interval [0, 1). logits: torch.Tensor Event log-odds of success (log(p/(1-p))). gate: torch.Tensor Probability of extra zeros given via a Bernoulli distribution.
Source
- https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L150
Source code in lightgbmlss/distributions/zero_inflated.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
|
ZeroInflatedPoisson
Bases: ZeroInflatedDistribution
A Zero-Inflated Poisson distribution.
Parameter
rate: torch.Tensor The rate of the Poisson distribution. gate: torch.Tensor Probability of extra zeros given via a Bernoulli distribution.
Source
https://github.com/pyro-ppl/pyro/blob/dev/pyro/distributions/zero_inflated.py#L121
Source code in lightgbmlss/distributions/zero_inflated.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
|
model
LightGBMLSS
LightGBMLSS model class
Parameters
dist : Distribution DistributionClass object. start_values : np.ndarray Starting values for each distributional parameter.
Source code in lightgbmlss/model.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 |
|
cv(params, train_set, num_boost_round=100, folds=None, nfold=5, stratified=True, shuffle=True, init_model=None, feature_name='auto', categorical_feature='auto', fpreproc=None, seed=123, callbacks=None, eval_train_metric=False, return_cvbooster=False)
Function to cross-validate a LightGBMLSS model with given parameters.
Parameters
params : dict
Parameters for training. Values passed through params
take precedence over those
supplied via arguments.
train_set : Dataset
Data to be trained on.
num_boost_round : int, optional (default=100)
Number of boosting iterations.
folds : generator or iterator of (train_idx, test_idx) tuples, scikit-learn splitter object or None, optional (default=None)
If generator or iterator, it should yield the train and test indices for each fold.
If object, it should be one of the scikit-learn splitter classes
(https://scikit-learn.org/stable/modules/classes.html#splitter-classes)
and have split
method.
This argument has highest priority over other data split arguments.
nfold : int, optional (default=5)
Number of folds in CV.
stratified : bool, optional (default=True)
Whether to perform stratified sampling.
shuffle : bool, optional (default=True)
Whether to shuffle before splitting data.
init_model : str, pathlib.Path, Booster or None, optional (default=None)
Filename of LightGBM model or Booster instance used for continue training.
feature_name : list of str, or 'auto', optional (default="auto")
Feature names.
If 'auto' and data is pandas DataFrame, data columns names are used.
categorical_feature : list of str or int, or 'auto', optional (default="auto")
Categorical features.
If list of int, interpreted as indices.
If list of str, interpreted as feature names (need to specify feature_name
as well).
If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.
All values in categorical features will be cast to int32 and thus should be less than int32 max value (2147483647).
Large values could be memory consuming. Consider using consecutive integers starting from zero.
All negative values in categorical features will be treated as missing values.
The output cannot be monotonically constrained with respect to a categorical feature.
Floating point numbers in categorical features will be rounded towards 0.
fpreproc : callable or None, optional (default=None)
Preprocessing function that takes (dtrain, dtest, params)
and returns transformed versions of those.
seed : int, optional (default=0)
Seed used to generate the folds (passed to numpy.random.seed).
callbacks : list of callable, or None, optional (default=None)
List of callback functions that are applied at each iteration.
See Callbacks in Python API for more information.
eval_train_metric : bool, optional (default=False)
Whether to display the train metric in progress.
The score of the metric is calculated again after each training step, so there is some impact on performance.
return_cvbooster : bool, optional (default=False)
Whether to return Booster models trained on each fold through CVBooster
.
Returns
eval_hist : dict
Evaluation history.
The dictionary has the following format:
{'metric1-mean': [values], 'metric1-stdv': [values],
'metric2-mean': [values], 'metric2-stdv': [values],
...}.
If return_cvbooster=True
, also returns trained boosters wrapped in a CVBooster
object via cvbooster
key.
Source code in lightgbmlss/model.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
|
expectile_plot(X, feature='x', expectile='0.05', plot_type='Partial_Dependence')
LightGBMLSS function for plotting expectile SHapley values.
pd.DataFrame
Train/Test Data
feature: str Specifies which feature to use for plotting Partial_Dependence plot. expectile: str Specifies which expectile to plot. plot_type: str Specifies which SHapley-plot to visualize. Currently, "Partial_Dependence" and "Feature_Importance" are supported.
Source code in lightgbmlss/model.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 |
|
hyper_opt(hp_dict, train_set, num_boost_round=500, nfold=10, early_stopping_rounds=20, max_minutes=10, n_trials=None, study_name=None, silence=False, seed=None, hp_seed=None)
Function to tune hyperparameters using optuna.
Arguments
hp_dict: dict Dictionary of hyperparameters to tune. train_set: lgb.Dataset Training data. num_boost_round: int Number of boosting iterations. nfold: int Number of folds in CV. early_stopping_rounds: int Activates early stopping. Cross-Validation metric (average of validation metric computed over CV folds) needs to improve at least once in every early_stopping_rounds round(s) to continue training. The last entry in the evaluation history will represent the best iteration. If there's more than one metric in the eval_metric parameter given in params, the last metric will be used for early stopping. max_minutes: int Time budget in minutes, i.e., stop study after the given number of minutes. n_trials: int The number of trials. If this argument is set to None, there is no limitation on the number of trials. study_name: str Name of the hyperparameter study. silence: bool Controls the verbosity of the trail, i.e., user can silence the outputs of the trail. seed: int Seed used to generate the folds (passed to numpy.random.seed). hp_seed: int Seed for random number generator used in the Bayesian hyper-parameter search.
Returns
opt_params : dict Optimal hyper-parameters.
Source code in lightgbmlss/model.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 |
|
load_model(model_path)
staticmethod
Load the model from a file.
Parameters
model_path : str The path to the saved model.
Returns
The loaded model.
Source code in lightgbmlss/model.py
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 |
|
plot(X, feature='x', parameter='loc', max_display=15, plot_type='Partial_Dependence')
LightGBMLSS SHap plotting function.
Arguments:
X: pd.DataFrame Train/Test Data feature: str Specifies which feature is to be plotted. parameter: str Specifies which distributional parameter is to be plotted. max_display: int Specifies the maximum number of features to be displayed. plot_type: str Specifies the type of plot: "Partial_Dependence" plots the partial dependence of the parameter on the feature. "Feature_Importance" plots the feature importance of the parameter.
Source code in lightgbmlss/model.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 |
|
predict(data, pred_type='parameters', n_samples=1000, quantiles=[0.1, 0.5, 0.9], seed=123)
Function that predicts from the trained model.
Arguments
data : pd.DataFrame Data to predict from. pred_type : str Type of prediction: - "samples" draws n_samples from the predicted distribution. - "quantiles" calculates the quantiles from the predicted distribution. - "parameters" returns the predicted distributional parameters. - "expectiles" returns the predicted expectiles. n_samples : int Number of samples to draw from the predicted distribution. quantiles : List[float] List of quantiles to calculate from the predicted distribution. seed : int Seed for random number generator used to draw samples from the predicted distribution.
Returns
predt_df : pd.DataFrame Predictions.
Source code in lightgbmlss/model.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
|
save_model(model_path)
Save the model to a file.
Parameters
model_path : str The path to save the model.
Returns
None
Source code in lightgbmlss/model.py
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
|
set_init_score(dmatrix)
Set init_score for distributions.
Arguments
dmatrix : Dataset Dataset to set base margin for.
Returns
None
Source code in lightgbmlss/model.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
set_params(params)
Set parameters for distributional model.
Arguments
params : Dict[str, Any] Parameters for model.
Returns
params : Dict[str, Any] Updated Parameters for model.
Source code in lightgbmlss/model.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
|
set_valid_margin(valid_sets)
Function that sets the base margin for the validation set.
Arguments
valid_sets : list List of tuples containing the evaluation set(s).
Returns
valid_sets : list List of tuples containing the evaluation set(s).
Source code in lightgbmlss/model.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
|
train(params, train_set, num_boost_round=100, valid_sets=None, valid_names=None, init_model=None, feature_name='auto', categorical_feature='auto', keep_training_booster=False, callbacks=None)
Function to perform the training of a LightGBMLSS model with given parameters.
Parameters
params : dict
Parameters for training. Values passed through params
take precedence over those
supplied via arguments.
train_set : Dataset
Data to be trained on.
num_boost_round : int, optional (default=100)
Number of boosting iterations.
valid_sets : list of Dataset, or None, optional (default=None)
List of data to be evaluated on during training.
valid_names : list of str, or None, optional (default=None)
Names of valid_sets
.
init_model : str, pathlib.Path, Booster or None, optional (default=None)
Filename of LightGBM model or Booster instance used for continue training.
feature_name : list of str, or 'auto', optional (default="auto")
Feature names.
If 'auto' and data is pandas DataFrame, data columns names are used.
categorical_feature : list of str or int, or 'auto', optional (default="auto")
Categorical features.
If list of int, interpreted as indices.
If list of str, interpreted as feature names (need to specify feature_name
as well).
If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.
All values in categorical features will be cast to int32 and thus should be less than int32 max value (2147483647).
Large values could be memory consuming. Consider using consecutive integers starting from zero.
All negative values in categorical features will be treated as missing values.
The output cannot be monotonically constrained with respect to a categorical feature.
Floating point numbers in categorical features will be rounded towards 0.
keep_training_booster : bool, optional (default=False)
Whether the returned Booster will be used to keep training.
If False, the returned value will be converted into _InnerPredictor before returning.
This means you won't be able to use eval
, eval_train
or eval_valid
methods of the returned Booster.
When your model is very large and cause the memory error,
you can try to set this param to True
to avoid the model conversion performed during the internal call of model_to_string
.
You can still use _InnerPredictor as init_model
for future continue training.
callbacks : list of callable, or None, optional (default=None)
List of callback functions that are applied at each iteration.
See Callbacks in Python API for more information.
Returns
booster : Booster The trained Booster model.
Source code in lightgbmlss/model.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
utils
exp_fn(predt)
Exponential function used to ensure predt is strictly positive.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
|
exp_fn_df(predt)
Exponential function used for Student-T distribution.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
|
gumbel_softmax_fn(predt, tau=1.0)
Gumbel-softmax function used to ensure predt is adding to one.
The Gumbel-softmax distribution is a continuous distribution over the simplex, which can be thought of as a "soft" version of a categorical distribution. It’s a way to draw samples from a categorical distribution in a differentiable way. The motivation behind using the Gumbel-Softmax is to make the discrete sampling process of categorical variables differentiable, which is useful in gradient-based optimization problems. To sample from a Gumbel-Softmax distribution, one would use the Gumbel-max trick: add a Gumbel noise to logits and apply the softmax. Formally, given a vector z, the Gumbel-softmax function s(z,tau)_i for a component i at temperature tau is defined as:
s(z,tau)_i = frac{e^{(z_i + g_i) / tau}}{sum_{j=1}^M e^{(z_j + g_j) / tau}}
where g_i is a sample from the Gumbel(0, 1) distribution. The parameter tau (temperature) controls the sharpness of the output distribution. As tau approaches 0, the mixing probabilities become more discrete, and as tau approaches infty, the mixing probabilities become more uniform. For more information we refer to
Jang, E., Gu, Shixiang and Poole, B. "Categorical Reparameterization with Gumbel-Softmax", ICLR, 2017.
Arguments
predt: torch.tensor Predicted values. tau: float, non-negative scalar temperature. Temperature parameter for the Gumbel-softmax distribution. As tau -> 0, the output becomes more discrete, and as tau -> inf, the output becomes more uniform.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
identity_fn(predt)
Identity mapping of predt.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
nan_to_num(predt)
Replace nan, inf and -inf with the mean of predt.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
relu_fn(predt)
Function used to ensure predt are scaled to max(0, predt).
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
|
sigmoid_fn(predt)
Function used to ensure predt are scaled to (0,1).
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
|
softmax_fn(predt)
Softmax function used to ensure predt is adding to one.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|
softplus_fn(predt)
Softplus function used to ensure predt is strictly positive.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
softplus_fn_df(predt)
Softplus function used for Student-T distribution.
Arguments
predt: torch.tensor Predicted values.
Returns
predt: torch.tensor Predicted values.
Source code in lightgbmlss/utils.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
|