glm.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. """
  2. Generalized Linear Models with Exponential Dispersion Family
  3. """
  4. # Author: Christian Lorentzen <lorentzen.ch@gmail.com>
  5. # some parts and tricks stolen from other sklearn files.
  6. # License: BSD 3 clause
  7. from numbers import Integral, Real
  8. import numpy as np
  9. import scipy.optimize
  10. from ..._loss.loss import (
  11. HalfGammaLoss,
  12. HalfPoissonLoss,
  13. HalfSquaredError,
  14. HalfTweedieLoss,
  15. HalfTweedieLossIdentity,
  16. )
  17. from ...base import BaseEstimator, RegressorMixin, _fit_context
  18. from ...utils import check_array
  19. from ...utils._openmp_helpers import _openmp_effective_n_threads
  20. from ...utils._param_validation import Hidden, Interval, StrOptions
  21. from ...utils.optimize import _check_optimize_result
  22. from ...utils.validation import _check_sample_weight, check_is_fitted
  23. from .._linear_loss import LinearModelLoss
  24. from ._newton_solver import NewtonCholeskySolver, NewtonSolver
  25. class _GeneralizedLinearRegressor(RegressorMixin, BaseEstimator):
  26. """Regression via a penalized Generalized Linear Model (GLM).
  27. GLMs based on a reproductive Exponential Dispersion Model (EDM) aim at fitting and
  28. predicting the mean of the target y as y_pred=h(X*w) with coefficients w.
  29. Therefore, the fit minimizes the following objective function with L2 priors as
  30. regularizer::
  31. 1/(2*sum(s_i)) * sum(s_i * deviance(y_i, h(x_i*w)) + 1/2 * alpha * ||w||_2^2
  32. with inverse link function h, s=sample_weight and per observation (unit) deviance
  33. deviance(y_i, h(x_i*w)). Note that for an EDM, 1/2 * deviance is the negative
  34. log-likelihood up to a constant (in w) term.
  35. The parameter ``alpha`` corresponds to the lambda parameter in glmnet.
  36. Instead of implementing the EDM family and a link function separately, we directly
  37. use the loss functions `from sklearn._loss` which have the link functions included
  38. in them for performance reasons. We pick the loss functions that implement
  39. (1/2 times) EDM deviances.
  40. Read more in the :ref:`User Guide <Generalized_linear_models>`.
  41. .. versionadded:: 0.23
  42. Parameters
  43. ----------
  44. alpha : float, default=1
  45. Constant that multiplies the penalty term and thus determines the
  46. regularization strength. ``alpha = 0`` is equivalent to unpenalized
  47. GLMs. In this case, the design matrix `X` must have full column rank
  48. (no collinearities).
  49. Values must be in the range `[0.0, inf)`.
  50. fit_intercept : bool, default=True
  51. Specifies if a constant (a.k.a. bias or intercept) should be
  52. added to the linear predictor (X @ coef + intercept).
  53. solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs'
  54. Algorithm to use in the optimization problem:
  55. 'lbfgs'
  56. Calls scipy's L-BFGS-B optimizer.
  57. 'newton-cholesky'
  58. Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to
  59. iterated reweighted least squares) with an inner Cholesky based solver.
  60. This solver is a good choice for `n_samples` >> `n_features`, especially
  61. with one-hot encoded categorical features with rare categories. Be aware
  62. that the memory usage of this solver has a quadratic dependency on
  63. `n_features` because it explicitly computes the Hessian matrix.
  64. .. versionadded:: 1.2
  65. max_iter : int, default=100
  66. The maximal number of iterations for the solver.
  67. Values must be in the range `[1, inf)`.
  68. tol : float, default=1e-4
  69. Stopping criterion. For the lbfgs solver,
  70. the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
  71. where ``g_j`` is the j-th component of the gradient (derivative) of
  72. the objective function.
  73. Values must be in the range `(0.0, inf)`.
  74. warm_start : bool, default=False
  75. If set to ``True``, reuse the solution of the previous call to ``fit``
  76. as initialization for ``coef_`` and ``intercept_``.
  77. verbose : int, default=0
  78. For the lbfgs solver set verbose to any positive number for verbosity.
  79. Values must be in the range `[0, inf)`.
  80. Attributes
  81. ----------
  82. coef_ : array of shape (n_features,)
  83. Estimated coefficients for the linear predictor (`X @ coef_ +
  84. intercept_`) in the GLM.
  85. intercept_ : float
  86. Intercept (a.k.a. bias) added to linear predictor.
  87. n_iter_ : int
  88. Actual number of iterations used in the solver.
  89. _base_loss : BaseLoss, default=HalfSquaredError()
  90. This is set during fit via `self._get_loss()`.
  91. A `_base_loss` contains a specific loss function as well as the link
  92. function. The loss to be minimized specifies the distributional assumption of
  93. the GLM, i.e. the distribution from the EDM. Here are some examples:
  94. ======================= ======== ==========================
  95. _base_loss Link Target Domain
  96. ======================= ======== ==========================
  97. HalfSquaredError identity y any real number
  98. HalfPoissonLoss log 0 <= y
  99. HalfGammaLoss log 0 < y
  100. HalfTweedieLoss log dependent on tweedie power
  101. HalfTweedieLossIdentity identity dependent on tweedie power
  102. ======================= ======== ==========================
  103. The link function of the GLM, i.e. mapping from linear predictor
  104. `X @ coeff + intercept` to prediction `y_pred`. For instance, with a log link,
  105. we have `y_pred = exp(X @ coeff + intercept)`.
  106. """
  107. # We allow for NewtonSolver classes for the "solver" parameter but do not
  108. # make them public in the docstrings. This facilitates testing and
  109. # benchmarking.
  110. _parameter_constraints: dict = {
  111. "alpha": [Interval(Real, 0.0, None, closed="left")],
  112. "fit_intercept": ["boolean"],
  113. "solver": [
  114. StrOptions({"lbfgs", "newton-cholesky"}),
  115. Hidden(type),
  116. ],
  117. "max_iter": [Interval(Integral, 1, None, closed="left")],
  118. "tol": [Interval(Real, 0.0, None, closed="neither")],
  119. "warm_start": ["boolean"],
  120. "verbose": ["verbose"],
  121. }
  122. def __init__(
  123. self,
  124. *,
  125. alpha=1.0,
  126. fit_intercept=True,
  127. solver="lbfgs",
  128. max_iter=100,
  129. tol=1e-4,
  130. warm_start=False,
  131. verbose=0,
  132. ):
  133. self.alpha = alpha
  134. self.fit_intercept = fit_intercept
  135. self.solver = solver
  136. self.max_iter = max_iter
  137. self.tol = tol
  138. self.warm_start = warm_start
  139. self.verbose = verbose
  140. @_fit_context(prefer_skip_nested_validation=True)
  141. def fit(self, X, y, sample_weight=None):
  142. """Fit a Generalized Linear Model.
  143. Parameters
  144. ----------
  145. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  146. Training data.
  147. y : array-like of shape (n_samples,)
  148. Target values.
  149. sample_weight : array-like of shape (n_samples,), default=None
  150. Sample weights.
  151. Returns
  152. -------
  153. self : object
  154. Fitted model.
  155. """
  156. X, y = self._validate_data(
  157. X,
  158. y,
  159. accept_sparse=["csc", "csr"],
  160. dtype=[np.float64, np.float32],
  161. y_numeric=True,
  162. multi_output=False,
  163. )
  164. # required by losses
  165. if self.solver == "lbfgs":
  166. # lbfgs will force coef and therefore raw_prediction to be float64. The
  167. # base_loss needs y, X @ coef and sample_weight all of same dtype
  168. # (and contiguous).
  169. loss_dtype = np.float64
  170. else:
  171. loss_dtype = min(max(y.dtype, X.dtype), np.float64)
  172. y = check_array(y, dtype=loss_dtype, order="C", ensure_2d=False)
  173. # TODO: We could support samples_weight=None as the losses support it.
  174. # Note that _check_sample_weight calls check_array(order="C") required by
  175. # losses.
  176. sample_weight = _check_sample_weight(sample_weight, X, dtype=loss_dtype)
  177. n_samples, n_features = X.shape
  178. self._base_loss = self._get_loss()
  179. linear_loss = LinearModelLoss(
  180. base_loss=self._base_loss,
  181. fit_intercept=self.fit_intercept,
  182. )
  183. if not linear_loss.base_loss.in_y_true_range(y):
  184. raise ValueError(
  185. "Some value(s) of y are out of the valid range of the loss"
  186. f" {self._base_loss.__class__.__name__!r}."
  187. )
  188. # TODO: if alpha=0 check that X is not rank deficient
  189. # IMPORTANT NOTE: Rescaling of sample_weight:
  190. # We want to minimize
  191. # obj = 1/(2*sum(sample_weight)) * sum(sample_weight * deviance)
  192. # + 1/2 * alpha * L2,
  193. # with
  194. # deviance = 2 * loss.
  195. # The objective is invariant to multiplying sample_weight by a constant. We
  196. # choose this constant such that sum(sample_weight) = 1. Thus, we end up with
  197. # obj = sum(sample_weight * loss) + 1/2 * alpha * L2.
  198. # Note that LinearModelLoss.loss() computes sum(sample_weight * loss).
  199. sample_weight = sample_weight / sample_weight.sum()
  200. if self.warm_start and hasattr(self, "coef_"):
  201. if self.fit_intercept:
  202. # LinearModelLoss needs intercept at the end of coefficient array.
  203. coef = np.concatenate((self.coef_, np.array([self.intercept_])))
  204. else:
  205. coef = self.coef_
  206. coef = coef.astype(loss_dtype, copy=False)
  207. else:
  208. coef = linear_loss.init_zero_coef(X, dtype=loss_dtype)
  209. if self.fit_intercept:
  210. coef[-1] = linear_loss.base_loss.link.link(
  211. np.average(y, weights=sample_weight)
  212. )
  213. l2_reg_strength = self.alpha
  214. n_threads = _openmp_effective_n_threads()
  215. # Algorithms for optimization:
  216. # Note again that our losses implement 1/2 * deviance.
  217. if self.solver == "lbfgs":
  218. func = linear_loss.loss_gradient
  219. opt_res = scipy.optimize.minimize(
  220. func,
  221. coef,
  222. method="L-BFGS-B",
  223. jac=True,
  224. options={
  225. "maxiter": self.max_iter,
  226. "maxls": 50, # default is 20
  227. "iprint": self.verbose - 1,
  228. "gtol": self.tol,
  229. # The constant 64 was found empirically to pass the test suite.
  230. # The point is that ftol is very small, but a bit larger than
  231. # machine precision for float64, which is the dtype used by lbfgs.
  232. "ftol": 64 * np.finfo(float).eps,
  233. },
  234. args=(X, y, sample_weight, l2_reg_strength, n_threads),
  235. )
  236. self.n_iter_ = _check_optimize_result("lbfgs", opt_res)
  237. coef = opt_res.x
  238. elif self.solver == "newton-cholesky":
  239. sol = NewtonCholeskySolver(
  240. coef=coef,
  241. linear_loss=linear_loss,
  242. l2_reg_strength=l2_reg_strength,
  243. tol=self.tol,
  244. max_iter=self.max_iter,
  245. n_threads=n_threads,
  246. verbose=self.verbose,
  247. )
  248. coef = sol.solve(X, y, sample_weight)
  249. self.n_iter_ = sol.iteration
  250. elif issubclass(self.solver, NewtonSolver):
  251. sol = self.solver(
  252. coef=coef,
  253. linear_loss=linear_loss,
  254. l2_reg_strength=l2_reg_strength,
  255. tol=self.tol,
  256. max_iter=self.max_iter,
  257. n_threads=n_threads,
  258. )
  259. coef = sol.solve(X, y, sample_weight)
  260. self.n_iter_ = sol.iteration
  261. else:
  262. raise ValueError(f"Invalid solver={self.solver}.")
  263. if self.fit_intercept:
  264. self.intercept_ = coef[-1]
  265. self.coef_ = coef[:-1]
  266. else:
  267. # set intercept to zero as the other linear models do
  268. self.intercept_ = 0.0
  269. self.coef_ = coef
  270. return self
  271. def _linear_predictor(self, X):
  272. """Compute the linear_predictor = `X @ coef_ + intercept_`.
  273. Note that we often use the term raw_prediction instead of linear predictor.
  274. Parameters
  275. ----------
  276. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  277. Samples.
  278. Returns
  279. -------
  280. y_pred : array of shape (n_samples,)
  281. Returns predicted values of linear predictor.
  282. """
  283. check_is_fitted(self)
  284. X = self._validate_data(
  285. X,
  286. accept_sparse=["csr", "csc", "coo"],
  287. dtype=[np.float64, np.float32],
  288. ensure_2d=True,
  289. allow_nd=False,
  290. reset=False,
  291. )
  292. return X @ self.coef_ + self.intercept_
  293. def predict(self, X):
  294. """Predict using GLM with feature matrix X.
  295. Parameters
  296. ----------
  297. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  298. Samples.
  299. Returns
  300. -------
  301. y_pred : array of shape (n_samples,)
  302. Returns predicted values.
  303. """
  304. # check_array is done in _linear_predictor
  305. raw_prediction = self._linear_predictor(X)
  306. y_pred = self._base_loss.link.inverse(raw_prediction)
  307. return y_pred
  308. def score(self, X, y, sample_weight=None):
  309. """Compute D^2, the percentage of deviance explained.
  310. D^2 is a generalization of the coefficient of determination R^2.
  311. R^2 uses squared error and D^2 uses the deviance of this GLM, see the
  312. :ref:`User Guide <regression_metrics>`.
  313. D^2 is defined as
  314. :math:`D^2 = 1-\\frac{D(y_{true},y_{pred})}{D_{null}}`,
  315. :math:`D_{null}` is the null deviance, i.e. the deviance of a model
  316. with intercept alone, which corresponds to :math:`y_{pred} = \\bar{y}`.
  317. The mean :math:`\\bar{y}` is averaged by sample_weight.
  318. Best possible score is 1.0 and it can be negative (because the model
  319. can be arbitrarily worse).
  320. Parameters
  321. ----------
  322. X : {array-like, sparse matrix} of shape (n_samples, n_features)
  323. Test samples.
  324. y : array-like of shape (n_samples,)
  325. True values of target.
  326. sample_weight : array-like of shape (n_samples,), default=None
  327. Sample weights.
  328. Returns
  329. -------
  330. score : float
  331. D^2 of self.predict(X) w.r.t. y.
  332. """
  333. # TODO: Adapt link to User Guide in the docstring, once
  334. # https://github.com/scikit-learn/scikit-learn/pull/22118 is merged.
  335. #
  336. # Note, default score defined in RegressorMixin is R^2 score.
  337. # TODO: make D^2 a score function in module metrics (and thereby get
  338. # input validation and so on)
  339. raw_prediction = self._linear_predictor(X) # validates X
  340. # required by losses
  341. y = check_array(y, dtype=raw_prediction.dtype, order="C", ensure_2d=False)
  342. if sample_weight is not None:
  343. # Note that _check_sample_weight calls check_array(order="C") required by
  344. # losses.
  345. sample_weight = _check_sample_weight(sample_weight, X, dtype=y.dtype)
  346. base_loss = self._base_loss
  347. if not base_loss.in_y_true_range(y):
  348. raise ValueError(
  349. "Some value(s) of y are out of the valid range of the loss"
  350. f" {base_loss.__name__}."
  351. )
  352. # Note that constant_to_optimal_zero is already multiplied by sample_weight.
  353. constant = np.mean(base_loss.constant_to_optimal_zero(y_true=y))
  354. if sample_weight is not None:
  355. constant *= sample_weight.shape[0] / np.sum(sample_weight)
  356. # Missing factor of 2 in deviance cancels out.
  357. deviance = base_loss(
  358. y_true=y,
  359. raw_prediction=raw_prediction,
  360. sample_weight=sample_weight,
  361. n_threads=1,
  362. )
  363. y_mean = base_loss.link.link(np.average(y, weights=sample_weight))
  364. deviance_null = base_loss(
  365. y_true=y,
  366. raw_prediction=np.tile(y_mean, y.shape[0]),
  367. sample_weight=sample_weight,
  368. n_threads=1,
  369. )
  370. return 1 - (deviance + constant) / (deviance_null + constant)
  371. def _more_tags(self):
  372. try:
  373. # Create instance of BaseLoss if fit wasn't called yet. This is necessary as
  374. # TweedieRegressor might set the used loss during fit different from
  375. # self._base_loss.
  376. base_loss = self._get_loss()
  377. return {"requires_positive_y": not base_loss.in_y_true_range(-1.0)}
  378. except (ValueError, AttributeError, TypeError):
  379. # This happens when the link or power parameter of TweedieRegressor is
  380. # invalid. We fallback on the default tags in that case.
  381. return {}
  382. def _get_loss(self):
  383. """This is only necessary because of the link and power arguments of the
  384. TweedieRegressor.
  385. Note that we do not need to pass sample_weight to the loss class as this is
  386. only needed to set loss.constant_hessian on which GLMs do not rely.
  387. """
  388. return HalfSquaredError()
  389. class PoissonRegressor(_GeneralizedLinearRegressor):
  390. """Generalized Linear Model with a Poisson distribution.
  391. This regressor uses the 'log' link function.
  392. Read more in the :ref:`User Guide <Generalized_linear_models>`.
  393. .. versionadded:: 0.23
  394. Parameters
  395. ----------
  396. alpha : float, default=1
  397. Constant that multiplies the L2 penalty term and determines the
  398. regularization strength. ``alpha = 0`` is equivalent to unpenalized
  399. GLMs. In this case, the design matrix `X` must have full column rank
  400. (no collinearities).
  401. Values of `alpha` must be in the range `[0.0, inf)`.
  402. fit_intercept : bool, default=True
  403. Specifies if a constant (a.k.a. bias or intercept) should be
  404. added to the linear predictor (`X @ coef + intercept`).
  405. solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs'
  406. Algorithm to use in the optimization problem:
  407. 'lbfgs'
  408. Calls scipy's L-BFGS-B optimizer.
  409. 'newton-cholesky'
  410. Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to
  411. iterated reweighted least squares) with an inner Cholesky based solver.
  412. This solver is a good choice for `n_samples` >> `n_features`, especially
  413. with one-hot encoded categorical features with rare categories. Be aware
  414. that the memory usage of this solver has a quadratic dependency on
  415. `n_features` because it explicitly computes the Hessian matrix.
  416. .. versionadded:: 1.2
  417. max_iter : int, default=100
  418. The maximal number of iterations for the solver.
  419. Values must be in the range `[1, inf)`.
  420. tol : float, default=1e-4
  421. Stopping criterion. For the lbfgs solver,
  422. the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
  423. where ``g_j`` is the j-th component of the gradient (derivative) of
  424. the objective function.
  425. Values must be in the range `(0.0, inf)`.
  426. warm_start : bool, default=False
  427. If set to ``True``, reuse the solution of the previous call to ``fit``
  428. as initialization for ``coef_`` and ``intercept_`` .
  429. verbose : int, default=0
  430. For the lbfgs solver set verbose to any positive number for verbosity.
  431. Values must be in the range `[0, inf)`.
  432. Attributes
  433. ----------
  434. coef_ : array of shape (n_features,)
  435. Estimated coefficients for the linear predictor (`X @ coef_ +
  436. intercept_`) in the GLM.
  437. intercept_ : float
  438. Intercept (a.k.a. bias) added to linear predictor.
  439. n_features_in_ : int
  440. Number of features seen during :term:`fit`.
  441. .. versionadded:: 0.24
  442. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  443. Names of features seen during :term:`fit`. Defined only when `X`
  444. has feature names that are all strings.
  445. .. versionadded:: 1.0
  446. n_iter_ : int
  447. Actual number of iterations used in the solver.
  448. See Also
  449. --------
  450. TweedieRegressor : Generalized Linear Model with a Tweedie distribution.
  451. Examples
  452. --------
  453. >>> from sklearn import linear_model
  454. >>> clf = linear_model.PoissonRegressor()
  455. >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
  456. >>> y = [12, 17, 22, 21]
  457. >>> clf.fit(X, y)
  458. PoissonRegressor()
  459. >>> clf.score(X, y)
  460. 0.990...
  461. >>> clf.coef_
  462. array([0.121..., 0.158...])
  463. >>> clf.intercept_
  464. 2.088...
  465. >>> clf.predict([[1, 1], [3, 4]])
  466. array([10.676..., 21.875...])
  467. """
  468. _parameter_constraints: dict = {
  469. **_GeneralizedLinearRegressor._parameter_constraints
  470. }
  471. def __init__(
  472. self,
  473. *,
  474. alpha=1.0,
  475. fit_intercept=True,
  476. solver="lbfgs",
  477. max_iter=100,
  478. tol=1e-4,
  479. warm_start=False,
  480. verbose=0,
  481. ):
  482. super().__init__(
  483. alpha=alpha,
  484. fit_intercept=fit_intercept,
  485. solver=solver,
  486. max_iter=max_iter,
  487. tol=tol,
  488. warm_start=warm_start,
  489. verbose=verbose,
  490. )
  491. def _get_loss(self):
  492. return HalfPoissonLoss()
  493. class GammaRegressor(_GeneralizedLinearRegressor):
  494. """Generalized Linear Model with a Gamma distribution.
  495. This regressor uses the 'log' link function.
  496. Read more in the :ref:`User Guide <Generalized_linear_models>`.
  497. .. versionadded:: 0.23
  498. Parameters
  499. ----------
  500. alpha : float, default=1
  501. Constant that multiplies the L2 penalty term and determines the
  502. regularization strength. ``alpha = 0`` is equivalent to unpenalized
  503. GLMs. In this case, the design matrix `X` must have full column rank
  504. (no collinearities).
  505. Values of `alpha` must be in the range `[0.0, inf)`.
  506. fit_intercept : bool, default=True
  507. Specifies if a constant (a.k.a. bias or intercept) should be
  508. added to the linear predictor `X @ coef_ + intercept_`.
  509. solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs'
  510. Algorithm to use in the optimization problem:
  511. 'lbfgs'
  512. Calls scipy's L-BFGS-B optimizer.
  513. 'newton-cholesky'
  514. Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to
  515. iterated reweighted least squares) with an inner Cholesky based solver.
  516. This solver is a good choice for `n_samples` >> `n_features`, especially
  517. with one-hot encoded categorical features with rare categories. Be aware
  518. that the memory usage of this solver has a quadratic dependency on
  519. `n_features` because it explicitly computes the Hessian matrix.
  520. .. versionadded:: 1.2
  521. max_iter : int, default=100
  522. The maximal number of iterations for the solver.
  523. Values must be in the range `[1, inf)`.
  524. tol : float, default=1e-4
  525. Stopping criterion. For the lbfgs solver,
  526. the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
  527. where ``g_j`` is the j-th component of the gradient (derivative) of
  528. the objective function.
  529. Values must be in the range `(0.0, inf)`.
  530. warm_start : bool, default=False
  531. If set to ``True``, reuse the solution of the previous call to ``fit``
  532. as initialization for `coef_` and `intercept_`.
  533. verbose : int, default=0
  534. For the lbfgs solver set verbose to any positive number for verbosity.
  535. Values must be in the range `[0, inf)`.
  536. Attributes
  537. ----------
  538. coef_ : array of shape (n_features,)
  539. Estimated coefficients for the linear predictor (`X @ coef_ +
  540. intercept_`) in the GLM.
  541. intercept_ : float
  542. Intercept (a.k.a. bias) added to linear predictor.
  543. n_features_in_ : int
  544. Number of features seen during :term:`fit`.
  545. .. versionadded:: 0.24
  546. n_iter_ : int
  547. Actual number of iterations used in the solver.
  548. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  549. Names of features seen during :term:`fit`. Defined only when `X`
  550. has feature names that are all strings.
  551. .. versionadded:: 1.0
  552. See Also
  553. --------
  554. PoissonRegressor : Generalized Linear Model with a Poisson distribution.
  555. TweedieRegressor : Generalized Linear Model with a Tweedie distribution.
  556. Examples
  557. --------
  558. >>> from sklearn import linear_model
  559. >>> clf = linear_model.GammaRegressor()
  560. >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
  561. >>> y = [19, 26, 33, 30]
  562. >>> clf.fit(X, y)
  563. GammaRegressor()
  564. >>> clf.score(X, y)
  565. 0.773...
  566. >>> clf.coef_
  567. array([0.072..., 0.066...])
  568. >>> clf.intercept_
  569. 2.896...
  570. >>> clf.predict([[1, 0], [2, 8]])
  571. array([19.483..., 35.795...])
  572. """
  573. _parameter_constraints: dict = {
  574. **_GeneralizedLinearRegressor._parameter_constraints
  575. }
  576. def __init__(
  577. self,
  578. *,
  579. alpha=1.0,
  580. fit_intercept=True,
  581. solver="lbfgs",
  582. max_iter=100,
  583. tol=1e-4,
  584. warm_start=False,
  585. verbose=0,
  586. ):
  587. super().__init__(
  588. alpha=alpha,
  589. fit_intercept=fit_intercept,
  590. solver=solver,
  591. max_iter=max_iter,
  592. tol=tol,
  593. warm_start=warm_start,
  594. verbose=verbose,
  595. )
  596. def _get_loss(self):
  597. return HalfGammaLoss()
  598. class TweedieRegressor(_GeneralizedLinearRegressor):
  599. """Generalized Linear Model with a Tweedie distribution.
  600. This estimator can be used to model different GLMs depending on the
  601. ``power`` parameter, which determines the underlying distribution.
  602. Read more in the :ref:`User Guide <Generalized_linear_models>`.
  603. .. versionadded:: 0.23
  604. Parameters
  605. ----------
  606. power : float, default=0
  607. The power determines the underlying target distribution according
  608. to the following table:
  609. +-------+------------------------+
  610. | Power | Distribution |
  611. +=======+========================+
  612. | 0 | Normal |
  613. +-------+------------------------+
  614. | 1 | Poisson |
  615. +-------+------------------------+
  616. | (1,2) | Compound Poisson Gamma |
  617. +-------+------------------------+
  618. | 2 | Gamma |
  619. +-------+------------------------+
  620. | 3 | Inverse Gaussian |
  621. +-------+------------------------+
  622. For ``0 < power < 1``, no distribution exists.
  623. alpha : float, default=1
  624. Constant that multiplies the L2 penalty term and determines the
  625. regularization strength. ``alpha = 0`` is equivalent to unpenalized
  626. GLMs. In this case, the design matrix `X` must have full column rank
  627. (no collinearities).
  628. Values of `alpha` must be in the range `[0.0, inf)`.
  629. fit_intercept : bool, default=True
  630. Specifies if a constant (a.k.a. bias or intercept) should be
  631. added to the linear predictor (`X @ coef + intercept`).
  632. link : {'auto', 'identity', 'log'}, default='auto'
  633. The link function of the GLM, i.e. mapping from linear predictor
  634. `X @ coeff + intercept` to prediction `y_pred`. Option 'auto' sets
  635. the link depending on the chosen `power` parameter as follows:
  636. - 'identity' for ``power <= 0``, e.g. for the Normal distribution
  637. - 'log' for ``power > 0``, e.g. for Poisson, Gamma and Inverse Gaussian
  638. distributions
  639. solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs'
  640. Algorithm to use in the optimization problem:
  641. 'lbfgs'
  642. Calls scipy's L-BFGS-B optimizer.
  643. 'newton-cholesky'
  644. Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to
  645. iterated reweighted least squares) with an inner Cholesky based solver.
  646. This solver is a good choice for `n_samples` >> `n_features`, especially
  647. with one-hot encoded categorical features with rare categories. Be aware
  648. that the memory usage of this solver has a quadratic dependency on
  649. `n_features` because it explicitly computes the Hessian matrix.
  650. .. versionadded:: 1.2
  651. max_iter : int, default=100
  652. The maximal number of iterations for the solver.
  653. Values must be in the range `[1, inf)`.
  654. tol : float, default=1e-4
  655. Stopping criterion. For the lbfgs solver,
  656. the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol``
  657. where ``g_j`` is the j-th component of the gradient (derivative) of
  658. the objective function.
  659. Values must be in the range `(0.0, inf)`.
  660. warm_start : bool, default=False
  661. If set to ``True``, reuse the solution of the previous call to ``fit``
  662. as initialization for ``coef_`` and ``intercept_`` .
  663. verbose : int, default=0
  664. For the lbfgs solver set verbose to any positive number for verbosity.
  665. Values must be in the range `[0, inf)`.
  666. Attributes
  667. ----------
  668. coef_ : array of shape (n_features,)
  669. Estimated coefficients for the linear predictor (`X @ coef_ +
  670. intercept_`) in the GLM.
  671. intercept_ : float
  672. Intercept (a.k.a. bias) added to linear predictor.
  673. n_iter_ : int
  674. Actual number of iterations used in the solver.
  675. n_features_in_ : int
  676. Number of features seen during :term:`fit`.
  677. .. versionadded:: 0.24
  678. feature_names_in_ : ndarray of shape (`n_features_in_`,)
  679. Names of features seen during :term:`fit`. Defined only when `X`
  680. has feature names that are all strings.
  681. .. versionadded:: 1.0
  682. See Also
  683. --------
  684. PoissonRegressor : Generalized Linear Model with a Poisson distribution.
  685. GammaRegressor : Generalized Linear Model with a Gamma distribution.
  686. Examples
  687. --------
  688. >>> from sklearn import linear_model
  689. >>> clf = linear_model.TweedieRegressor()
  690. >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]]
  691. >>> y = [2, 3.5, 5, 5.5]
  692. >>> clf.fit(X, y)
  693. TweedieRegressor()
  694. >>> clf.score(X, y)
  695. 0.839...
  696. >>> clf.coef_
  697. array([0.599..., 0.299...])
  698. >>> clf.intercept_
  699. 1.600...
  700. >>> clf.predict([[1, 1], [3, 4]])
  701. array([2.500..., 4.599...])
  702. """
  703. _parameter_constraints: dict = {
  704. **_GeneralizedLinearRegressor._parameter_constraints,
  705. "power": [Interval(Real, None, None, closed="neither")],
  706. "link": [StrOptions({"auto", "identity", "log"})],
  707. }
  708. def __init__(
  709. self,
  710. *,
  711. power=0.0,
  712. alpha=1.0,
  713. fit_intercept=True,
  714. link="auto",
  715. solver="lbfgs",
  716. max_iter=100,
  717. tol=1e-4,
  718. warm_start=False,
  719. verbose=0,
  720. ):
  721. super().__init__(
  722. alpha=alpha,
  723. fit_intercept=fit_intercept,
  724. solver=solver,
  725. max_iter=max_iter,
  726. tol=tol,
  727. warm_start=warm_start,
  728. verbose=verbose,
  729. )
  730. self.link = link
  731. self.power = power
  732. def _get_loss(self):
  733. if self.link == "auto":
  734. if self.power <= 0:
  735. # identity link
  736. return HalfTweedieLossIdentity(power=self.power)
  737. else:
  738. # log link
  739. return HalfTweedieLoss(power=self.power)
  740. if self.link == "log":
  741. return HalfTweedieLoss(power=self.power)
  742. if self.link == "identity":
  743. return HalfTweedieLossIdentity(power=self.power)