code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def resid_pearson(self):
"""
Pearson residuals. The Pearson residuals are defined as
(`endog` - `mu`)/sqrt(VAR(`mu`)) where VAR is the distribution
specific variance function. See statsmodels.families.family and
statsmodels.families.varfuncs for more information.
"""
return (np.sqrt(self._n_trials) * (self._endog-self.mu) *
np.sqrt(self._var_weights) /
np.sqrt(self.family.variance(self.mu))) | Pearson residuals. The Pearson residuals are defined as
(`endog` - `mu`)/sqrt(VAR(`mu`)) where VAR is the distribution
specific variance function. See statsmodels.families.family and
statsmodels.families.varfuncs for more information. | resid_pearson | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def resid_working(self):
"""
Working residuals. The working residuals are defined as
`resid_response`/link'(`mu`). See statsmodels.family.links for the
derivatives of the link functions. They are defined analytically.
"""
# Isn't self.resid_response is already adjusted by _n_trials?
val = (self.resid_response * self.family.link.deriv(self.mu))
val *= self._n_trials
return val | Working residuals. The working residuals are defined as
`resid_response`/link'(`mu`). See statsmodels.family.links for the
derivatives of the link functions. They are defined analytically. | resid_working | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def resid_anscombe(self):
"""
Anscombe residuals. See statsmodels.families.family for distribution-
specific Anscombe residuals. Currently, the unscaled residuals are
provided. In a future version, the scaled residuals will be provided.
"""
return self.resid_anscombe_scaled | Anscombe residuals. See statsmodels.families.family for distribution-
specific Anscombe residuals. Currently, the unscaled residuals are
provided. In a future version, the scaled residuals will be provided. | resid_anscombe | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def resid_anscombe_scaled(self):
"""
Scaled Anscombe residuals. See statsmodels.families.family for
distribution-specific Anscombe residuals.
"""
return self.family.resid_anscombe(self._endog, self.fittedvalues,
var_weights=self._var_weights,
scale=self.scale) | Scaled Anscombe residuals. See statsmodels.families.family for
distribution-specific Anscombe residuals. | resid_anscombe_scaled | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def resid_anscombe_unscaled(self):
"""
Unscaled Anscombe residuals. See statsmodels.families.family for
distribution-specific Anscombe residuals.
"""
return self.family.resid_anscombe(self._endog, self.fittedvalues,
var_weights=self._var_weights,
scale=1.) | Unscaled Anscombe residuals. See statsmodels.families.family for
distribution-specific Anscombe residuals. | resid_anscombe_unscaled | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def resid_deviance(self):
"""
Deviance residuals. See statsmodels.families.family for distribution-
specific deviance residuals.
"""
dev = self.family.resid_dev(self._endog, self.fittedvalues,
var_weights=self._var_weights,
scale=1.)
return dev | Deviance residuals. See statsmodels.families.family for distribution-
specific deviance residuals. | resid_deviance | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def pearson_chi2(self):
"""
Pearson's Chi-Squared statistic is defined as the sum of the squares
of the Pearson residuals.
"""
chisq = (self._endog - self.mu)**2 / self.family.variance(self.mu)
chisq *= self._iweights * self._n_trials
chisqsum = np.sum(chisq)
return chisqsum | Pearson's Chi-Squared statistic is defined as the sum of the squares
of the Pearson residuals. | pearson_chi2 | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def fittedvalues(self):
"""
The estimated mean response.
This is the value of the inverse of the link function at
lin_pred, where lin_pred is the linear predicted value
obtained by multiplying the design matrix by the coefficient
vector.
"""
return self.mu | The estimated mean response.
This is the value of the inverse of the link function at
lin_pred, where lin_pred is the linear predicted value
obtained by multiplying the design matrix by the coefficient
vector. | fittedvalues | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def mu(self):
"""
See GLM docstring.
"""
return self.model.predict(self.params) | See GLM docstring. | mu | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def null(self):
"""
Fitted values of the null model
"""
endog = self._endog
model = self.model
exog = np.ones((len(endog), 1))
kwargs = model._get_init_kwds().copy()
kwargs.pop('family')
for key in getattr(model, '_null_drop_keys', []):
del kwargs[key]
start_params = np.atleast_1d(self.family.link(endog.mean()))
oe = self.model._offset_exposure
if not (np.size(oe) == 1 and oe == 0):
with warnings.catch_warnings():
warnings.simplefilter("ignore", DomainWarning)
mod = GLM(endog, exog, family=self.family, **kwargs)
fitted = mod.fit(start_params=start_params).fittedvalues
else:
# correct if fitted is identical across observations
wls_model = lm.WLS(endog, exog,
weights=self._iweights * self._n_trials)
fitted = wls_model.fit().fittedvalues
return fitted | Fitted values of the null model | null | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def deviance(self):
"""
See statsmodels.families.family for the distribution-specific deviance
functions.
"""
return self.family.deviance(self._endog, self.mu, self._var_weights,
self._freq_weights) | See statsmodels.families.family for the distribution-specific deviance
functions. | deviance | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def null_deviance(self):
"""The value of the deviance function for the model fit with a constant
as the only regressor."""
return self.family.deviance(self._endog, self.null, self._var_weights,
self._freq_weights) | The value of the deviance function for the model fit with a constant
as the only regressor. | null_deviance | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def llnull(self):
"""
Log-likelihood of the model fit with a constant as the only regressor
"""
return self.family.loglike(self._endog, self.null,
var_weights=self._var_weights,
freq_weights=self._freq_weights,
scale=self.scale) | Log-likelihood of the model fit with a constant as the only regressor | llnull | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def llf_scaled(self, scale=None):
"""
Return the log-likelihood at the given scale, using the
estimated scale if the provided scale is None. In the Gaussian
case with linear link, the concentrated log-likelihood is
returned.
"""
_modelfamily = self.family
if scale is None:
if (isinstance(self.family, families.Gaussian) and
isinstance(self.family.link, families.links.Power) and
(self.family.link.power == 1.)):
# Scale for the concentrated Gaussian log likelihood
# (profile log likelihood with the scale parameter
# profiled out).
scale = (np.power(self._endog - self.mu, 2) * self._iweights).sum()
scale /= self.model.wnobs
else:
scale = self.scale
val = _modelfamily.loglike(self._endog, self.mu,
var_weights=self._var_weights,
freq_weights=self._freq_weights,
scale=scale)
return val | Return the log-likelihood at the given scale, using the
estimated scale if the provided scale is None. In the Gaussian
case with linear link, the concentrated log-likelihood is
returned. | llf_scaled | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def llf(self):
"""
Value of the loglikelihood function evalued at params.
See statsmodels.families.family for distribution-specific
loglikelihoods. The result uses the concentrated
log-likelihood if the family is Gaussian and the link is linear,
otherwise it uses the non-concentrated log-likelihood evaluated
at the estimated scale.
"""
return self.llf_scaled() | Value of the loglikelihood function evalued at params.
See statsmodels.families.family for distribution-specific
loglikelihoods. The result uses the concentrated
log-likelihood if the family is Gaussian and the link is linear,
otherwise it uses the non-concentrated log-likelihood evaluated
at the estimated scale. | llf | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def pseudo_rsquared(self, kind="cs"):
"""
Pseudo R-squared
Cox-Snell likelihood ratio pseudo R-squared is valid for both discrete
and continuous data. McFadden's pseudo R-squared is only valid for
discrete data.
Cox & Snell's pseudo-R-squared: 1 - exp((llnull - llf)*(2/nobs))
McFadden's pseudo-R-squared: 1 - (llf / llnull)
Parameters
----------
kind : P"cs", "mcf"}
Type of pseudo R-square to return
Returns
-------
float
Pseudo R-squared
"""
kind = kind.lower()
if kind.startswith("mcf"):
prsq = 1 - self.llf / self.llnull
elif kind.startswith("cox") or kind in ["cs", "lr"]:
prsq = 1 - np.exp((self.llnull - self.llf) * (2 / self.nobs))
else:
raise ValueError("only McFadden and Cox-Snell are available")
return prsq | Pseudo R-squared
Cox-Snell likelihood ratio pseudo R-squared is valid for both discrete
and continuous data. McFadden's pseudo R-squared is only valid for
discrete data.
Cox & Snell's pseudo-R-squared: 1 - exp((llnull - llf)*(2/nobs))
McFadden's pseudo-R-squared: 1 - (llf / llnull)
Parameters
----------
kind : P"cs", "mcf"}
Type of pseudo R-square to return
Returns
-------
float
Pseudo R-squared | pseudo_rsquared | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def aic(self):
"""
Akaike Information Criterion
-2 * `llf` + 2 * (`df_model` + 1)
"""
return self.info_criteria("aic") | Akaike Information Criterion
-2 * `llf` + 2 * (`df_model` + 1) | aic | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def bic(self):
"""
Bayes Information Criterion
`deviance` - `df_resid` * log(`nobs`)
.. warning::
The current definition is based on the deviance rather than the
log-likelihood. This is not consistent with the AIC definition,
and after 0.13 both will make use of the log-likelihood definition.
Notes
-----
The log-likelihood version is defined
-2 * `llf` + (`df_model` + 1)*log(n)
"""
if _use_bic_helper.use_bic_llf not in (True, False):
warnings.warn(
"The bic value is computed using the deviance formula. After "
"0.13 this will change to the log-likelihood based formula. "
"This change has no impact on the relative rank of models "
"compared using BIC. You can directly access the "
"log-likelihood version using the `bic_llf` attribute. You "
"can suppress this message by calling "
"statsmodels.genmod.generalized_linear_model.SET_USE_BIC_LLF "
"with True to get the LLF-based version now or False to retain"
"the deviance version.",
FutureWarning
)
if bool(_use_bic_helper.use_bic_llf):
return self.bic_llf
return self.bic_deviance | Bayes Information Criterion
`deviance` - `df_resid` * log(`nobs`)
.. warning::
The current definition is based on the deviance rather than the
log-likelihood. This is not consistent with the AIC definition,
and after 0.13 both will make use of the log-likelihood definition.
Notes
-----
The log-likelihood version is defined
-2 * `llf` + (`df_model` + 1)*log(n) | bic | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def bic_deviance(self):
"""
Bayes Information Criterion
Based on the deviance,
`deviance` - `df_resid` * log(`nobs`)
"""
return (self.deviance -
(self.model.wnobs - self.df_model - 1) *
np.log(self.model.wnobs)) | Bayes Information Criterion
Based on the deviance,
`deviance` - `df_resid` * log(`nobs`) | bic_deviance | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def bic_llf(self):
"""
Bayes Information Criterion
Based on the log-likelihood,
-2 * `llf` + log(n) * (`df_model` + 1)
"""
return self.info_criteria("bic") | Bayes Information Criterion
Based on the log-likelihood,
-2 * `llf` + log(n) * (`df_model` + 1) | bic_llf | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def info_criteria(self, crit, scale=None, dk_params=0):
"""Return an information criterion for the model.
Parameters
----------
crit : string
One of 'aic', 'bic', or 'qaic'.
scale : float
The scale parameter estimated using the parent model,
used only for qaic.
dk_params : int or float
Correction to the number of parameters used in the information
criterion. By default, only mean parameters are included, the
scale parameter is not included in the parameter count.
Use ``dk_params=1`` to include scale in the parameter count.
Returns
-------
Value of information criterion.
Notes
-----
The quasi-Akaike Information criterion (qaic) is -2 *
`llf`/`scale` + 2 * (`df_model` + 1). It may not give
meaningful results except for Poisson and related models.
The QAIC (ic_type='qaic') must be evaluated with a provided
scale parameter. Two QAIC values are only comparable if they
are calculated using the same scale parameter. The scale
parameter should be estimated using the largest model among
all models being compared.
References
----------
Burnham KP, Anderson KR (2002). Model Selection and Multimodel
Inference; Springer New York.
"""
crit = crit.lower()
k_params = self.df_model + 1 + dk_params
if crit == "aic":
return -2 * self.llf + 2 * k_params
elif crit == "bic":
nobs = self.df_model + self.df_resid + 1
bic = -2*self.llf + k_params*np.log(nobs)
return bic
elif crit == "qaic":
f = self.model.family
fl = (families.Poisson, families.NegativeBinomial,
families.Binomial)
if not isinstance(f, fl):
msg = "QAIC is only valid for Binomial, Poisson and "
msg += "Negative Binomial families."
warnings.warn(msg)
llf = self.llf_scaled(scale=1)
return -2 * llf/scale + 2 * k_params | Return an information criterion for the model.
Parameters
----------
crit : string
One of 'aic', 'bic', or 'qaic'.
scale : float
The scale parameter estimated using the parent model,
used only for qaic.
dk_params : int or float
Correction to the number of parameters used in the information
criterion. By default, only mean parameters are included, the
scale parameter is not included in the parameter count.
Use ``dk_params=1`` to include scale in the parameter count.
Returns
-------
Value of information criterion.
Notes
-----
The quasi-Akaike Information criterion (qaic) is -2 *
`llf`/`scale` + 2 * (`df_model` + 1). It may not give
meaningful results except for Poisson and related models.
The QAIC (ic_type='qaic') must be evaluated with a provided
scale parameter. Two QAIC values are only comparable if they
are calculated using the same scale parameter. The scale
parameter should be estimated using the largest model among
all models being compared.
References
----------
Burnham KP, Anderson KR (2002). Model Selection and Multimodel
Inference; Springer New York. | info_criteria | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def get_prediction(self, exog=None, exposure=None, offset=None,
transform=True, which=None, linear=None,
average=False, agg_weights=None,
row_labels=None):
"""
Compute prediction results for GLM compatible models.
Options and return class depend on whether "which" is None or not.
Parameters
----------
exog : array_like, optional
The values for which you want to predict.
exposure : array_like, optional
Exposure time values, only can be used with the log link
function.
offset : array_like, optional
Offset values.
transform : bool, optional
If the model was fit via a formula, do you want to pass
exog through the formula. Default is True. E.g., if you fit
a model y ~ log(x1) + log(x2), and transform is True, then
you can pass a data structure that contains x1 and x2 in
their original form. Otherwise, you'd need to log the data
first.
which : 'mean', 'linear', 'var'(optional)
Statitistic to predict. Default is 'mean'.
If which is None, then the deprecated keyword "linear" applies.
If which is not None, then a generic Prediction results class will
be returned. Some options are only available if which is not None.
See notes.
- 'mean' returns the conditional expectation of endog E(y | x),
i.e. inverse of the model's link function of linear predictor.
- 'linear' returns the linear predictor of the mean function.
- 'var_unscaled' variance of endog implied by the likelihood model.
This does not include scale or var_weights.
linear : bool
The ``linear` keyword is deprecated and will be removed,
use ``which`` keyword instead.
If which is None, then the linear keyword is used, otherwise it will
be ignored.
If True and which is None, the linear predicted values are returned.
If False or None, then the statistic specified by ``which`` will be
returned.
average : bool
Keyword is only used if ``which`` is not None.
If average is True, then the mean prediction is computed, that is,
predictions are computed for individual exog and then the average
over observation is used.
If average is False, then the results are the predictions for all
observations, i.e. same length as ``exog``.
agg_weights : ndarray, optional
Keyword is only used if ``which`` is not None.
Aggregation weights, only used if average is True.
row_labels : list of str or None
If row_lables are provided, then they will replace the generated
labels.
Returns
-------
prediction_results : instance of a PredictionResults class.
The prediction results instance contains prediction and prediction
variance and can on demand calculate confidence intervals and summary
tables for the prediction of the mean and of new observations.
The Results class of the return depends on the value of ``which``.
See Also
--------
GLM.predict
GLMResults.predict
Notes
-----
Changes in statsmodels 0.14: The ``which`` keyword has been added.
If ``which`` is None, then the behavior is the same as in previous
versions, and returns the mean and linear prediction results.
If the ``which`` keyword is not None, then a generic prediction results
class is returned and is not backwards compatible with the old prediction
results class, e.g. column names of summary_frame differs.
There are more choices for the returned predicted statistic using
``which``. More choices will be added in the next release.
Two additional keyword, average and agg_weights options are now also
available if ``which`` is not None.
In a future version ``which`` will become not None and the backwards
compatible prediction results class will be removed.
"""
import statsmodels.regression._prediction as linpred
pred_kwds = {'exposure': exposure, 'offset': offset, 'which': 'linear'}
if which is None:
# two calls to a get_prediction duplicates exog generation if patsy
res_linpred = linpred.get_prediction(self, exog=exog,
transform=transform,
row_labels=row_labels,
pred_kwds=pred_kwds)
pred_kwds['which'] = 'mean'
res = pred.get_prediction_glm(self, exog=exog, transform=transform,
row_labels=row_labels,
linpred=res_linpred,
link=self.model.family.link,
pred_kwds=pred_kwds)
else:
# new generic version, if 'which' is specified
pred_kwds = {'exposure': exposure, 'offset': offset}
# not yet, only applies to count families
# y_values is explicit so we can add it to the docstring
# if y_values is not None:
# pred_kwds["y_values"] = y_values
res = pred.get_prediction(
self,
exog=exog,
which=which,
transform=transform,
row_labels=row_labels,
average=average,
agg_weights=agg_weights,
pred_kwds=pred_kwds
)
return res | Compute prediction results for GLM compatible models.
Options and return class depend on whether "which" is None or not.
Parameters
----------
exog : array_like, optional
The values for which you want to predict.
exposure : array_like, optional
Exposure time values, only can be used with the log link
function.
offset : array_like, optional
Offset values.
transform : bool, optional
If the model was fit via a formula, do you want to pass
exog through the formula. Default is True. E.g., if you fit
a model y ~ log(x1) + log(x2), and transform is True, then
you can pass a data structure that contains x1 and x2 in
their original form. Otherwise, you'd need to log the data
first.
which : 'mean', 'linear', 'var'(optional)
Statitistic to predict. Default is 'mean'.
If which is None, then the deprecated keyword "linear" applies.
If which is not None, then a generic Prediction results class will
be returned. Some options are only available if which is not None.
See notes.
- 'mean' returns the conditional expectation of endog E(y | x),
i.e. inverse of the model's link function of linear predictor.
- 'linear' returns the linear predictor of the mean function.
- 'var_unscaled' variance of endog implied by the likelihood model.
This does not include scale or var_weights.
linear : bool
The ``linear` keyword is deprecated and will be removed,
use ``which`` keyword instead.
If which is None, then the linear keyword is used, otherwise it will
be ignored.
If True and which is None, the linear predicted values are returned.
If False or None, then the statistic specified by ``which`` will be
returned.
average : bool
Keyword is only used if ``which`` is not None.
If average is True, then the mean prediction is computed, that is,
predictions are computed for individual exog and then the average
over observation is used.
If average is False, then the results are the predictions for all
observations, i.e. same length as ``exog``.
agg_weights : ndarray, optional
Keyword is only used if ``which`` is not None.
Aggregation weights, only used if average is True.
row_labels : list of str or None
If row_lables are provided, then they will replace the generated
labels.
Returns
-------
prediction_results : instance of a PredictionResults class.
The prediction results instance contains prediction and prediction
variance and can on demand calculate confidence intervals and summary
tables for the prediction of the mean and of new observations.
The Results class of the return depends on the value of ``which``.
See Also
--------
GLM.predict
GLMResults.predict
Notes
-----
Changes in statsmodels 0.14: The ``which`` keyword has been added.
If ``which`` is None, then the behavior is the same as in previous
versions, and returns the mean and linear prediction results.
If the ``which`` keyword is not None, then a generic prediction results
class is returned and is not backwards compatible with the old prediction
results class, e.g. column names of summary_frame differs.
There are more choices for the returned predicted statistic using
``which``. More choices will be added in the next release.
Two additional keyword, average and agg_weights options are now also
available if ``which`` is not None.
In a future version ``which`` will become not None and the backwards
compatible prediction results class will be removed. | get_prediction | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def get_hat_matrix_diag(self, observed=True):
"""
Compute the diagonal of the hat matrix
Parameters
----------
observed : bool
If true, then observed hessian is used in the hat matrix
computation. If false, then the expected hessian is used.
In the case of a canonical link function both are the same.
Returns
-------
hat_matrix_diag : ndarray
The diagonal of the hat matrix computed from the observed
or expected hessian.
"""
weights = self.model.hessian_factor(self.params, observed=observed)
wexog = np.sqrt(weights)[:, None] * self.model.exog
hd = (wexog * np.linalg.pinv(wexog).T).sum(1)
return hd | Compute the diagonal of the hat matrix
Parameters
----------
observed : bool
If true, then observed hessian is used in the hat matrix
computation. If false, then the expected hessian is used.
In the case of a canonical link function both are the same.
Returns
-------
hat_matrix_diag : ndarray
The diagonal of the hat matrix computed from the observed
or expected hessian. | get_hat_matrix_diag | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def get_influence(self, observed=True):
"""
Get an instance of GLMInfluence with influence and outlier measures
Parameters
----------
observed : bool
If true, then observed hessian is used in the hat matrix
computation. If false, then the expected hessian is used.
In the case of a canonical link function both are the same.
Returns
-------
infl : GLMInfluence instance
The instance has methods to calculate the main influence and
outlier measures as attributes.
See Also
--------
statsmodels.stats.outliers_influence.GLMInfluence
"""
from statsmodels.stats.outliers_influence import GLMInfluence
weights = self.model.hessian_factor(self.params, observed=observed)
weights_sqrt = np.sqrt(weights)
wexog = weights_sqrt[:, None] * self.model.exog
wendog = weights_sqrt * self.model.endog
# using get_hat_matrix_diag has duplicated computation
hat_matrix_diag = self.get_hat_matrix_diag(observed=observed)
infl = GLMInfluence(self, endog=wendog, exog=wexog,
resid=self.resid_pearson / np.sqrt(self.scale),
hat_matrix_diag=hat_matrix_diag)
return infl | Get an instance of GLMInfluence with influence and outlier measures
Parameters
----------
observed : bool
If true, then observed hessian is used in the hat matrix
computation. If false, then the expected hessian is used.
In the case of a canonical link function both are the same.
Returns
-------
infl : GLMInfluence instance
The instance has methods to calculate the main influence and
outlier measures as attributes.
See Also
--------
statsmodels.stats.outliers_influence.GLMInfluence | get_influence | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def get_distribution(self, exog=None, exposure=None,
offset=None, var_weights=1., n_trials=1.):
"""
Return a instance of the predictive distribution.
Parameters
----------
scale : scalar
The scale parameter.
exog : array_like
The predictor variable matrix.
offset : array_like or None
Offset variable for predicted mean.
exposure : array_like or None
Log(exposure) will be added to the linear prediction.
var_weights : array_like
1d array of variance (analytic) weights. The default is None.
n_trials : int
Number of trials for the binomial distribution. The default is 1
which corresponds to a Bernoulli random variable.
Returns
-------
gen
Instance of a scipy frozen distribution based on estimated
parameters.
Use the ``rvs`` method to generate random values.
Notes
-----
Due to the behavior of ``scipy.stats.distributions objects``, the
returned random number generator must be called with ``gen.rvs(n)``
where ``n`` is the number of observations in the data set used
to fit the model. If any other value is used for ``n``, misleading
results will be produced.
"""
# Note this is mostly a copy of GLM.get_prediction
# calling here results.predict avoids the exog check and trasnform
if isinstance(self.model.family, (families.Binomial, families.Poisson,
families.NegativeBinomial)):
# use scale=1, independent of QMLE scale for discrete
scale = 1.
if self.scale != 1.:
msg = "using scale=1, no exess dispersion in distribution"
warnings.warn(msg, UserWarning)
else:
scale = self.scale
mu = self.predict(exog, exposure, offset, which="mean")
kwds = {}
if (np.any(n_trials != 1) and
isinstance(self.model.family, families.Binomial)):
kwds["n_trials"] = n_trials
distr = self.model.family.get_distribution(
mu, scale, var_weights=var_weights, **kwds)
return distr | Return a instance of the predictive distribution.
Parameters
----------
scale : scalar
The scale parameter.
exog : array_like
The predictor variable matrix.
offset : array_like or None
Offset variable for predicted mean.
exposure : array_like or None
Log(exposure) will be added to the linear prediction.
var_weights : array_like
1d array of variance (analytic) weights. The default is None.
n_trials : int
Number of trials for the binomial distribution. The default is 1
which corresponds to a Bernoulli random variable.
Returns
-------
gen
Instance of a scipy frozen distribution based on estimated
parameters.
Use the ``rvs`` method to generate random values.
Notes
-----
Due to the behavior of ``scipy.stats.distributions objects``, the
returned random number generator must be called with ``gen.rvs(n)``
where ``n`` is the number of observations in the data set used
to fit the model. If any other value is used for ``n``, misleading
results will be produced. | get_distribution | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def get_margeff(self, at='overall', method='dydx', atexog=None,
dummy=False, count=False):
"""Get marginal effects of the fitted model.
Warning: offset, exposure and weights (var_weights and freq_weights)
are not supported by margeff.
Parameters
----------
at : str, optional
Options are:
- 'overall', The average of the marginal effects at each
observation.
- 'mean', The marginal effects at the mean of each regressor.
- 'median', The marginal effects at the median of each regressor.
- 'zero', The marginal effects at zero for each regressor.
- 'all', The marginal effects at each observation. If `at` is all
only margeff will be available from the returned object.
Note that if `exog` is specified, then marginal effects for all
variables not specified by `exog` are calculated using the `at`
option.
method : str, optional
Options are:
- 'dydx' - dy/dx - No transformation is made and marginal effects
are returned. This is the default.
- 'eyex' - estimate elasticities of variables in `exog` --
d(lny)/d(lnx)
- 'dyex' - estimate semi-elasticity -- dy/d(lnx)
- 'eydx' - estimate semi-elasticity -- d(lny)/dx
Note that tranformations are done after each observation is
calculated. Semi-elasticities for binary variables are computed
using the midpoint method. 'dyex' and 'eyex' do not make sense
for discrete variables. For interpretations of these methods
see notes below.
atexog : array_like, optional
Optionally, you can provide the exogenous variables over which to
get the marginal effects. This should be a dictionary with the key
as the zero-indexed column number and the value of the dictionary.
Default is None for all independent variables less the constant.
dummy : bool, optional
If False, treats binary variables (if present) as continuous. This
is the default. Else if True, treats binary variables as
changing from 0 to 1. Note that any variable that is either 0 or 1
is treated as binary. Each binary variable is treated separately
for now.
count : bool, optional
If False, treats count variables (if present) as continuous. This
is the default. Else if True, the marginal effect is the
change in probabilities when each observation is increased by one.
Returns
-------
DiscreteMargins : marginal effects instance
Returns an object that holds the marginal effects, standard
errors, confidence intervals, etc. See
`statsmodels.discrete.discrete_margins.DiscreteMargins` for more
information.
Notes
-----
Interpretations of methods:
- 'dydx' - change in `endog` for a change in `exog`.
- 'eyex' - proportional change in `endog` for a proportional change
in `exog`.
- 'dyex' - change in `endog` for a proportional change in `exog`.
- 'eydx' - proportional change in `endog` for a change in `exog`.
When using after Poisson, returns the expected number of events per
period, assuming that the model is loglinear.
Status : unsupported features offset, exposure and weights. Default
handling of freq_weights for average effect "overall" might change.
"""
if getattr(self.model, "offset", None) is not None:
raise NotImplementedError("Margins with offset are not available.")
if (np.any(self.model.var_weights != 1) or
np.any(self.model.freq_weights != 1)):
warnings.warn("weights are not taken into account by margeff")
from statsmodels.discrete.discrete_margins import DiscreteMargins
return DiscreteMargins(self, (at, method, atexog, dummy, count)) | Get marginal effects of the fitted model.
Warning: offset, exposure and weights (var_weights and freq_weights)
are not supported by margeff.
Parameters
----------
at : str, optional
Options are:
- 'overall', The average of the marginal effects at each
observation.
- 'mean', The marginal effects at the mean of each regressor.
- 'median', The marginal effects at the median of each regressor.
- 'zero', The marginal effects at zero for each regressor.
- 'all', The marginal effects at each observation. If `at` is all
only margeff will be available from the returned object.
Note that if `exog` is specified, then marginal effects for all
variables not specified by `exog` are calculated using the `at`
option.
method : str, optional
Options are:
- 'dydx' - dy/dx - No transformation is made and marginal effects
are returned. This is the default.
- 'eyex' - estimate elasticities of variables in `exog` --
d(lny)/d(lnx)
- 'dyex' - estimate semi-elasticity -- dy/d(lnx)
- 'eydx' - estimate semi-elasticity -- d(lny)/dx
Note that tranformations are done after each observation is
calculated. Semi-elasticities for binary variables are computed
using the midpoint method. 'dyex' and 'eyex' do not make sense
for discrete variables. For interpretations of these methods
see notes below.
atexog : array_like, optional
Optionally, you can provide the exogenous variables over which to
get the marginal effects. This should be a dictionary with the key
as the zero-indexed column number and the value of the dictionary.
Default is None for all independent variables less the constant.
dummy : bool, optional
If False, treats binary variables (if present) as continuous. This
is the default. Else if True, treats binary variables as
changing from 0 to 1. Note that any variable that is either 0 or 1
is treated as binary. Each binary variable is treated separately
for now.
count : bool, optional
If False, treats count variables (if present) as continuous. This
is the default. Else if True, the marginal effect is the
change in probabilities when each observation is increased by one.
Returns
-------
DiscreteMargins : marginal effects instance
Returns an object that holds the marginal effects, standard
errors, confidence intervals, etc. See
`statsmodels.discrete.discrete_margins.DiscreteMargins` for more
information.
Notes
-----
Interpretations of methods:
- 'dydx' - change in `endog` for a change in `exog`.
- 'eyex' - proportional change in `endog` for a proportional change
in `exog`.
- 'dyex' - change in `endog` for a proportional change in `exog`.
- 'eydx' - proportional change in `endog` for a change in `exog`.
When using after Poisson, returns the expected number of events per
period, assuming that the model is loglinear.
Status : unsupported features offset, exposure and weights. Default
handling of freq_weights for average effect "overall" might change. | get_margeff | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def summary(self, yname=None, xname=None, title=None, alpha=.05):
"""
Summarize the Regression Results
Parameters
----------
yname : str, optional
Default is `y`
xname : list[str], optional
Names for the exogenous variables, default is `var_#` for ## in
the number of regressors. Must match the number of parameters in
the model
title : str, optional
Title for the top table. If not None, then this replaces the
default title
alpha : float
significance level for the confidence intervals
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be printed or
converted to various output formats.
See Also
--------
statsmodels.iolib.summary.Summary : class to hold summary results
"""
top_left = [('Dep. Variable:', None),
('Model:', None),
('Model Family:', [self.family.__class__.__name__]),
('Link Function:', [self.family.link.__class__.__name__]),
('Method:', [self.method]),
('Date:', None),
('Time:', None),
('No. Iterations:',
["%d" % self.fit_history['iteration']]),
]
try:
prsquared = self.pseudo_rsquared(kind="cs")
except ValueError:
prsquared = np.nan
top_right = [('No. Observations:', None),
('Df Residuals:', None),
('Df Model:', None),
('Scale:', ["%#8.5g" % self.scale]),
('Log-Likelihood:', None),
('Deviance:', ["%#8.5g" % self.deviance]),
('Pearson chi2:', ["%#6.3g" % self.pearson_chi2]),
('Pseudo R-squ. (CS):', ["%#6.4g" % prsquared])
]
if hasattr(self, 'cov_type'):
top_left.append(('Covariance Type:', [self.cov_type]))
if title is None:
title = "Generalized Linear Model Regression Results"
# create summary tables
from statsmodels.iolib.summary import Summary
smry = Summary()
smry.add_table_2cols(self, gleft=top_left, gright=top_right,
yname=yname, xname=xname, title=title)
smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha,
use_t=self.use_t)
if hasattr(self, 'constraints'):
smry.add_extra_txt(['Model has been estimated subject to linear '
'equality constraints.'])
return smry | Summarize the Regression Results
Parameters
----------
yname : str, optional
Default is `y`
xname : list[str], optional
Names for the exogenous variables, default is `var_#` for ## in
the number of regressors. Must match the number of parameters in
the model
title : str, optional
Title for the top table. If not None, then this replaces the
default title
alpha : float
significance level for the confidence intervals
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be printed or
converted to various output formats.
See Also
--------
statsmodels.iolib.summary.Summary : class to hold summary results | summary | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def summary2(self, yname=None, xname=None, title=None, alpha=.05,
float_format="%.4f"):
"""Experimental summary for regression Results
Parameters
----------
yname : str
Name of the dependent variable (optional)
xname : list[str], optional
Names for the exogenous variables, default is `var_#` for ## in
the number of regressors. Must match the number of parameters in
the model
title : str, optional
Title for the top table. If not None, then this replaces the
default title
alpha : float
significance level for the confidence intervals
float_format : str
print format for floats in parameters summary
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be printed or
converted to various output formats.
See Also
--------
statsmodels.iolib.summary2.Summary : class to hold summary results
"""
from statsmodels.iolib import summary2
smry = summary2.Summary()
with warnings.catch_warnings():
warnings.simplefilter("ignore", FutureWarning)
smry.add_base(results=self, alpha=alpha, float_format=float_format,
xname=xname, yname=yname, title=title)
if hasattr(self, 'constraints'):
smry.add_text('Model has been estimated subject to linear '
'equality constraints.')
return smry | Experimental summary for regression Results
Parameters
----------
yname : str
Name of the dependent variable (optional)
xname : list[str], optional
Names for the exogenous variables, default is `var_#` for ## in
the number of regressors. Must match the number of parameters in
the model
title : str, optional
Title for the top table. If not None, then this replaces the
default title
alpha : float
significance level for the confidence intervals
float_format : str
print format for floats in parameters summary
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be printed or
converted to various output formats.
See Also
--------
statsmodels.iolib.summary2.Summary : class to hold summary results | summary2 | python | statsmodels/statsmodels | statsmodels/genmod/generalized_linear_model.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/generalized_linear_model.py | BSD-3-Clause |
def mat(self, dim, term):
"""
Returns the term'th basis matrix, which is a dim x dim
matrix.
"""
raise NotImplementedError | Returns the term'th basis matrix, which is a dim x dim
matrix. | mat | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def objective(self, params):
"""
Calculate the gradient of the QIF objective function.
Parameters
----------
params : array_like
The model parameters at which the gradient is evaluated.
Returns
-------
grad : array_like
The gradient vector of the QIF objective function.
gn_deriv : array_like
The gradients of each estimating equation with
respect to the parameter.
"""
endog = self.endog
exog = self.exog
lpr = np.dot(exog, params)
mean = self.family.link.inverse(lpr)
va = self.family.variance(mean)
# Mean derivative
idl = self.family.link.inverse_deriv(lpr)
idl2 = self.family.link.inverse_deriv2(lpr)
vd = self.family.variance.deriv(mean)
m = self.cov_struct.num_terms
p = exog.shape[1]
d = p * m
gn = np.zeros(d)
gi = np.zeros(d)
gi_deriv = np.zeros((d, p))
gn_deriv = np.zeros((d, p))
cn_deriv = [0] * p
cmat = np.zeros((d, d))
fastvar = self.family.variance is varfuncs.constant
fastlink = isinstance(
self.family.link,
# TODO: Remove links.identity after deprecation final
(links.Identity, links.identity)
)
for ix in self.groups_ix:
sd = np.sqrt(va[ix])
resid = endog[ix] - mean[ix]
sresid = resid / sd
deriv = exog[ix, :] * idl[ix, None]
jj = 0
for j in range(m):
# The derivative of each term in (5) of Qu et al.
# There are four terms involving beta in a product.
# Iterated application of the product rule gives
# the gradient as a sum of four terms.
c = self.cov_struct.mat(len(ix), j)
crs1 = np.dot(c, sresid) / sd
gi[jj:jj+p] = np.dot(deriv.T, crs1)
crs2 = np.dot(c, -deriv / sd[:, None]) / sd[:, None]
gi_deriv[jj:jj+p, :] = np.dot(deriv.T, crs2)
if not (fastlink and fastvar):
for k in range(p):
m1 = np.dot(exog[ix, :].T,
idl2[ix] * exog[ix, k] * crs1)
if not fastvar:
vx = -0.5 * vd[ix] * deriv[:, k] / va[ix]**1.5
m2 = np.dot(deriv.T, vx * np.dot(c, sresid))
m3 = np.dot(deriv.T, np.dot(c, vx * resid) / sd)
else:
m2, m3 = 0, 0
gi_deriv[jj:jj+p, k] += m1 + m2 + m3
jj += p
for j in range(p):
u = np.outer(gi, gi_deriv[:, j])
cn_deriv[j] += u + u.T
gn += gi
gn_deriv += gi_deriv
cmat += np.outer(gi, gi)
ngrp = len(self.groups_ix)
gn /= ngrp
gn_deriv /= ngrp
cmat /= ngrp**2
qif = np.dot(gn, np.linalg.solve(cmat, gn))
gcg = np.zeros(p)
for j in range(p):
cn_deriv[j] /= len(self.groups_ix)**2
u = np.linalg.solve(cmat, cn_deriv[j]).T
u = np.linalg.solve(cmat, u)
gcg[j] = np.dot(gn, np.dot(u, gn))
grad = 2 * np.dot(gn_deriv.T, np.linalg.solve(cmat, gn)) - gcg
return qif, grad, cmat, gn, gn_deriv | Calculate the gradient of the QIF objective function.
Parameters
----------
params : array_like
The model parameters at which the gradient is evaluated.
Returns
-------
grad : array_like
The gradient vector of the QIF objective function.
gn_deriv : array_like
The gradients of each estimating equation with
respect to the parameter. | objective | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def estimate_scale(self, params):
"""
Estimate the dispersion/scale.
The scale parameter for binomial and Poisson families is
fixed at 1, otherwise it is estimated from the data.
"""
if isinstance(self.family, (families.Binomial, families.Poisson)):
return 1.
if hasattr(self, "ddof_scale"):
ddof_scale = self.ddof_scale
else:
ddof_scale = self.exog[1]
lpr = np.dot(self.exog, params)
mean = self.family.link.inverse(lpr)
resid = self.endog - mean
scale = np.sum(resid**2) / (self.nobs - ddof_scale)
return scale | Estimate the dispersion/scale.
The scale parameter for binomial and Poisson families is
fixed at 1, otherwise it is estimated from the data. | estimate_scale | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def from_formula(cls, formula, groups, data, subset=None,
*args, **kwargs):
"""
Create a QIF model instance from a formula and dataframe.
Parameters
----------
formula : str or generic Formula object
The formula specifying the model
groups : array_like or string
Array of grouping labels. If a string, this is the name
of a variable in `data` that contains the grouping labels.
data : array_like
The data for the model.
subset : array_like
An array_like object of booleans, integers, or index
values that indicate the subset of the data to used when
fitting the model.
Returns
-------
model : QIF model instance
"""
if isinstance(groups, str):
groups = data[groups]
advance_eval_env(kwargs)
model = super().from_formula(
formula, data=data, subset=subset,
groups=groups, *args, **kwargs)
return model | Create a QIF model instance from a formula and dataframe.
Parameters
----------
formula : str or generic Formula object
The formula specifying the model
groups : array_like or string
Array of grouping labels. If a string, this is the name
of a variable in `data` that contains the grouping labels.
data : array_like
The data for the model.
subset : array_like
An array_like object of booleans, integers, or index
values that indicate the subset of the data to used when
fitting the model.
Returns
-------
model : QIF model instance | from_formula | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def fit(self, maxiter=100, start_params=None, tol=1e-6, gtol=1e-4,
ddof_scale=None):
"""
Fit a GLM to correlated data using QIF.
Parameters
----------
maxiter : int
Maximum number of iterations.
start_params : array_like, optional
Starting values
tol : float
Convergence threshold for difference of successive
estimates.
gtol : float
Convergence threshold for gradient.
ddof_scale : int, optional
Degrees of freedom for the scale parameter
Returns
-------
QIFResults object
"""
if ddof_scale is None:
self.ddof_scale = self.exog.shape[1]
else:
self.ddof_scale = ddof_scale
if start_params is None:
model = GLM(self.endog, self.exog, family=self.family)
result = model.fit()
params = result.params
else:
params = start_params
for _ in range(maxiter):
qif, grad, cmat, _, gn_deriv = self.objective(params)
gnorm = np.sqrt(np.sum(grad * grad))
self._fit_history["qif"].append(qif)
self._fit_history["gradnorm"].append(gnorm)
if gnorm < gtol:
break
cjac = 2 * np.dot(gn_deriv.T, np.linalg.solve(cmat, gn_deriv))
step = np.linalg.solve(cjac, grad)
snorm = np.sqrt(np.sum(step * step))
self._fit_history["stepnorm"].append(snorm)
if snorm < tol:
break
params -= step
vcov = np.dot(gn_deriv.T, np.linalg.solve(cmat, gn_deriv))
vcov = np.linalg.inv(vcov)
scale = self.estimate_scale(params)
rslt = QIFResults(self, params, vcov / scale, scale)
rslt.fit_history = self._fit_history
self._fit_history = defaultdict(list)
return QIFResultsWrapper(rslt) | Fit a GLM to correlated data using QIF.
Parameters
----------
maxiter : int
Maximum number of iterations.
start_params : array_like, optional
Starting values
tol : float
Convergence threshold for difference of successive
estimates.
gtol : float
Convergence threshold for gradient.
ddof_scale : int, optional
Degrees of freedom for the scale parameter
Returns
-------
QIFResults object | fit | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def aic(self):
"""
An AIC-like statistic for models fit using QIF.
"""
if isinstance(self.model.cov_struct, QIFIndependence):
msg = "AIC not available with QIFIndependence covariance"
raise ValueError(msg)
df = self.model.exog.shape[1]
return self.qif + 2*df | An AIC-like statistic for models fit using QIF. | aic | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def bic(self):
"""
A BIC-like statistic for models fit using QIF.
"""
if isinstance(self.model.cov_struct, QIFIndependence):
msg = "BIC not available with QIFIndependence covariance"
raise ValueError(msg)
df = self.model.exog.shape[1]
return self.qif + np.log(self.model.nobs)*df | A BIC-like statistic for models fit using QIF. | bic | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def fittedvalues(self):
"""
Returns the fitted values from the model.
"""
return self.model.family.link.inverse(
np.dot(self.model.exog, self.params)) | Returns the fitted values from the model. | fittedvalues | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def summary(self, yname=None, xname=None, title=None, alpha=.05):
"""
Summarize the QIF regression results
Parameters
----------
yname : str, optional
Default is `y`
xname : list[str], optional
Names for the exogenous variables, default is `var_#` for ## in
the number of regressors. Must match the number of parameters in
the model
title : str, optional
Title for the top table. If not None, then this replaces
the default title
alpha : float
significance level for the confidence intervals
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be
printed or converted to various output formats.
See Also
--------
statsmodels.iolib.summary.Summary : class to hold summary results
"""
top_left = [('Dep. Variable:', None),
('Method:', ['QIF']),
('Family:', [self.model.family.__class__.__name__]),
('Covariance structure:',
[self.model.cov_struct.__class__.__name__]),
('Date:', None),
('Time:', None),
]
NY = [len(y) for y in self.model.groups_ix]
top_right = [('No. Observations:', [sum(NY)]),
('No. clusters:', [len(NY)]),
('Min. cluster size:', [min(NY)]),
('Max. cluster size:', [max(NY)]),
('Mean cluster size:', ["%.1f" % np.mean(NY)]),
('Scale:', ["%.3f" % self.scale]),
]
if title is None:
title = self.model.__class__.__name__ + ' ' +\
"Regression Results"
# Override the exog variable names if xname is provided as an
# argument.
if xname is None:
xname = self.model.exog_names
if yname is None:
yname = self.model.endog_names
# Create summary table instance
from statsmodels.iolib.summary import Summary
smry = Summary()
smry.add_table_2cols(self, gleft=top_left, gright=top_right,
yname=yname, xname=xname,
title=title)
smry.add_table_params(self, yname=yname, xname=xname,
alpha=alpha, use_t=False)
return smry | Summarize the QIF regression results
Parameters
----------
yname : str, optional
Default is `y`
xname : list[str], optional
Names for the exogenous variables, default is `var_#` for ## in
the number of regressors. Must match the number of parameters in
the model
title : str, optional
Title for the top table. If not None, then this replaces
the default title
alpha : float
significance level for the confidence intervals
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be
printed or converted to various output formats.
See Also
--------
statsmodels.iolib.summary.Summary : class to hold summary results | summary | python | statsmodels/statsmodels | statsmodels/genmod/qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/qif.py | BSD-3-Clause |
def check_constraint(da, va, ga):
"""
Check the score testing of the parameter constraints.
""" | Check the score testing of the parameter constraints. | check_constraint | python | statsmodels/statsmodels | statsmodels/genmod/tests/gee_simulation_check.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/gee_simulation_check.py | BSD-3-Clause |
def setup_class(cls):
"""
Test Gaussian family with canonical identity link
"""
# Test Precisions
cls.decimal_resids = DECIMAL_3
cls.decimal_params = DECIMAL_2
cls.decimal_bic = DECIMAL_0
cls.decimal_bse = DECIMAL_3
from statsmodels.datasets.longley import load
cls.data = load()
cls.data.endog = np.require(cls.data.endog, requirements="W")
cls.data.exog = np.require(cls.data.exog, requirements="W")
cls.data.exog = add_constant(cls.data.exog, prepend=False)
cls.res1 = GLM(
cls.data.endog, cls.data.exog, family=sm.families.Gaussian()
).fit()
from .results.results_glm import Longley
cls.res2 = Longley() | Test Gaussian family with canonical identity link | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Test Gaussian family with canonical identity link
"""
# Test Precisions
cls.decimal_resids = DECIMAL_3
cls.decimal_params = DECIMAL_2
cls.decimal_bic = DECIMAL_0
cls.decimal_bse = DECIMAL_2
from statsmodels.datasets.longley import load
cls.data = load()
cls.data.endog = np.require(cls.data.endog, requirements="W")
cls.data.exog = np.require(cls.data.exog, requirements="W")
cls.data.exog = add_constant(cls.data.exog, prepend=False)
cls.res1 = GLM(
cls.data.endog, cls.data.exog, family=sm.families.Gaussian()
).fit(method="newton")
from .results.results_glm import Longley
cls.res2 = Longley() | Test Gaussian family with canonical identity link | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Test Binomial family with canonical logit link using star98 dataset.
"""
cls.decimal_resids = DECIMAL_1
cls.decimal_bic = DECIMAL_2
from statsmodels.datasets.star98 import load
from .results.results_glm import Star98
data = load()
data.endog = np.require(data.endog, requirements="W")
data.exog = np.require(data.exog, requirements="W")
data.exog = add_constant(data.exog, prepend=False)
cls.res1 = GLM(data.endog, data.exog, family=sm.families.Binomial()).fit()
# NOTE: if you want to replicate with RModel
# res2 = RModel(data.endog[:,0]/trials, data.exog, r.glm,
# family=r.binomial, weights=trials)
cls.res2 = Star98() | Test Binomial family with canonical logit link using star98 dataset. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Gamma family with canonical inverse link (power -1)
"""
# Test Precisions
cls.decimal_aic_R = -1 # TODO: off by about 1, we are right with Stata
cls.decimal_resids = DECIMAL_2
from statsmodels.datasets.scotland import load
from .results.results_glm import Scotvote
data = load()
data.exog = add_constant(data.exog, prepend=False)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res1 = GLM(data.endog, data.exog, family=sm.families.Gamma()).fit()
cls.res1 = res1
# res2 = RModel(data.endog, data.exog, r.glm, family=r.Gamma)
res2 = Scotvote()
res2.aic_R += 2 # R does not count degree of freedom for scale with gamma
cls.res2 = res2 | Tests Gamma family with canonical inverse link (power -1) | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Poisson family with canonical log link.
Test results were obtained by R.
"""
from .results.results_glm import Cpunish
cls.data = cpunish.load()
cls.data.endog = np.require(cls.data.endog, requirements="W")
cls.data.exog = np.require(cls.data.exog, requirements="W")
cls.data.exog[:, 3] = np.log(cls.data.exog[:, 3])
cls.data.exog = add_constant(cls.data.exog, prepend=False)
cls.res1 = GLM(
cls.data.endog, cls.data.exog, family=sm.families.Poisson()
).fit()
cls.res2 = Cpunish()
# compare with discrete, start close to save time
modd = discrete.Poisson(cls.data.endog, cls.data.exog)
cls.resd = modd.fit(start_params=cls.res1.params * 0.9, disp=False) | Tests Poisson family with canonical log link.
Test results were obtained by R. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests the Inverse Gaussian family in GLM.
Notes
-----
Used the rndivgx.ado file provided by Hardin and Hilbe to
generate the data. Results are read from model_results, which
were obtained by running R_ig.s
"""
# Test Precisions
cls.decimal_aic_R = DECIMAL_0
cls.decimal_loglike = DECIMAL_0
from .results.results_glm import InvGauss
res2 = InvGauss()
res1 = GLM(res2.endog, res2.exog, family=sm.families.InverseGaussian()).fit()
cls.res1 = res1
cls.res2 = res2 | Tests the Inverse Gaussian family in GLM.
Notes
-----
Used the rndivgx.ado file provided by Hardin and Hilbe to
generate the data. Results are read from model_results, which
were obtained by running R_ig.s | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Test Negative Binomial family with log link
"""
# Test Precision
cls.decimal_resid = DECIMAL_1
cls.decimal_params = DECIMAL_3
cls.decimal_resids = -1 # 1 % mismatch at 0
cls.decimal_fittedvalues = DECIMAL_1
from statsmodels.datasets.committee import load
cls.data = load()
cls.data.endog = np.require(cls.data.endog, requirements="W")
cls.data.exog = np.require(cls.data.exog, requirements="W")
cls.data.exog[:, 2] = np.log(cls.data.exog[:, 2])
interaction = cls.data.exog[:, 2] * cls.data.exog[:, 1]
cls.data.exog = np.column_stack((cls.data.exog, interaction))
cls.data.exog = add_constant(cls.data.exog, prepend=False)
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DomainWarning)
with pytest.warns(UserWarning):
fam = sm.families.NegativeBinomial()
cls.res1 = GLM(cls.data.endog, cls.data.exog, family=fam).fit(scale="x2")
from .results.results_glm import Committee
res2 = Committee()
res2.aic_R += 2 # They do not count a degree of freedom for the scale
cls.res2 = res2
cls.has_edispersion = True | Test Negative Binomial family with log link | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Test Gaussian family with canonical identity link
"""
# Test Precisions
cls.decimal_resids = DECIMAL_3
cls.decimal_params = DECIMAL_2
cls.decimal_bic = DECIMAL_0
cls.decimal_bse = DECIMAL_3
from statsmodels.datasets.longley import load
cls.data = load()
cls.data.exog = add_constant(cls.data.exog, prepend=False)
params = sm.OLS(cls.data.endog, cls.data.exog).fit().params
cls.res1 = GLM(
cls.data.endog, cls.data.exog, family=sm.families.Gaussian()
).fit(start_params=params)
from .results.results_glm import Longley
cls.res2 = Longley() | Test Gaussian family with canonical identity link | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Poisson family with canonical log link.
"""
super().setup_class()
cls.endog = np.asarray(cls.endog)
cls.exog = np.asarray(cls.exog)
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=sm.families.Poisson(),
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=sm.families.Poisson()).fit() | Tests Poisson family with canonical log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Poisson family with canonical log link.
"""
super().setup_class()
start_params = np.array(
[
1.82794424e-04,
-4.76785037e-02,
-9.48249717e-02,
-2.92293226e-04,
2.63728909e00,
-2.05934384e01,
]
)
fit_kwds = dict(method="newton")
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=sm.families.Poisson(),
).fit(**fit_kwds)
fit_kwds = dict(method="newton", start_params=start_params)
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=sm.families.Poisson()).fit(
**fit_kwds
) | Tests Poisson family with canonical log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Poisson family with canonical log link.
"""
super().setup_class()
start_params = np.array(
[
1.82794424e-04,
-4.76785037e-02,
-9.48249717e-02,
-2.92293226e-04,
2.63728909e00,
-2.05934384e01,
]
)
fit_kwds = dict(cov_type="HC0")
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=sm.families.Poisson(),
).fit(**fit_kwds)
fit_kwds = dict(cov_type="HC0", start_params=start_params)
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=sm.families.Poisson()).fit(
**fit_kwds
) | Tests Poisson family with canonical log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Poisson family with canonical log link.
"""
super().setup_class()
start_params = np.array(
[
1.82794424e-04,
-4.76785037e-02,
-9.48249717e-02,
-2.92293226e-04,
2.63728909e00,
-2.05934384e01,
]
)
gid = np.arange(1, len(cls.endog) + 1) // 2
fit_kwds = dict(
cov_type="cluster",
cov_kwds={"groups": gid, "use_correction": False},
)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=sm.families.Poisson(),
).fit(**fit_kwds)
gidr = np.repeat(gid, cls.weight)
fit_kwds = dict(
cov_type="cluster",
cov_kwds={"groups": gidr, "use_correction": False},
)
cls.res2 = GLM(
cls.endog_big, cls.exog_big, family=sm.families.Poisson()
).fit(start_params=start_params, **fit_kwds) | Tests Poisson family with canonical log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Binomial family with canonical logit link.
"""
super().setup_class()
cls.endog = cls.endog / 100
cls.endog_big = cls.endog_big / 100
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=sm.families.Binomial(),
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=sm.families.Binomial()).fit() | Tests Binomial family with canonical logit link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Negative Binomial family with canonical link
g(p) = log(p/(p + 1/alpha))
"""
super().setup_class()
alpha = 1.0
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DomainWarning)
family_link = sm.families.NegativeBinomial(
link=sm.families.links.NegativeBinomial(alpha=alpha),
alpha=alpha,
)
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=family_link,
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests Negative Binomial family with canonical link
g(p) = log(p/(p + 1/alpha)) | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Gamma family with log link.
"""
super().setup_class()
family_link = sm.families.Gamma(sm.families.links.Log())
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests Gamma family with log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Gaussian family with log link.
"""
super().setup_class()
family_link = sm.families.Gaussian(sm.families.links.Log())
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests Gaussian family with log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests InverseGaussian family with log link.
"""
super().setup_class()
family_link = sm.families.InverseGaussian(sm.families.links.Log())
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests InverseGaussian family with log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Gamma family with log link.
"""
super().setup_class()
family_link = sm.families.Gamma(sm.families.links.Log())
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit(method="newton")
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit(
method="newton"
) | Tests Gamma family with log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Gamma family with log link.
"""
super().setup_class()
family_link = sm.families.Gamma(sm.families.links.Log())
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=family_link,
).fit(scale="X2")
cls.res2 = GLM(
cls.endog_big,
cls.exog_big,
family=family_link,
).fit(scale="X2") | Tests Gamma family with log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Gamma family with log link.
"""
super().setup_class()
family_link = sm.families.Gamma(sm.families.links.Log())
cls.res1 = GLM(
cls.endog,
cls.exog,
freq_weights=cls.weight,
family=family_link,
).fit(scale="dev")
cls.res2 = GLM(
cls.endog_big,
cls.exog_big,
family=family_link,
).fit(scale="dev") | Tests Gamma family with log link. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Tweedie family with log link and var_power=1.
"""
super().setup_class()
family_link = sm.families.Tweedie(link=sm.families.links.Log(), var_power=1)
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests Tweedie family with log link and var_power=1. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Tweedie family with Power(1) link and var_power=2.
"""
cls.data = cpunish.load_pandas()
cls.endog = cls.data.endog
cls.exog = cls.data.exog[["INCOME", "SOUTH"]]
np.random.seed(1234)
cls.weight = np.random.randint(5, 100, len(cls.endog))
cls.endog_big = np.repeat(cls.endog.values, cls.weight)
cls.exog_big = np.repeat(cls.exog.values, cls.weight, axis=0)
link = sm.families.links.Power()
family_link = sm.families.Tweedie(link=link, var_power=2)
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests Tweedie family with Power(1) link and var_power=2. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Tests Tweedie family with Power(0.5) link and var_power=1.5.
"""
super().setup_class()
family_link = sm.families.Tweedie(
link=sm.families.links.Power(0.5), var_power=1.5
)
cls.res1 = GLM(
cls.endog, cls.exog, freq_weights=cls.weight, family=family_link
).fit()
cls.res2 = GLM(cls.endog_big, cls.exog_big, family=family_link).fit() | Tests Tweedie family with Power(0.5) link and var_power=1.5. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def setup_class(cls):
"""
Test Binomial family with canonical logit link using star98 dataset.
"""
from statsmodels.datasets.star98 import load
data = load()
data.exog = add_constant(data.exog, prepend=False)
cls.model = GLM(data.endog, data.exog, family=sm.families.Binomial()) | Test Binomial family with canonical logit link using star98 dataset. | setup_class | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def test_names():
"""Test the name properties if using a pandas series.
They should not be the defaults if the series has a name.
Don't care about the data here, only testing the name properties.
"""
y = pd.Series([0, 1], name="endog_not_default")
x = pd.DataFrame({"a": [1, 1], "b": [1, 0]})
exposure = pd.Series([0, 0], name="exposure_not_default")
freq_weights = pd.Series([0, 0], name="freq_weights_not_default")
offset = pd.Series([0, 0], name="offset_not_default")
var_weights = pd.Series([0, 0], name="var_weights_not_default")
model = GLM(
endog=y,
exog=x,
exposure=exposure,
freq_weights=freq_weights,
offset=offset,
var_weights=var_weights,
family=sm.families.Tweedie(),
)
assert model.offset_name == "offset_not_default"
assert model.exposure_name == "exposure_not_default"
assert model.freq_weights_name == "freq_weights_not_default"
assert model.var_weights_name == "var_weights_not_default"
assert model.endog_names == "endog_not_default"
assert model.exog_names == ["a", "b"] | Test the name properties if using a pandas series.
They should not be the defaults if the series has a name.
Don't care about the data here, only testing the name properties. | test_names | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def test_names_default():
"""Test the name properties if using a numpy arrays.
Don't care about the data here, only testing the name properties.
"""
y = np.array([0, 1])
x = np.array(
[
[
1,
1,
],
[1, 0],
]
)
exposure = np.array([0, 0])
freq_weights = np.array([0, 0])
offset = np.array([0, 0])
var_weights = np.array([0, 0])
model = GLM(
endog=y,
exog=x,
exposure=exposure,
freq_weights=freq_weights,
offset=offset,
var_weights=var_weights,
family=sm.families.Tweedie(),
)
assert model.offset_name == "offset"
assert model.exposure_name == "exposure"
assert model.freq_weights_name == "freq_weights"
assert model.var_weights_name == "var_weights"
assert model.endog_names == "y"
assert model.exog_names == ["const", "x1"] | Test the name properties if using a numpy arrays.
Don't care about the data here, only testing the name properties. | test_names_default | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_glm.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_glm.py | BSD-3-Clause |
def load_data(fname, icept=True):
"""
Load a data set from the results directory. The data set should
be a CSV file with the following format:
Column 0: Group indicator
Column 1: endog variable
Columns 2-end: exog variables
If `icept` is True, an intercept is prepended to the exog
variables.
"""
cur_dir = os.path.dirname(os.path.abspath(__file__))
Z = np.genfromtxt(os.path.join(cur_dir, 'results', fname),
delimiter=",")
group = Z[:, 0]
endog = Z[:, 1]
exog = Z[:, 2:]
if icept:
exog = np.concatenate((np.ones((exog.shape[0], 1)), exog),
axis=1)
return endog, exog, group | Load a data set from the results directory. The data set should
be a CSV file with the following format:
Column 0: Group indicator
Column 1: endog variable
Columns 2-end: exog variables
If `icept` is True, an intercept is prepended to the exog
variables. | load_data | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_gee.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_gee.py | BSD-3-Clause |
def test_multinomial(self):
"""
Check the 2-class multinomial (nominal) GEE fit against
logistic regression.
"""
np.random.seed(34234)
endog = np.r_[0, 0, 0, 0, 1, 1, 1, 1]
exog = np.ones((8, 2))
exog[:, 1] = np.r_[1, 2, 1, 1, 2, 1, 2, 2]
groups = np.arange(8)
model = gee.NominalGEE(endog, exog, groups)
results = model.fit(cov_type='naive', start_params=[
3.295837, -2.197225])
logit_model = gee.GEE(endog, exog, groups,
family=families.Binomial())
logit_results = logit_model.fit(cov_type='naive')
assert_allclose(results.params, -logit_results.params, rtol=1e-5)
assert_allclose(results.bse, logit_results.bse, rtol=1e-5) | Check the 2-class multinomial (nominal) GEE fit against
logistic regression. | test_multinomial | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_gee.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_gee.py | BSD-3-Clause |
def test_formula_environment(self):
"""Test that GEE uses the right environment for formulas."""
n = 100
rng = np.random.default_rng(34234)
X1 = rng.normal(size=n)
Y = X1 + rng.normal(size=n)
Time = rng.uniform(size=n)
groups = np.kron(lrange(20), np.ones(5))
data = pd.DataFrame({"Y": Y, "X1": X1, "Time": Time, "groups": groups})
va = cov_struct.Autoregressive(grid=False)
family = families.Gaussian()
def times_two(x):
return 2 * x
mat = np.concatenate((np.ones((n, 1)), times_two(X1[:, None])), axis=1)
result_direct = gee.GEE(
Y, mat, groups, time=Time, family=family, cov_struct=va
).fit()
assert result_direct is not None
result_formula = gee.GEE.from_formula(
"Y ~ times_two(X1)",
groups,
data,
time=Time,
family=family,
cov_struct=va,
).fit()
assert result_formula is not None
assert_almost_equal(
result_direct.params,
result_formula.params,
decimal=8,
) | Test that GEE uses the right environment for formulas. | test_formula_environment | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_gee.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_gee.py | BSD-3-Clause |
def test_equivalence(self):
"""
The Equivalence covariance structure can represent an
exchangeable covariance structure. Here we check that the
results are identical using the two approaches.
"""
np.random.seed(3424)
endog = np.random.normal(size=20)
exog = np.random.normal(size=(20, 2))
exog[:, 0] = 1
groups = np.kron(np.arange(5), np.ones(4))
groups[12:] = 3 # Create unequal size groups
# Set up an Equivalence covariance structure to mimic an
# Exchangeable covariance structure.
pairs = {}
start = [0, 4, 8, 12]
for k in range(4):
pairs[k] = {}
# Diagonal values (variance parameters)
if k < 3:
pairs[k][0] = (start[k] + np.r_[0, 1, 2, 3],
start[k] + np.r_[0, 1, 2, 3])
else:
pairs[k][0] = (start[k] + np.r_[0, 1, 2, 3, 4, 5, 6, 7],
start[k] + np.r_[0, 1, 2, 3, 4, 5, 6, 7])
# Off-diagonal pairs (covariance parameters)
if k < 3:
a, b = np.tril_indices(4, -1)
pairs[k][1] = (start[k] + a, start[k] + b)
else:
a, b = np.tril_indices(8, -1)
pairs[k][1] = (start[k] + a, start[k] + b)
ex = cov_struct.Exchangeable()
model1 = gee.GEE(endog, exog, groups, cov_struct=ex)
result1 = model1.fit()
for return_cov in False, True:
ec = cov_struct.Equivalence(pairs, return_cov=return_cov)
model2 = gee.GEE(endog, exog, groups, cov_struct=ec)
result2 = model2.fit()
# Use large atol/rtol for the correlation case since there
# are some small differences in the results due to degree
# of freedom differences.
if return_cov is True:
atol, rtol = 1e-6, 1e-6
else:
atol, rtol = 1e-3, 1e-3
assert_allclose(result1.params, result2.params,
atol=atol, rtol=rtol)
assert_allclose(result1.bse, result2.bse, atol=atol, rtol=rtol)
assert_allclose(result1.scale, result2.scale, atol=atol, rtol=rtol) | The Equivalence covariance structure can represent an
exchangeable covariance structure. Here we check that the
results are identical using the two approaches. | test_equivalence | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_gee.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_gee.py | BSD-3-Clause |
def test_formula_environment():
"""Test that QIF uses the right environment for formulas."""
rng = np.random.default_rng(3423)
x1 = rng.normal(size=100)
y = x1 + rng.normal(size=100)
groups = np.kron(np.arange(25), np.ones(4))
def times_two(x):
return 2 * x
cov_struct = QIFIndependence()
result_direct = QIF(
y,
times_two(x1).reshape(-1, 1),
groups=groups,
cov_struct=cov_struct
).fit()
df = pd.DataFrame({"y": y, "x1": x1, "groups": groups})
result_formula = QIF.from_formula(
"y ~ 0 + times_two(x1)",
groups="groups",
cov_struct=cov_struct,
data=df
).fit()
assert_allclose(result_direct.params, result_formula.params)
assert_allclose(result_direct.bse, result_formula.bse) | Test that QIF uses the right environment for formulas. | test_formula_environment | python | statsmodels/statsmodels | statsmodels/genmod/tests/test_qif.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/tests/test_qif.py | BSD-3-Clause |
def _setlink(self, link):
"""
Helper method to set the link for a family.
Raises a ``ValueError`` exception if the link is not available. Note
that the error message might not be that informative because it tells
you that the link should be in the base class for the link function.
See statsmodels.genmod.generalized_linear_model.GLM for a list of
appropriate links for each family but note that not all of these are
currently available.
"""
# TODO: change the links class attribute in the families to hold
# meaningful information instead of a list of links instances such as
# [<statsmodels.family.links.Log object at 0x9a4240c>,
# <statsmodels.family.links.Power object at 0x9a423ec>,
# <statsmodels.family.links.Power object at 0x9a4236c>]
# for Poisson...
self._link = link
if self._check_link:
if not isinstance(link, L.Link):
raise TypeError("The input should be a valid Link object.")
if hasattr(self, "links"):
validlink = max([isinstance(link, _) for _ in self.links])
if not validlink:
msg = "Invalid link for family, should be in %s. (got %s)"
raise ValueError(msg % (repr(self.links), link)) | Helper method to set the link for a family.
Raises a ``ValueError`` exception if the link is not available. Note
that the error message might not be that informative because it tells
you that the link should be in the base class for the link function.
See statsmodels.genmod.generalized_linear_model.GLM for a list of
appropriate links for each family but note that not all of these are
currently available. | _setlink | python | statsmodels/statsmodels | statsmodels/genmod/families/family.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/family.py | BSD-3-Clause |
def _getlink(self):
"""
Helper method to get the link for a family.
"""
return self._link | Helper method to get the link for a family. | _getlink | python | statsmodels/statsmodels | statsmodels/genmod/families/family.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/family.py | BSD-3-Clause |
def predict(self, mu):
"""
Linear predictors based on given mu values.
Parameters
----------
mu : ndarray
The mean response variables
Returns
-------
lin_pred : ndarray
Linear predictors based on the mean response variables. The value
of the link function at the given mu.
"""
return self.link(mu) | Linear predictors based on given mu values.
Parameters
----------
mu : ndarray
The mean response variables
Returns
-------
lin_pred : ndarray
Linear predictors based on the mean response variables. The value
of the link function at the given mu. | predict | python | statsmodels/statsmodels | statsmodels/genmod/families/family.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/family.py | BSD-3-Clause |
def _clean(self, x):
"""
Helper function to trim the data so that it is in (0,inf)
Notes
-----
The need for this function was discovered through usage and its
possible that other families might need a check for validity of the
domain.
"""
return np.clip(x, FLOAT_EPS, np.inf) | Helper function to trim the data so that it is in (0,inf)
Notes
-----
The need for this function was discovered through usage and its
possible that other families might need a check for validity of the
domain. | _clean | python | statsmodels/statsmodels | statsmodels/genmod/families/family.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/family.py | BSD-3-Clause |
def initialize(self, endog, freq_weights):
'''
Initialize the response variable.
Parameters
----------
endog : ndarray
Endogenous response variable
freq_weights : ndarray
1d array of frequency weights
Returns
-------
If `endog` is binary, returns `endog`
If `endog` is a 2d array, then the input is assumed to be in the format
(successes, failures) and
successes/(success + failures) is returned. And n is set to
successes + failures.
'''
# if not np.all(np.asarray(freq_weights) == 1):
# self.variance = V.Binomial(n=freq_weights)
if endog.ndim > 1 and endog.shape[1] > 2:
raise ValueError('endog has more than 2 columns. The Binomial '
'link supports either a single response variable '
'or a paired response variable.')
elif endog.ndim > 1 and endog.shape[1] > 1:
y = endog[:, 0]
# overwrite self.freq_weights for deviance below
self.n = endog.sum(1)
return y*1./self.n, self.n
else:
return endog, np.ones(endog.shape[0]) | Initialize the response variable.
Parameters
----------
endog : ndarray
Endogenous response variable
freq_weights : ndarray
1d array of frequency weights
Returns
-------
If `endog` is binary, returns `endog`
If `endog` is a 2d array, then the input is assumed to be in the format
(successes, failures) and
successes/(success + failures) is returned. And n is set to
successes + failures. | initialize | python | statsmodels/statsmodels | statsmodels/genmod/families/family.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/family.py | BSD-3-Clause |
def __call__(self, p):
"""
Return the value of the link function. This is just a placeholder.
Parameters
----------
p : array_like
Probabilities
Returns
-------
g(p) : array_like
The value of the link function g(p) = z
"""
return NotImplementedError | Return the value of the link function. This is just a placeholder.
Parameters
----------
p : array_like
Probabilities
Returns
-------
g(p) : array_like
The value of the link function g(p) = z | __call__ | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse(self, z):
"""
Inverse of the link function. Just a placeholder.
Parameters
----------
z : array_like
`z` is usually the linear predictor of the transformed variable
in the IRLS algorithm for GLM.
Returns
-------
g^(-1)(z) : ndarray
The value of the inverse of the link function g^(-1)(z) = p
"""
return NotImplementedError | Inverse of the link function. Just a placeholder.
Parameters
----------
z : array_like
`z` is usually the linear predictor of the transformed variable
in the IRLS algorithm for GLM.
Returns
-------
g^(-1)(z) : ndarray
The value of the inverse of the link function g^(-1)(z) = p | inverse | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv(self, p):
"""
Derivative of the link function g'(p). Just a placeholder.
Parameters
----------
p : array_like
Returns
-------
g'(p) : ndarray
The value of the derivative of the link function g'(p)
"""
return NotImplementedError | Derivative of the link function g'(p). Just a placeholder.
Parameters
----------
p : array_like
Returns
-------
g'(p) : ndarray
The value of the derivative of the link function g'(p) | deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv2(self, p):
"""Second derivative of the link function g''(p)
implemented through numerical differentiation
"""
from statsmodels.tools.numdiff import _approx_fprime_cs_scalar
return _approx_fprime_cs_scalar(p, self.deriv) | Second derivative of the link function g''(p)
implemented through numerical differentiation | deriv2 | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse_deriv(self, z):
"""
Derivative of the inverse link function g^(-1)(z).
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g'^(-1)(z) : ndarray
The value of the derivative of the inverse of the link function
Notes
-----
This reference implementation gives the correct result but is
inefficient, so it can be overridden in subclasses.
"""
return 1 / self.deriv(self.inverse(z)) | Derivative of the inverse link function g^(-1)(z).
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g'^(-1)(z) : ndarray
The value of the derivative of the inverse of the link function
Notes
-----
This reference implementation gives the correct result but is
inefficient, so it can be overridden in subclasses. | inverse_deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse_deriv2(self, z):
"""
Second derivative of the inverse link function g^(-1)(z).
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g'^(-1)(z) : ndarray
The value of the second derivative of the inverse of the link
function
Notes
-----
This reference implementation gives the correct result but is
inefficient, so it can be overridden in subclasses.
"""
iz = self.inverse(z)
return -self.deriv2(iz) / self.deriv(iz) ** 3 | Second derivative of the inverse link function g^(-1)(z).
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g'^(-1)(z) : ndarray
The value of the second derivative of the inverse of the link
function
Notes
-----
This reference implementation gives the correct result but is
inefficient, so it can be overridden in subclasses. | inverse_deriv2 | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def _clean(self, p):
"""
Clip logistic values to range (eps, 1-eps)
Parameters
----------
p : array_like
Probabilities
Returns
-------
pclip : ndarray
Clipped probabilities
"""
return np.clip(p, FLOAT_EPS, 1. - FLOAT_EPS) | Clip logistic values to range (eps, 1-eps)
Parameters
----------
p : array_like
Probabilities
Returns
-------
pclip : ndarray
Clipped probabilities | _clean | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def __call__(self, p):
"""
The logit transform
Parameters
----------
p : array_like
Probabilities
Returns
-------
z : ndarray
Logit transform of `p`
Notes
-----
g(p) = log(p / (1 - p))
"""
p = self._clean(p)
return np.log(p / (1. - p)) | The logit transform
Parameters
----------
p : array_like
Probabilities
Returns
-------
z : ndarray
Logit transform of `p`
Notes
-----
g(p) = log(p / (1 - p)) | __call__ | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse(self, z):
"""
Inverse of the logit transform
Parameters
----------
z : array_like
The value of the logit transform at `p`
Returns
-------
p : ndarray
Probabilities
Notes
-----
g^(-1)(z) = exp(z)/(1+exp(z))
"""
z = np.asarray(z)
t = np.exp(-z)
return 1. / (1. + t) | Inverse of the logit transform
Parameters
----------
z : array_like
The value of the logit transform at `p`
Returns
-------
p : ndarray
Probabilities
Notes
-----
g^(-1)(z) = exp(z)/(1+exp(z)) | inverse | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv(self, p):
"""
Derivative of the logit transform
Parameters
----------
p : array_like
Probabilities
Returns
-------
g'(p) : ndarray
Value of the derivative of logit transform at `p`
Notes
-----
g'(p) = 1 / (p * (1 - p))
Alias for `Logit`:
logit = Logit()
"""
p = self._clean(p)
return 1. / (p * (1 - p)) | Derivative of the logit transform
Parameters
----------
p : array_like
Probabilities
Returns
-------
g'(p) : ndarray
Value of the derivative of logit transform at `p`
Notes
-----
g'(p) = 1 / (p * (1 - p))
Alias for `Logit`:
logit = Logit() | deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse_deriv(self, z):
"""
Derivative of the inverse of the logit transform
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g'^(-1)(z) : ndarray
The value of the derivative of the inverse of the logit function
"""
t = np.exp(z)
return t / (1 + t) ** 2 | Derivative of the inverse of the logit transform
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g'^(-1)(z) : ndarray
The value of the derivative of the inverse of the logit function | inverse_deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv2(self, p):
"""
Second derivative of the logit function.
Parameters
----------
p : array_like
probabilities
Returns
-------
g''(z) : ndarray
The value of the second derivative of the logit function
"""
v = p * (1 - p)
return (2 * p - 1) / v ** 2 | Second derivative of the logit function.
Parameters
----------
p : array_like
probabilities
Returns
-------
g''(z) : ndarray
The value of the second derivative of the logit function | deriv2 | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def __call__(self, p):
"""
Power transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
z : array_like
Power transform of x
Notes
-----
g(p) = x**self.power
"""
if self.power == 1:
return p
else:
return np.power(p, self.power) | Power transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
z : array_like
Power transform of x
Notes
-----
g(p) = x**self.power | __call__ | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse(self, z):
"""
Inverse of the power transform link function
Parameters
----------
`z` : array_like
Value of the transformed mean parameters at `p`
Returns
-------
`p` : ndarray
Mean parameters
Notes
-----
g^(-1)(z`) = `z`**(1/`power`)
"""
if self.power == 1:
return z
else:
return np.power(z, 1. / self.power) | Inverse of the power transform link function
Parameters
----------
`z` : array_like
Value of the transformed mean parameters at `p`
Returns
-------
`p` : ndarray
Mean parameters
Notes
-----
g^(-1)(z`) = `z`**(1/`power`) | inverse | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv(self, p):
"""
Derivative of the power transform
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g'(p) : ndarray
Derivative of power transform of `p`
Notes
-----
g'(`p`) = `power` * `p`**(`power` - 1)
"""
if self.power == 1:
return np.ones_like(p)
else:
return self.power * np.power(p, self.power - 1) | Derivative of the power transform
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g'(p) : ndarray
Derivative of power transform of `p`
Notes
-----
g'(`p`) = `power` * `p`**(`power` - 1) | deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv2(self, p):
"""
Second derivative of the power transform
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g''(p) : ndarray
Second derivative of the power transform of `p`
Notes
-----
g''(`p`) = `power` * (`power` - 1) * `p`**(`power` - 2)
"""
if self.power == 1:
return np.zeros_like(p)
else:
return self.power * (self.power - 1) * np.power(p, self.power - 2) | Second derivative of the power transform
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g''(p) : ndarray
Second derivative of the power transform of `p`
Notes
-----
g''(`p`) = `power` * (`power` - 1) * `p`**(`power` - 2) | deriv2 | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse_deriv(self, z):
"""
Derivative of the inverse of the power transform
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)'(z) : ndarray
The value of the derivative of the inverse of the power transform
function
"""
if self.power == 1:
return np.ones_like(z)
else:
return np.power(z, (1 - self.power) / self.power) / self.power | Derivative of the inverse of the power transform
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)'(z) : ndarray
The value of the derivative of the inverse of the power transform
function | inverse_deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse_deriv2(self, z):
"""
Second derivative of the inverse of the power transform
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)'(z) : ndarray
The value of the derivative of the inverse of the power transform
function
"""
if self.power == 1:
return np.zeros_like(z)
else:
return ((1 - self.power) *
np.power(z, (1 - 2*self.power)/self.power) / self.power**2) | Second derivative of the inverse of the power transform
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)'(z) : ndarray
The value of the derivative of the inverse of the power transform
function | inverse_deriv2 | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def __call__(self, p, **extra):
"""
Log transform link function
Parameters
----------
x : array_like
Mean parameters
Returns
-------
z : ndarray
log(x)
Notes
-----
g(p) = log(p)
"""
x = self._clean(p)
return np.log(x) | Log transform link function
Parameters
----------
x : array_like
Mean parameters
Returns
-------
z : ndarray
log(x)
Notes
-----
g(p) = log(p) | __call__ | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse(self, z):
"""
Inverse of log transform link function
Parameters
----------
z : ndarray
The inverse of the link function at `p`
Returns
-------
p : ndarray
The mean probabilities given the value of the inverse `z`
Notes
-----
g^{-1}(z) = exp(z)
"""
return np.exp(z) | Inverse of log transform link function
Parameters
----------
z : ndarray
The inverse of the link function at `p`
Returns
-------
p : ndarray
The mean probabilities given the value of the inverse `z`
Notes
-----
g^{-1}(z) = exp(z) | inverse | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv(self, p):
"""
Derivative of log transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g'(p) : ndarray
derivative of log transform of x
Notes
-----
g'(x) = 1/x
"""
p = self._clean(p)
return 1. / p | Derivative of log transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g'(p) : ndarray
derivative of log transform of x
Notes
-----
g'(x) = 1/x | deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv2(self, p):
"""
Second derivative of the log transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g''(p) : ndarray
Second derivative of log transform of x
Notes
-----
g''(x) = -1/x^2
"""
p = self._clean(p)
return -1. / p ** 2 | Second derivative of the log transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g''(p) : ndarray
Second derivative of log transform of x
Notes
-----
g''(x) = -1/x^2 | deriv2 | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse_deriv(self, z):
"""
Derivative of the inverse of the log transform link function
Parameters
----------
z : ndarray
The inverse of the link function at `p`
Returns
-------
g^(-1)'(z) : ndarray
The value of the derivative of the inverse of the log function,
the exponential function
"""
return np.exp(z) | Derivative of the inverse of the log transform link function
Parameters
----------
z : ndarray
The inverse of the link function at `p`
Returns
-------
g^(-1)'(z) : ndarray
The value of the derivative of the inverse of the log function,
the exponential function | inverse_deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def __call__(self, p, **extra):
"""
Log-complement transform link function
Parameters
----------
x : array_like
Mean parameters
Returns
-------
z : ndarray
log(1 - x)
Notes
-----
g(p) = log(1-p)
"""
x = self._clean(p)
return np.log(1 - x) | Log-complement transform link function
Parameters
----------
x : array_like
Mean parameters
Returns
-------
z : ndarray
log(1 - x)
Notes
-----
g(p) = log(1-p) | __call__ | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def inverse(self, z):
"""
Inverse of log-complement transform link function
Parameters
----------
z : ndarray
The inverse of the link function at `p`
Returns
-------
p : ndarray
The mean probabilities given the value of the inverse `z`
Notes
-----
g^{-1}(z) = 1 - exp(z)
"""
return 1 - np.exp(z) | Inverse of log-complement transform link function
Parameters
----------
z : ndarray
The inverse of the link function at `p`
Returns
-------
p : ndarray
The mean probabilities given the value of the inverse `z`
Notes
-----
g^{-1}(z) = 1 - exp(z) | inverse | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
def deriv(self, p):
"""
Derivative of log-complement transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g'(p) : ndarray
derivative of log-complement transform of x
Notes
-----
g'(x) = -1/(1 - x)
"""
p = self._clean(p)
return -1. / (1. - p) | Derivative of log-complement transform link function
Parameters
----------
p : array_like
Mean parameters
Returns
-------
g'(p) : ndarray
derivative of log-complement transform of x
Notes
-----
g'(x) = -1/(1 - x) | deriv | python | statsmodels/statsmodels | statsmodels/genmod/families/links.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py | BSD-3-Clause |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.