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
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def score_test(self, params_constrained, k_constraints=None,
exog_extra=None, observed=True):
"""score test for restrictions or for omitted variables
The covariance matrix for the score is based on the Hessian, i.e.
observed information matrix or optionally on the expected information
matrix..
Parameters
----------
params_constrained : array_like
estimated parameter of the restricted model. This can be the
parameter estimate for the current when testing for omitted
variables.
k_constraints : int or None
Number of constraints that were used in the estimation of params
restricted relative to the number of exog in the model.
This must be provided if no exog_extra are given. If exog_extra is
not None, then k_constraints is assumed to be zero if it is None.
exog_extra : None or array_like
Explanatory variables that are jointly tested for inclusion in the
model, i.e. omitted variables.
observed : bool
If True, then the observed Hessian is used in calculating the
covariance matrix of the score. If false then the expected
information matrix is used.
Returns
-------
chi2_stat : float
chisquare statistic for the score test
p-value : float
P-value of the score test based on the chisquare distribution.
df : int
Degrees of freedom used in the p-value calculation. This is equal
to the number of constraints.
Notes
-----
not yet verified for case with scale not equal to 1.
"""
if exog_extra is None:
if k_constraints is None:
raise ValueError('if exog_extra is None, then k_constraints'
'needs to be given')
score = self.score(params_constrained)
hessian = self.hessian(params_constrained, observed=observed)
else:
# exog_extra = np.asarray(exog_extra)
if k_constraints is None:
k_constraints = 0
ex = np.column_stack((self.exog, exog_extra))
k_constraints += ex.shape[1] - self.exog.shape[1]
score_factor = self.score_factor(params_constrained)
score = (score_factor[:, None] * ex).sum(0)
hessian_factor = self.hessian_factor(params_constrained,
observed=observed)
hessian = -np.dot(ex.T * hessian_factor, ex)
from scipy import stats
# TODO check sign, why minus?
chi2stat = -score.dot(np.linalg.solve(hessian, score[:, None]))
pval = stats.chi2.sf(chi2stat, k_constraints)
# return a stats results instance instead? Contrast?
return chi2stat, pval, k_constraints | score test for restrictions or for omitted variables
The covariance matrix for the score is based on the Hessian, i.e.
observed information matrix or optionally on the expected information
matrix..
Parameters
----------
params_constrained : array_like
estimated parameter of the restricted model. This can be the
parameter estimate for the current when testing for omitted
variables.
k_constraints : int or None
Number of constraints that were used in the estimation of params
restricted relative to the number of exog in the model.
This must be provided if no exog_extra are given. If exog_extra is
not None, then k_constraints is assumed to be zero if it is None.
exog_extra : None or array_like
Explanatory variables that are jointly tested for inclusion in the
model, i.e. omitted variables.
observed : bool
If True, then the observed Hessian is used in calculating the
covariance matrix of the score. If false then the expected
information matrix is used.
Returns
-------
chi2_stat : float
chisquare statistic for the score test
p-value : float
P-value of the score test based on the chisquare distribution.
df : int
Degrees of freedom used in the p-value calculation. This is equal
to the number of constraints.
Notes
-----
not yet verified for case with scale not equal to 1. | score_test | 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 _update_history(self, tmp_result, mu, history):
"""
Helper method to update history during iterative fit.
"""
history['params'].append(tmp_result.params)
history['deviance'].append(self.family.deviance(self.endog, mu,
self.var_weights,
self.freq_weights,
self.scale))
return history | Helper method to update history during iterative fit. | _update_history | 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 estimate_scale(self, mu):
"""
Estimate the dispersion/scale.
Type of scale can be chose in the fit method.
Parameters
----------
mu : ndarray
mu is the mean response estimate
Returns
-------
Estimate of scale
Notes
-----
The default scale for Binomial, Poisson and Negative Binomial
families is 1. The default for the other families is Pearson's
Chi-Square estimate.
See Also
--------
statsmodels.genmod.generalized_linear_model.GLM.fit
"""
if not self.scaletype:
if isinstance(self.family, (families.Binomial, families.Poisson,
families.NegativeBinomial)):
return 1.
else:
return self._estimate_x2_scale(mu)
if isinstance(self.scaletype, float):
return np.array(self.scaletype)
if isinstance(self.scaletype, str):
if self.scaletype.lower() == 'x2':
return self._estimate_x2_scale(mu)
elif self.scaletype.lower() == 'dev':
return (self.family.deviance(self.endog, mu, self.var_weights,
self.freq_weights, 1.) /
(self.df_resid))
else:
raise ValueError("Scale %s with type %s not understood" %
(self.scaletype, type(self.scaletype)))
else:
raise ValueError("Scale %s with type %s not understood" %
(self.scaletype, type(self.scaletype))) | Estimate the dispersion/scale.
Type of scale can be chose in the fit method.
Parameters
----------
mu : ndarray
mu is the mean response estimate
Returns
-------
Estimate of scale
Notes
-----
The default scale for Binomial, Poisson and Negative Binomial
families is 1. The default for the other families is Pearson's
Chi-Square estimate.
See Also
--------
statsmodels.genmod.generalized_linear_model.GLM.fit | estimate_scale | 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 estimate_tweedie_power(self, mu, method='brentq', low=1.01, high=5.):
"""
Tweedie specific function to estimate scale and the variance parameter.
The variance parameter is also referred to as p, xi, or shape.
Parameters
----------
mu : array_like
Fitted mean response variable
method : str, defaults to 'brentq'
Scipy optimizer used to solve the Pearson equation. Only brentq
currently supported.
low : float, optional
Low end of the bracketing interval [a,b] to be used in the search
for the power. Defaults to 1.01.
high : float, optional
High end of the bracketing interval [a,b] to be used in the search
for the power. Defaults to 5.
Returns
-------
power : float
The estimated shape or power.
"""
if method == 'brentq':
from scipy.optimize import brentq
def psi_p(power, mu):
scale = ((self.iweights * (self.endog - mu) ** 2 /
(mu ** power)).sum() / self.df_resid)
return (np.sum(self.iweights * ((self.endog - mu) ** 2 /
(scale * (mu ** power)) - 1) *
np.log(mu)) / self.freq_weights.sum())
power = brentq(psi_p, low, high, args=(mu))
else:
raise NotImplementedError('Only brentq can currently be used')
return power | Tweedie specific function to estimate scale and the variance parameter.
The variance parameter is also referred to as p, xi, or shape.
Parameters
----------
mu : array_like
Fitted mean response variable
method : str, defaults to 'brentq'
Scipy optimizer used to solve the Pearson equation. Only brentq
currently supported.
low : float, optional
Low end of the bracketing interval [a,b] to be used in the search
for the power. Defaults to 1.01.
high : float, optional
High end of the bracketing interval [a,b] to be used in the search
for the power. Defaults to 5.
Returns
-------
power : float
The estimated shape or power. | estimate_tweedie_power | 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 predict(self, params, exog=None, exposure=None, offset=None,
which="mean", linear=None):
"""
Return predicted values for a design matrix
Parameters
----------
params : array_like
Parameters / coefficients of a GLM.
exog : array_like, optional
Design / exogenous data. Is exog is None, model exog is used.
exposure : array_like, optional
Exposure time values, only can be used with the log link
function. See notes for details.
offset : array_like, optional
Offset values. See notes for details.
which : 'mean', 'linear', 'var'(optional)
Statitistic to predict. Default is 'mean'.
- '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 True, returns the linear predicted values. If False or None,
then the statistic specified by ``which`` will be returned.
Returns
-------
An array of fitted values
Notes
-----
Any `exposure` and `offset` provided here take precedence over
the `exposure` and `offset` used in the model fit. If `exog`
is passed as an argument here, then any `exposure` and
`offset` values in the fit will be ignored.
Exposure values must be strictly positive.
"""
if linear is not None:
msg = 'linear keyword is deprecated, use which="linear"'
warnings.warn(msg, FutureWarning)
if linear is True:
which = "linear"
# Use fit offset if appropriate
if offset is None and exog is None and hasattr(self, 'offset'):
offset = self.offset
elif offset is None:
offset = 0.
if exposure is not None and not isinstance(self.family.link,
families.links.Log):
raise ValueError("exposure can only be used with the log link "
"function")
# Use fit exposure if appropriate
if exposure is None and exog is None and hasattr(self, 'exposure'):
# Already logged
exposure = self.exposure
elif exposure is None:
exposure = 0.
else:
exposure = np.log(np.asarray(exposure))
if exog is None:
exog = self.exog
linpred = np.dot(exog, params) + offset + exposure
if which == "mean":
return self.family.fitted(linpred)
elif which == "linear":
return linpred
elif which == "var_unscaled":
mean = self.family.fitted(linpred)
var_ = self.family.variance(mean)
return var_
else:
raise ValueError(f'The which value "{which}" is not recognized') | Return predicted values for a design matrix
Parameters
----------
params : array_like
Parameters / coefficients of a GLM.
exog : array_like, optional
Design / exogenous data. Is exog is None, model exog is used.
exposure : array_like, optional
Exposure time values, only can be used with the log link
function. See notes for details.
offset : array_like, optional
Offset values. See notes for details.
which : 'mean', 'linear', 'var'(optional)
Statitistic to predict. Default is 'mean'.
- '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 True, returns the linear predicted values. If False or None,
then the statistic specified by ``which`` will be returned.
Returns
-------
An array of fitted values
Notes
-----
Any `exposure` and `offset` provided here take precedence over
the `exposure` and `offset` used in the model fit. If `exog`
is passed as an argument here, then any `exposure` and
`offset` values in the fit will be ignored.
Exposure values must be strictly positive. | predict | 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, params, scale=None, exog=None, exposure=None,
offset=None, var_weights=1., n_trials=1.):
"""
Return a instance of the predictive distribution.
Parameters
----------
params : array_like
The model 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.
"""
scale = float_like(scale, "scale", optional=True)
# use scale=1, independent of QMLE scale for discrete
if isinstance(self.family, (families.Binomial, families.Poisson,
families.NegativeBinomial)):
scale = 1.
mu = self.predict(params, exog, exposure, offset, which="mean")
kwds = {}
if (np.any(n_trials != 1) and
isinstance(self.family, families.Binomial)):
kwds["n_trials"] = n_trials
distr = self.family.get_distribution(mu, scale,
var_weights=var_weights, **kwds)
return distr | Return a instance of the predictive distribution.
Parameters
----------
params : array_like
The model 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 fit(self, start_params=None, maxiter=100, method='IRLS', tol=1e-8,
scale=None, cov_type='nonrobust', cov_kwds=None, use_t=None,
full_output=True, disp=False, max_start_irls=3, **kwargs):
"""
Fits a generalized linear model for a given family.
Parameters
----------
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
The default is family-specific and is given by the
``family.starting_mu(endog)``. If start_params is given then the
initial mean will be calculated as ``np.dot(exog, start_params)``.
maxiter : int, optional
Default is 100.
method : str
Default is 'IRLS' for iteratively reweighted least squares.
Otherwise gradient optimization is used.
tol : float
Convergence tolerance. Default is 1e-8.
scale : str or float, optional
`scale` can be 'X2', 'dev', or a float
The default value is None, which uses `X2` for Gamma, Gaussian,
and Inverse Gaussian.
`X2` is Pearson's chi-square divided by `df_resid`.
The default is 1 for the Binomial and Poisson families.
`dev` is the deviance divided by df_resid
cov_type : str
The type of parameter estimate covariance matrix to compute.
cov_kwds : dict-like
Extra arguments for calculating the covariance of the parameter
estimates.
use_t : bool
If True, the Student t-distribution is used for inference.
full_output : bool, optional
Set to True to have all available output in the Results object's
mle_retvals attribute. The output is dependent on the solver.
See LikelihoodModelResults notes section for more information.
Not used if methhod is IRLS.
disp : bool, optional
Set to True to print convergence messages. Not used if method is
IRLS.
max_start_irls : int
The number of IRLS iterations used to obtain starting
values for gradient optimization. Only relevant if
`method` is set to something other than 'IRLS'.
atol : float, optional
(available with IRLS fits) The absolute tolerance criterion that
must be satisfied. Defaults to ``tol``. Convergence is attained
when: :math:`rtol * prior + atol > abs(current - prior)`
rtol : float, optional
(available with IRLS fits) The relative tolerance criterion that
must be satisfied. Defaults to 0 which means ``rtol`` is not used.
Convergence is attained when:
:math:`rtol * prior + atol > abs(current - prior)`
tol_criterion : str, optional
(available with IRLS fits) Defaults to ``'deviance'``. Can
optionally be ``'params'``.
wls_method : str, optional
(available with IRLS fits) options are 'lstsq', 'pinv' and 'qr'
specifies which linear algebra function to use for the irls
optimization. Default is `lstsq` which uses the same underlying
svd based approach as 'pinv', but is faster during iterations.
'lstsq' and 'pinv' regularize the estimate in singular and
near-singular cases by truncating small singular values based
on `rcond` of the respective numpy.linalg function. 'qr' is
only valid for cases that are not singular nor near-singular.
optim_hessian : {'eim', 'oim'}, optional
(available with scipy optimizer fits) When 'oim'--the default--the
observed Hessian is used in fitting. 'eim' is the expected Hessian.
This may provide more stable fits, but adds assumption that the
Hessian is correctly specified.
Notes
-----
If method is 'IRLS', then an additional keyword 'attach_wls' is
available. This is currently for internal use only and might change
in future versions. If attach_wls' is true, then the final WLS
instance of the IRLS iteration is attached to the results instance
as `results_wls` attribute.
"""
if isinstance(scale, str):
scale = scale.lower()
if scale not in ("x2", "dev"):
raise ValueError(
"scale must be either X2 or dev when a string."
)
elif scale is not None:
# GH-6627
try:
scale = float(scale)
except Exception as exc:
raise type(exc)(
"scale must be a float if given and no a string."
)
self.scaletype = scale
if method.lower() == "irls":
if cov_type.lower() == 'eim':
cov_type = 'nonrobust'
return self._fit_irls(start_params=start_params, maxiter=maxiter,
tol=tol, scale=scale, cov_type=cov_type,
cov_kwds=cov_kwds, use_t=use_t, **kwargs)
else:
self._optim_hessian = kwargs.get('optim_hessian')
if self._optim_hessian is not None:
del kwargs['optim_hessian']
self._tmp_like_exog = np.empty_like(self.exog, dtype=float)
fit_ = self._fit_gradient(start_params=start_params,
method=method,
maxiter=maxiter,
tol=tol, scale=scale,
full_output=full_output,
disp=disp, cov_type=cov_type,
cov_kwds=cov_kwds, use_t=use_t,
max_start_irls=max_start_irls,
**kwargs)
del self._optim_hessian
del self._tmp_like_exog
return fit_ | Fits a generalized linear model for a given family.
Parameters
----------
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
The default is family-specific and is given by the
``family.starting_mu(endog)``. If start_params is given then the
initial mean will be calculated as ``np.dot(exog, start_params)``.
maxiter : int, optional
Default is 100.
method : str
Default is 'IRLS' for iteratively reweighted least squares.
Otherwise gradient optimization is used.
tol : float
Convergence tolerance. Default is 1e-8.
scale : str or float, optional
`scale` can be 'X2', 'dev', or a float
The default value is None, which uses `X2` for Gamma, Gaussian,
and Inverse Gaussian.
`X2` is Pearson's chi-square divided by `df_resid`.
The default is 1 for the Binomial and Poisson families.
`dev` is the deviance divided by df_resid
cov_type : str
The type of parameter estimate covariance matrix to compute.
cov_kwds : dict-like
Extra arguments for calculating the covariance of the parameter
estimates.
use_t : bool
If True, the Student t-distribution is used for inference.
full_output : bool, optional
Set to True to have all available output in the Results object's
mle_retvals attribute. The output is dependent on the solver.
See LikelihoodModelResults notes section for more information.
Not used if methhod is IRLS.
disp : bool, optional
Set to True to print convergence messages. Not used if method is
IRLS.
max_start_irls : int
The number of IRLS iterations used to obtain starting
values for gradient optimization. Only relevant if
`method` is set to something other than 'IRLS'.
atol : float, optional
(available with IRLS fits) The absolute tolerance criterion that
must be satisfied. Defaults to ``tol``. Convergence is attained
when: :math:`rtol * prior + atol > abs(current - prior)`
rtol : float, optional
(available with IRLS fits) The relative tolerance criterion that
must be satisfied. Defaults to 0 which means ``rtol`` is not used.
Convergence is attained when:
:math:`rtol * prior + atol > abs(current - prior)`
tol_criterion : str, optional
(available with IRLS fits) Defaults to ``'deviance'``. Can
optionally be ``'params'``.
wls_method : str, optional
(available with IRLS fits) options are 'lstsq', 'pinv' and 'qr'
specifies which linear algebra function to use for the irls
optimization. Default is `lstsq` which uses the same underlying
svd based approach as 'pinv', but is faster during iterations.
'lstsq' and 'pinv' regularize the estimate in singular and
near-singular cases by truncating small singular values based
on `rcond` of the respective numpy.linalg function. 'qr' is
only valid for cases that are not singular nor near-singular.
optim_hessian : {'eim', 'oim'}, optional
(available with scipy optimizer fits) When 'oim'--the default--the
observed Hessian is used in fitting. 'eim' is the expected Hessian.
This may provide more stable fits, but adds assumption that the
Hessian is correctly specified.
Notes
-----
If method is 'IRLS', then an additional keyword 'attach_wls' is
available. This is currently for internal use only and might change
in future versions. If attach_wls' is true, then the final WLS
instance of the IRLS iteration is attached to the results instance
as `results_wls` attribute. | fit | 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 _fit_gradient(self, start_params=None, method="newton",
maxiter=100, tol=1e-8, full_output=True,
disp=True, scale=None, cov_type='nonrobust',
cov_kwds=None, use_t=None, max_start_irls=3,
**kwargs):
"""
Fits a generalized linear model for a given family iteratively
using the scipy gradient optimizers.
"""
# fix scale during optimization, see #4616
scaletype = self.scaletype
self.scaletype = 1.
if (max_start_irls > 0) and (start_params is None):
irls_rslt = self._fit_irls(start_params=start_params,
maxiter=max_start_irls,
tol=tol, scale=1., cov_type='nonrobust',
cov_kwds=None, use_t=None,
**kwargs)
start_params = irls_rslt.params
del irls_rslt
rslt = super().fit(start_params=start_params,
maxiter=maxiter, full_output=full_output,
method=method, disp=disp, **kwargs)
# reset scaletype to original
self.scaletype = scaletype
mu = self.predict(rslt.params)
scale = self.estimate_scale(mu)
if rslt.normalized_cov_params is None:
cov_p = None
else:
cov_p = rslt.normalized_cov_params / scale
if cov_type.lower() == 'eim':
oim = False
cov_type = 'nonrobust'
else:
oim = True
try:
cov_p = np.linalg.inv(-self.hessian(rslt.params, observed=oim)) / scale
except LinAlgError:
warnings.warn('Inverting hessian failed, no bse or cov_params '
'available', HessianInversionWarning)
cov_p = None
results_class = getattr(self, '_results_class', GLMResults)
results_class_wrapper = getattr(self, '_results_class_wrapper', GLMResultsWrapper)
glm_results = results_class(self, rslt.params,
cov_p,
scale,
cov_type=cov_type, cov_kwds=cov_kwds,
use_t=use_t)
# TODO: iteration count is not always available
history = {'iteration': 0}
if full_output:
glm_results.mle_retvals = rslt.mle_retvals
if 'iterations' in rslt.mle_retvals:
history['iteration'] = rslt.mle_retvals['iterations']
glm_results.method = method
glm_results.fit_history = history
return results_class_wrapper(glm_results) | Fits a generalized linear model for a given family iteratively
using the scipy gradient optimizers. | _fit_gradient | 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 _fit_irls(self, start_params=None, maxiter=100, tol=1e-8,
scale=None, cov_type='nonrobust', cov_kwds=None,
use_t=None, **kwargs):
"""
Fits a generalized linear model for a given family using
iteratively reweighted least squares (IRLS).
"""
attach_wls = kwargs.pop('attach_wls', False)
atol = kwargs.get('atol')
rtol = kwargs.get('rtol', 0.)
tol_criterion = kwargs.get('tol_criterion', 'deviance')
wls_method = kwargs.get('wls_method', 'lstsq')
atol = tol if atol is None else atol
endog = self.endog
wlsexog = self.exog
if start_params is None:
start_params = np.zeros(self.exog.shape[1])
mu = self.family.starting_mu(self.endog)
lin_pred = self.family.predict(mu)
else:
lin_pred = np.dot(wlsexog, start_params) + self._offset_exposure
mu = self.family.fitted(lin_pred)
self.scale = self.estimate_scale(mu)
dev = self.family.deviance(self.endog, mu, self.var_weights,
self.freq_weights, self.scale)
if np.isnan(dev):
raise ValueError("The first guess on the deviance function "
"returned a nan. This could be a boundary "
" problem and should be reported.")
# first guess on the deviance is assumed to be scaled by 1.
# params are none to start, so they line up with the deviance
history = dict(params=[np.inf, start_params], deviance=[np.inf, dev])
converged = False
criterion = history[tol_criterion]
# This special case is used to get the likelihood for a specific
# params vector.
if maxiter == 0:
mu = self.family.fitted(lin_pred)
self.scale = self.estimate_scale(mu)
wls_results = lm.RegressionResults(self, start_params, None)
iteration = 0
for iteration in range(maxiter):
self.weights = (self.iweights * self.n_trials *
self.family.weights(mu))
wlsendog = (lin_pred + self.family.link.deriv(mu) * (self.endog-mu)
- self._offset_exposure)
wls_mod = reg_tools._MinimalWLS(wlsendog, wlsexog,
self.weights, check_endog=True,
check_weights=True)
wls_results = wls_mod.fit(method=wls_method)
lin_pred = np.dot(self.exog, wls_results.params)
lin_pred += self._offset_exposure
mu = self.family.fitted(lin_pred)
history = self._update_history(wls_results, mu, history)
self.scale = self.estimate_scale(mu)
if endog.squeeze().ndim == 1 and np.allclose(mu - endog, 0):
msg = ("Perfect separation or prediction detected, "
"parameter may not be identified")
warnings.warn(msg, category=PerfectSeparationWarning)
converged = _check_convergence(criterion, iteration + 1, atol,
rtol)
if converged:
break
self.mu = mu
if maxiter > 0: # Only if iterative used
wls_method2 = 'pinv' if wls_method == 'lstsq' else wls_method
wls_model = lm.WLS(wlsendog, wlsexog, self.weights)
wls_results = wls_model.fit(method=wls_method2)
glm_results = GLMResults(self, wls_results.params,
wls_results.normalized_cov_params,
self.scale,
cov_type=cov_type, cov_kwds=cov_kwds,
use_t=use_t)
glm_results.method = "IRLS"
glm_results.mle_settings = {}
glm_results.mle_settings['wls_method'] = wls_method
glm_results.mle_settings['optimizer'] = glm_results.method
if (maxiter > 0) and (attach_wls is True):
glm_results.results_wls = wls_results
history['iteration'] = iteration + 1
glm_results.fit_history = history
glm_results.converged = converged
return GLMResultsWrapper(glm_results) | Fits a generalized linear model for a given family using
iteratively reweighted least squares (IRLS). | _fit_irls | 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 fit_constrained(self, constraints, start_params=None, **fit_kwds):
"""fit the model subject to linear equality constraints
The constraints are of the form `R params = q`
where R is the constraint_matrix and q is the vector of
constraint_values.
The estimation creates a new model with transformed design matrix,
exog, and converts the results back to the original parameterization.
Parameters
----------
constraints : formula expression or tuple
If it is a tuple, then the constraint needs to be given by two
arrays (constraint_matrix, constraint_value), i.e. (R, q).
Otherwise, the constraints can be given as strings or list of
strings.
see t_test for details
start_params : None or array_like
starting values for the optimization. `start_params` needs to be
given in the original parameter space and are internally
transformed.
**fit_kwds : keyword arguments
fit_kwds are used in the optimization of the transformed model.
Returns
-------
results : Results instance
"""
from statsmodels.base._constraints import (
LinearConstraints,
fit_constrained,
)
from statsmodels.formula._manager import FormulaManager
# same pattern as in base.LikelihoodModel.t_test
lc = FormulaManager().get_linear_constraints(constraints, self.exog_names)
R, q = lc.constraint_matrix, lc.constraint_values
# TODO: add start_params option, need access to tranformation
# fit_constrained needs to do the transformation
params, cov, res_constr = fit_constrained(self, R, q,
start_params=start_params,
fit_kwds=fit_kwds)
# create dummy results Instance, TODO: wire up properly
res = self.fit(start_params=params, maxiter=0) # we get a wrapper back
res._results.params = params
res._results.cov_params_default = cov
cov_type = fit_kwds.get('cov_type', 'nonrobust')
if cov_type != 'nonrobust':
res._results.normalized_cov_params = cov / res_constr.scale
else:
res._results.normalized_cov_params = None
res._results.scale = res_constr.scale
k_constr = len(q)
res._results.df_resid += k_constr
res._results.df_model -= k_constr
res._results.constraints = LinearConstraints.from_formula_parser(lc)
res._results.k_constr = k_constr
res._results.results_constrained = res_constr
return res | fit the model subject to linear equality constraints
The constraints are of the form `R params = q`
where R is the constraint_matrix and q is the vector of
constraint_values.
The estimation creates a new model with transformed design matrix,
exog, and converts the results back to the original parameterization.
Parameters
----------
constraints : formula expression or tuple
If it is a tuple, then the constraint needs to be given by two
arrays (constraint_matrix, constraint_value), i.e. (R, q).
Otherwise, the constraints can be given as strings or list of
strings.
see t_test for details
start_params : None or array_like
starting values for the optimization. `start_params` needs to be
given in the original parameter space and are internally
transformed.
**fit_kwds : keyword arguments
fit_kwds are used in the optimization of the transformed model.
Returns
-------
results : Results instance | fit_constrained | 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 offset_name(self):
"""
Name of the offset variable if available. If offset is not a pd.Series,
defaults to 'offset'.
"""
return self._offset_name | Name of the offset variable if available. If offset is not a pd.Series,
defaults to 'offset'. | offset_name | 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 exposure_name(self):
"""
Name of the exposure variable if available. If exposure is not a pd.Series,
defaults to 'exposure'.
"""
return self._exposure_name | Name of the exposure variable if available. If exposure is not a pd.Series,
defaults to 'exposure'. | exposure_name | 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 freq_weights_name(self):
"""
Name of the freq weights variable if available. If freq_weights is not a
pd.Series, defaults to 'freq_weights'.
"""
return self._freq_weights_name | Name of the freq weights variable if available. If freq_weights is not a
pd.Series, defaults to 'freq_weights'. | freq_weights_name | 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 var_weights_name(self):
"""
Name of var weights variable if available. If var_weights is not a pd.Series,
defaults to 'var_weights'.
"""
return self._var_weights_name | Name of var weights variable if available. If var_weights is not a pd.Series,
defaults to 'var_weights'. | var_weights_name | 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_response(self):
"""
Response residuals. The response residuals are defined as
`endog` - `fittedvalues`
"""
return self._n_trials * (self._endog-self.mu) | Response residuals. The response residuals are defined as
`endog` - `fittedvalues` | resid_response | 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_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 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):
"""
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 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 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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.