Liking cljdoc? Tell your friends :D

fastmath.ml.regression

Linear and generalized linear regression models with analysis, categorical encodings and isotonic regression.

lm fits ordinary (OLS) and weighted (WLS) least squares models, glm fits generalized linear models with the IRLS method for the families and links stored in families and links (custom ones are created with ->family and ->link), glm-nbinomial additionally estimates theta of the negative binomial family. Both fit functions can use an offset, weights, a transformation of the terms (see polynomial-transformer, trigonometric-transformer and b-spline-transformer) and regularization by data augmentation (add-penalty).

A fitted model is a record which can be called as a function (see predict). analysis returns leverage, residuals and influence measures, quantile-residuals the randomized quantile residuals of a GLM and dose the lethal or effective dose of a binomial model. Categorical terms are encoded with fastmath.ml.regression.contrast.

Isotonic regression is available as pava and cir.

Linear and generalized linear regression models with analysis, categorical encodings and isotonic regression.

[[lm]] fits ordinary (OLS) and weighted (WLS) least squares models, [[glm]] fits generalized linear models with the IRLS method for the families and links stored in [[families]] and [[links]] (custom ones are created with [[->family]] and [[->link]]), [[glm-nbinomial]] additionally estimates theta of the negative binomial family. Both fit functions can use an offset, weights, a transformation of the terms (see [[polynomial-transformer]], [[trigonometric-transformer]] and [[b-spline-transformer]]) and regularization by data augmentation ([[add-penalty]]).

A fitted model is a record which can be called as a function (see [[predict]]). [[analysis]] returns leverage, residuals and influence measures, [[quantile-residuals]] the randomized quantile residuals of a GLM and [[dose]] the lethal or effective dose of a binomial model. Categorical terms are encoded with `fastmath.ml.regression.contrast`.

Isotonic regression is available as [[pava]] and [[cir]].
raw docstring

->familyclj

(->family family-map)
(->family variance residual-deviance)
(->family default-link
          variance
          initialize
          residual-deviance
          aic
          quantile-residuals-fun
          dispersion)

Create Family record.

Arguments:

  • default-link - canonical link function, default: :identity
  • variance - variance function in terms of mean
  • initialize - initialization of glm, default: the same as in :gaussian
  • residual-deviance - calculates residual deviance
  • aic - calculates AIC, default (constantly ##NaN)
  • quantile-residuals-fun - calculates quantile residuals, default as in :gaussian
  • disperation - value or :estimate (default), :pearson or :mean-deviance

Initialization will be called with ys and weights and should return:

  • ys, possibly changed if any adjustment is necessary
  • init-mu, starting point
  • weights, possibly changes or orignal
  • (optional) any other data used to calculate AIC

AIC function should accept: ys, fitted, weights, deviance, observation, rank (fitted parameters) and additional data created by initialization

Minimum version should define variance and residual-deviance.

Create `Family` record.

Arguments:

* `default-link` - canonical link function, default: `:identity`
* `variance` - variance function in terms of mean
* `initialize` - initialization of glm, default: the same as in `:gaussian`
* `residual-deviance` - calculates residual deviance
* `aic` - calculates AIC, default `(constantly ##NaN)`
* `quantile-residuals-fun` - calculates quantile residuals, default as in `:gaussian`
* `disperation` - value or `:estimate` (default), `:pearson` or `:mean-deviance`

Initialization will be called with `ys` and `weights` and should return:

* ys, possibly changed if any adjustment is necessary
* init-mu, starting point
* weights, possibly changes or orignal
* (optional) any other data used to calculate AIC

AIC function should accept: `ys`, `fitted`, `weights`, `deviance`, `observation`, `rank` (fitted parameters) and additional data created by initialization

Minimum version should define `variance` and `residual-deviance`.
raw docstring

(->link link-map)
(->link g mean mean-derivative)

Creates link record.

Args:

  • g - link function
  • mean - mean, inverse link function
  • mean-derivative - derivative of mean
Creates link record.

Args:

* `g` - link function
* `mean` - mean, inverse link function
* `mean-derivative` - derivative of mean
raw docstring

->stringcljmultimethod

Returns a text summary of the fitted model (LMData or GLMData): residuals, coefficient table and fit statistics. It is used by print-method and toString of the models.

Returns a text summary of the fitted model (`LMData` or `GLMData`): residuals, coefficient table and fit statistics. It is used by `print-method` and `toString` of the models.
raw docstring

add-penaltyclj

(add-penalty xss penalty penalty-param)
(add-penalty xss penalty penalty-param intercept?)

Adds rows with penalty data to a given seq of seqs (a row matrix).

Penalties and parameters map:

  • :ridge - diagonal matrix with sqrt(:lambda) parameter, used in regularized regression.
  • :diffs - differences of given :order multiplied by sqrt(:lambda), used in penalized b-splines.

Two add more than one penalty, create seq of penalty types and parameters, eg: [:diffs :ridge]

Adds rows with penalty data to a given seq of seqs (a row matrix).

Penalties and parameters map:

* `:ridge` - diagonal matrix with sqrt(`:lambda`) parameter, used in regularized regression.
* `:diffs` - differences of given `:order` multiplied by sqrt(`:lambda`), used in penalized b-splines.

Two add more than one penalty, create seq of penalty types and parameters, eg: `[:diffs :ridge]`
raw docstring

analysisclj

(analysis model)

Influence analysis, leverage, standardized and studentized residuals, correlation.

Parameters:

  • model - a model returned by lm or glm

Returns the map described in the documentation of lm and glm (it is calculated once, on the first call). Entries for observations with a zero weight are ##NaN and these observations are never listed in :influential.

See also quantile-residuals.

Influence analysis, leverage, standardized and studentized residuals, correlation.

Parameters:

- `model` - a model returned by [[lm]] or [[glm]]

Returns the map described in the documentation of [[lm]] and [[glm]] (it is calculated once, on the first call). Entries for observations with a zero weight are `##NaN` and these observations are never listed in `:influential`.

See also [[quantile-residuals]].
raw docstring

b-spline-transformerclj

(b-spline-transformer xs nseg degree)
(b-spline-transformer xl xr nseg degree)

Creates a transformer which expands a number into B-spline basis functions on equally spaced knots, as splineDesign in R.

Parameters:

  • xs - training values of the variable, their minimum and maximum are xl and xr
  • xl, xr - the range of the variable (the arity without xs)
  • nseg - number of segments between xl and xr
  • degree - the degree of B-splines, at least 1 (3 is cubic)

Returns a function which accepts a one element data point [x] (a model :transformer) and returns a sequence of nseg + degree basis functions evaluated at x. The functions sum up to 1.0 for x in [xl, xr].

Use the :diffs penalty of the :augmentation option of lm and glm for smoothing (P-splines).

See also polynomial-transformer, trigonometric-transformer, add-penalty.

Creates a transformer which expands a number into B-spline basis functions on equally spaced knots, as `splineDesign` in R.

Parameters:

- `xs` - training values of the variable, their minimum and maximum are `xl` and `xr`
- `xl`, `xr` - the range of the variable (the arity without `xs`)
- `nseg` - number of segments between `xl` and `xr`
- `degree` - the degree of B-splines, at least `1` (`3` is cubic)

Returns a function which accepts a one element data point `[x]` (a model `:transformer`) and returns a sequence of `nseg + degree` basis functions evaluated at `x`. The functions sum up to `1.0` for `x` in `[xl, xr]`.

Use the `:diffs` penalty of the `:augmentation` option of [[lm]] and [[glm]] for smoothing (P-splines).

See also [[polynomial-transformer]], [[trigonometric-transformer]], [[add-penalty]].
raw docstring

circlj

(cir ys)
(cir xs ys)
(cir xs ys order)
(cir xs ys ws order)

Centered Isotonic Regression.

Returns shrinked [xs,ys] pair.

Arguments:

  • xs - regressor variable
  • ys - response variable
  • ws - weights (optional)
  • order - :asc or :increasing (default), :desc or :decreasing, :non-decreasing and :non-increasing.

Returns a pair of empty sequences for an empty ys.

Throws ex-info for a not finite response, for xs which are not finite or not sorted ascending, for weights which are not finite and positive, for the data of different lengths and for an unknown order.

Centered Isotonic Regression.

Returns shrinked [`xs`,`ys`] pair.

Arguments:
- `xs` - regressor variable
- `ys` - response variable
- `ws` - weights (optional)
- `order` - `:asc` or `:increasing` (default), `:desc` or `:decreasing`, `:non-decreasing` and `:non-increasing`.

Returns a pair of empty sequences for an empty `ys`.

Throws `ex-info` for a not finite response, for `xs` which are not finite or not sorted ascending, for weights which are not finite and positive, for the data of different lengths and for an unknown order.
raw docstring

doseclj

(dose glm-model)
(dose glm-model p)
(dose glm-model p coeff-id)
(dose {:keys [link-fun xtxinv intercept? intercept beta dispersion]}
      p
      intercept-id
      coeff-id)

Predict Lethal/Effective dose for given p (default: p=0.5, median).

  • intercept-id - id of intercept, default: 0
  • coeff-id is the coefficient used for calculating dose, default: 1

The model can be fitted with :simple? true. Throws ex-info when an index is not an index of a coefficient. For p of 0 or 1 the link is infinite: the dose and its :stderr are infinite.

:stderr is scaled by the model's :dispersion (1.0 for fixed-dispersion families such as binomial/poisson, so a no-op there; the estimated value for gaussian/gamma/inverse-gaussian/quasi-* families, where the parameter covariance is dispersion * xtxinv, not xtxinv alone).

Predict Lethal/Effective dose for given `p` (default: p=0.5, median).

* intercept-id - id of intercept, default: 0
* coeff-id is the coefficient used for calculating dose, default: 1

The model can be fitted with `:simple? true`. Throws `ex-info` when an index is not an index of a coefficient. For `p` of `0` or `1` the link is infinite: the dose and its `:stderr` are infinite.

`:stderr` is scaled by the model's `:dispersion` (1.0 for fixed-dispersion
families such as binomial/poisson, so a no-op there; the estimated value
for gaussian/gamma/inverse-gaussian/quasi-* families, where the parameter
covariance is `dispersion * xtxinv`, not `xtxinv` alone).
raw docstring

familiesclj

Families of GLM, a map from a keyword to a Family record (see ->family) or to a function returning a Family from a map of parameters.

Records: :binomial, :quasi-binomial, :gaussian, :gamma, :poisson, :quasi-poisson and :inverse-gaussian. The :quasi- families estimate the dispersion, :binomial and :poisson fix it to 1.0.

Functions: :nbinomial (parameter :nbinomial-theta, default 1.0).

Each family has the canonical link as the default one: :logit for the binomial families, :identity for :gaussian, :inverse for :gamma, :log for the poisson families and :nbinomial, :inversesq for :inverse-gaussian. Use family-with-link to get a family merged with a link.

Families of GLM, a map from a keyword to a `Family` record (see [[->family]]) or to a function returning a `Family` from a map of parameters.

Records: `:binomial`, `:quasi-binomial`, `:gaussian`, `:gamma`, `:poisson`, `:quasi-poisson` and `:inverse-gaussian`. The `:quasi-` families estimate the dispersion, `:binomial` and `:poisson` fix it to `1.0`.

Functions: `:nbinomial` (parameter `:nbinomial-theta`, default `1.0`).

Each family has the canonical link as the default one: `:logit` for the binomial families, `:identity` for `:gaussian`, `:inverse` for `:gamma`, `:log` for the poisson families and `:nbinomial`, `:inversesq` for `:inverse-gaussian`. Use [[family-with-link]] to get a family merged with a link.
raw docstring

(family-with-link family)
(family-with-link family params)
(family-with-link family link params)

Returns family with a link as single map.

Returns family with a link as single map.
raw docstring

glmclj

(glm ys xss)
(glm ys
     xss
     {:keys [max-iters tol epsilon family link weights alpha offset
             dispersion-estimator intercept? init-mu simple? transformer names
             decomposition augmentation augmentation-params]
      :or {max-iters 25
           tol 1.0E-8
           epsilon 1.0E-8
           family :gaussian
           alpha 0.05
           intercept? true
           simple? false
           decomposition :cholesky}
      :as params})

Fit a generalized linear model using IRLS method.

Arguments:

  • ys - response vector
  • xss - terms of systematic component
  • optional parameters

Parameters:

  • :tol - tolerance of the matrix decomposition: the relative threshold of small singular values (rank deficiency of the model matrix) and the threshold of the QR/RRQR decomposition, default: 1.0e-8
  • :epsilon - tolerance for IRLS (stopping condition): relative change of the deviance, default: 1.0e-8
  • :max-iters - maximum numbers of iterations, an integer >= 1, default: 25
  • :weights - optional weights, finite and non-negative; an observation with the weight 0 stays in :fitted and :residuals but it does not take part in the model (it is not counted in :nobs and degrees of freedom)
  • :offset - optional offset
  • :alpha - significance level, default: 0.05
  • :intercept? - should intercept term be included, default: true
  • :init-mu - initial response vector for IRLS (finite numbers, one for each observation)
  • :simple? - returns simplified result
  • :dispersion-estimator - :pearson, :mean-deviance or any positive number, replaces default one.
  • :family - family, default: :gaussian
  • :link - link
  • :nbinomial-theta - theta for :nbinomial family, default: 1.0.
  • :transformer - an optional function which will be used to transform systematic component xs before fitting and prediction
  • :names - an optional vector of names to use when printing the model
  • :decomposition - which matrix decomposition use to find solution, :cholesky (default), :rrqr (rank revealing) or :qr
  • :augmentation and augmentation-params - regularization by data augmentation
    • :ridge - adds ridge regresion penalty (intercept is not penalized), default parameters {:lambda 0.1}
    • :diffs - adds differences penalty, use with b-spline-transformation for smoothing, default parameters {:lambda 1.0 :order 2}

Family is one of the: :gaussian (default), :binomial, :quasi-binomial, :poisson, :quasi-poisson, :gamma, :inverse-gaussian, :nbinomial, custom Family record (see ->family) or a function returning Family (accepting a map as an argument)

Link is one of the: :probit, :identity, :loglog, :sqrt, :inverse, :logit, :power (parameter :power-exponent, default 1.0; the exponent 0.0 is the :log link), :nbinomial, :cauchit, :distribution (parameter :distribution), :cloglog, :inversesq, :log, :clog, custom Link record (see ->link) or a function returning Link (accepting a map as an argument)

Notes:

  • SVD decomposition is used instead of more common QR
  • intercept term is added implicitely if intercept? is set to true (by default)
  • :nbinomial family requires :nbinomial-theta parameter
  • Each family has its own default (canonical) link.
  • For the :binomial families ys can be a sequence of pairs [successes failures]; the weights are multiplied by the number of trials.
  • Gaussian AIC uses the observations with a positive weight (R returns infinity when a weight is zero).

The fit does not depend on the units of the terms nor on the scale of the weights (see lm).

Throws ex-info when an option is invalid (:option, :value and :expected in the data), when the response is outside of the domain of the family (proportions for binomial, non-negative values for poisson and negative binomial, positive values for gamma and inverse gaussian, finite numbers otherwise), when the terms are not finite numbers or the rows have different lengths, when the lengths of ys, xss, :weights, :offset and :init-mu differ, when weights are negative or not finite, when the model has no terms, when the model matrix is rank deficient (:rank, :columns, :tol and :singular-values in the data), when the variance of the mean is invalid or the IRLS equations are singular, which usually means a diverging fit, eg. perfect separation (:iteration in the data) and when a family with an estimated dispersion has no residual degrees of freedom.

Returned record implementes IFn protocol and contains:

  • :model - set to :glm
  • :intercept? - whether intercept term is included or not
  • :xtxinv - (X^T X)^-1
  • :intercept - intercept term value
  • :beta - vector of model coefficients (without intercept)
  • :coefficients - coefficient analysis, a list of maps containing :estimate, :stderr, :t-value, :p-value and :confidence-interval
  • :weights - weights, :weights (working) and :initial
  • :residuals - a map containing :raw, :working, :pearsons and :deviance residuals
  • :fitted - fitted values for xss
  • :df - degrees of freedom: :residual, :null and :intercept
  • :observations - number of observations (rows)
  • :nobs - number of observations with a positive weight, used in degrees of freedom and information criteria
  • :deviance - deviances: :residual and :null
  • :dispersion - default or calculated, used in a model
  • :dispersions - :pearson and :mean-deviance
  • :family - family used
  • :link - link used
  • :link-fun - link function, g
  • :mean-fun - mean function, g^-1
  • :q - (1-alpha/2) quantile of T or Normal distribution for residual degrees of freedom
  • :chi2 and :p-value - Chi-squared statistic and respective p-value
  • :ll - a map containing log-likelihood and AIC/BIC (GLM and based on deviance, dev+2ED)
  • :analysis - leverage, residual and influence analysis - a delay
  • :iters and :converged? - number of iterations and convergence indicator (true when the change of the deviance is smaller than :epsilon, also at the last allowed iteration)
  • :decomposition - decomposition used

Analysis, delay containing a map:

  • :residuals - :standardized and :studentized residuals (pearsons and deviance)
  • :leverage - :hat, :sigmas and leveraged :coefficients (leave-one-out)
  • :influence - :cooks-distance, :dffits, :dfbetas and :covratio
  • :influential - list of influential observations (ids) for influence measures
  • :correlation - correlation matrix of estimated parameters
Fit a generalized linear model using IRLS method.

Arguments:

* `ys` - response vector
* `xss` - terms of systematic component
* optional parameters

Parameters:

* `:tol` - tolerance of the matrix decomposition: the relative threshold of small singular values (rank deficiency of the model matrix) and the threshold of the QR/RRQR decomposition, default: `1.0e-8`
* `:epsilon` - tolerance for IRLS (stopping condition): relative change of the deviance, default: `1.0e-8`
* `:max-iters` - maximum numbers of iterations, an integer >= 1, default: `25`
* `:weights` - optional weights, finite and non-negative; an observation with the weight 0 stays in `:fitted` and `:residuals` but it does not take part in the model (it is not counted in `:nobs` and degrees of freedom)
* `:offset` - optional offset
* `:alpha` - significance level, default: `0.05`
* `:intercept?` - should intercept term be included, default: `true`
* `:init-mu` - initial response vector for IRLS (finite numbers, one for each observation)
* `:simple?` - returns simplified result
* `:dispersion-estimator` - `:pearson`, `:mean-deviance` or any positive number, replaces default one.
* `:family` - family, default: `:gaussian`
* `:link` - link
* `:nbinomial-theta` - theta for `:nbinomial` family, default: `1.0`.
* `:transformer` - an optional function which will be used to transform systematic component `xs` before fitting and prediction
* `:names` - an optional vector of names to use when printing the model
* `:decomposition` - which matrix decomposition use to find solution, `:cholesky` (default), `:rrqr` (rank revealing) or `:qr`
* `:augmentation` and `augmentation-params` - regularization by data augmentation
    - `:ridge` - adds ridge regresion penalty (intercept is not penalized), default parameters `{:lambda 0.1}` 
    - `:diffs` - adds differences penalty, use with `b-spline-transformation` for smoothing, default parameters `{:lambda 1.0 :order 2}` 


Family is one of the: `:gaussian` (default), `:binomial`, `:quasi-binomial`, `:poisson`, `:quasi-poisson`, `:gamma`, `:inverse-gaussian`, `:nbinomial`, custom `Family` record (see [[->family]]) or a function returning Family (accepting a map as an argument)

Link is one of the: `:probit`, `:identity`, `:loglog`, `:sqrt`, `:inverse`, `:logit`, `:power` (parameter `:power-exponent`, default `1.0`; the exponent `0.0` is the `:log` link), `:nbinomial`, `:cauchit`, `:distribution` (parameter `:distribution`), `:cloglog`, `:inversesq`, `:log`, `:clog`, custom `Link` record (see [[->link]]) or a function returning Link (accepting a map as an argument)

Notes:

* SVD decomposition is used instead of more common QR
* intercept term is added implicitely if `intercept?` is set to `true` (by default)
* `:nbinomial` family requires `:nbinomial-theta` parameter
* Each family has its own default (canonical) link.
* For the `:binomial` families `ys` can be a sequence of pairs `[successes failures]`; the weights are multiplied by the number of trials.
* Gaussian AIC uses the observations with a positive weight (R returns infinity when a weight is zero).

The fit does not depend on the units of the terms nor on the scale of the weights (see [[lm]]).

Throws `ex-info` when an option is invalid (`:option`, `:value` and `:expected` in the data), when the response is outside of the domain of the family (proportions for binomial, non-negative values for poisson and negative binomial, positive values for gamma and inverse gaussian, finite numbers otherwise), when the terms are not finite numbers or the rows have different lengths, when the lengths of `ys`, `xss`, `:weights`, `:offset` and `:init-mu` differ, when weights are negative or not finite, when the model has no terms, when the model matrix is rank deficient (`:rank`, `:columns`, `:tol` and `:singular-values` in the data), when the variance of the mean is invalid or the IRLS equations are singular, which usually means a diverging fit, eg. perfect separation (`:iteration` in the data) and when a family with an estimated dispersion has no residual degrees of freedom.

Returned record implementes `IFn` protocol and contains:

* `:model` - set to `:glm`
* `:intercept?` - whether intercept term is included or not
* `:xtxinv` - (X^T X)^-1
* `:intercept` - intercept term value
* `:beta` - vector of model coefficients (without intercept)
* `:coefficients` - coefficient analysis, a list of maps containing `:estimate`, `:stderr`, `:t-value`, `:p-value` and `:confidence-interval`
* `:weights` - weights, `:weights` (working) and `:initial`
* `:residuals` - a map containing `:raw`, `:working`, `:pearsons` and `:deviance` residuals
* `:fitted` - fitted values for xss
* `:df` - degrees of freedom: `:residual`, `:null` and `:intercept`
* `:observations` - number of observations (rows)
* `:nobs` - number of observations with a positive weight, used in degrees of freedom and information criteria
* `:deviance` - deviances: `:residual` and `:null`
* `:dispersion` - default or calculated, used in a model
* `:dispersions` - `:pearson` and `:mean-deviance`
* `:family` - family used
* `:link` - link used
* `:link-fun` - link function, `g`
* `:mean-fun` - mean function, `g^-1`
* `:q` - (1-alpha/2) quantile of T or Normal distribution for residual degrees of freedom
* `:chi2` and `:p-value` - Chi-squared statistic and respective p-value
* `:ll` - a map containing log-likelihood and AIC/BIC (GLM and based on deviance, dev+2ED)
* `:analysis` - leverage, residual and influence analysis - a delay
* `:iters` and `:converged?` - number of iterations and convergence indicator (`true` when the change of the deviance is smaller than `:epsilon`, also at the last allowed iteration)
* `:decomposition` - decomposition used

Analysis, delay containing a map:

* `:residuals` - `:standardized` and `:studentized` residuals (pearsons and deviance)
* `:leverage` - `:hat`, `:sigmas` and leveraged `:coefficients` (leave-one-out)
* `:influence` - `:cooks-distance`, `:dffits`, `:dfbetas` and `:covratio`
* `:influential` - list of influential observations (ids) for influence measures
* `:correlation` - correlation matrix of estimated parameters
raw docstring

glm-nbinomialclj

(glm-nbinomial ys xss)
(glm-nbinomial ys
               xss
               {:keys [nbinomial-theta max-iters epsilon]
                :or {max-iters 25 epsilon 1.0E-8}
                :as params})

Fits theta for negative binomial glm in iterative process.

Returns fitted model with the keys :nbinomial-theta and :nbinomial-theta-stderr (the standard error of theta from the observed information, SE.theta of glm.nb in R).

Arguments and parameters are the same as for glm.

Additional parameters:

  • :nbinomial-theta - initial theta used as a starting point for optimization.
Fits theta for negative binomial glm in iterative process.

Returns fitted model with the keys `:nbinomial-theta` and `:nbinomial-theta-stderr` (the standard error of theta from the observed information, `SE.theta` of `glm.nb` in R).

Arguments and parameters are the same as for `glm`.

Additional parameters:

* `:nbinomial-theta` - initial theta used as a starting point for optimization.
raw docstring

Link functions of GLM, a map from a keyword to a Link record (see ->link) or to a function returning a Link from a map of parameters.

Records: :logit, :probit, :cauchit, :cloglog, :loglog, :identity, :log, :clog (log(1-mu)), :sqrt, :inversesq (1/mu^2) and :inverse.

Functions: :power (parameter :power-exponent, default 1.0, the exponent 0.0 is the :log link), :nbinomial (parameter :nbinomial-theta, default 1.0) and :distribution (parameter :distribution, the quantile function of a distribution as the link, default: standard normal).

Use family-with-link to get a family merged with a link.

Link functions of GLM, a map from a keyword to a `Link` record (see [[->link]]) or to a function returning a `Link` from a map of parameters.

Records: `:logit`, `:probit`, `:cauchit`, `:cloglog`, `:loglog`, `:identity`, `:log`, `:clog` (`log(1-mu)`), `:sqrt`, `:inversesq` (`1/mu^2`) and `:inverse`.

Functions: `:power` (parameter `:power-exponent`, default `1.0`, the exponent `0.0` is the `:log` link), `:nbinomial` (parameter `:nbinomial-theta`, default `1.0`) and `:distribution` (parameter `:distribution`, the quantile function of a distribution as the link, default: standard normal).

Use [[family-with-link]] to get a family merged with a link.
raw docstring

lmclj

(lm ys xss)
(lm ys
    xss
    {:keys [tol weights alpha intercept? offset transformer names decomposition
            augmentation augmentation-params]
     :or {tol 1.0E-8 alpha 0.05 intercept? true decomposition :cholesky}})

Fit a linear model using ordinary (OLS) or weighted (WLS) least squares.

Arguments:

  • ys - response vector
  • xss - terms of systematic component
  • optional parameters

Parameters:

  • :tol - tolerance of the matrix decomposition: the relative threshold of small singular values (rank deficiency of the model matrix) and the threshold of the QR/RRQR decomposition, default: 1.0e-8
  • :weights - optional weights for WLS, finite and non-negative; an observation with the weight 0 stays in :fitted and :residuals but it does not take part in the model (it is not counted in :nobs and degrees of freedom)
  • :offset - optional offset
  • :alpha - significance level, a number between 0 and 1, default: 0.05
  • :intercept? - should intercept term be included, default: true
  • :transformer - an optional function which will be used to transform systematic component xs before fitting and prediction
  • :names - sequence or string, used as name for coefficient when pretty-printing model, default 'X'
  • :decomposition - which matrix decomposition use to find solution, :cholesky (default), :rrqr (rank revealing) or :qr
  • :augmentation and augmentation-params - regularization by data augmentation
    • :ridge - adds ridge regresion penalty (intercept is not penalized), default parameters {:lambda 0.1}
    • :diffs - adds differences penalty, use with b-spline-transformation for smoothing, default parameters {:lambda 1.0 :order 2}

Notes:

  • SVD decomposition is used instead of more common QR
  • intercept term is added implicitely if intercept? is set to true (by default)
  • xss equal to :intercept fits a model with the intercept only: :f-statistic and :p-value are ##NaN and R-squared is 0.0
  • Two variants of AIC/BIC are calculated, one based on log-likelihood, second on RSS/n

The fit does not depend on the units of the terms nor on the scale of the weights: columns of the model matrix and weights are scaled before the rank is checked and the system is solved.

Throws ex-info when an option is invalid (:option, :value and :expected in the data), when the response is empty or not finite, when the terms are not finite numbers or the rows have different lengths, when the lengths of ys, xss, :weights and :offset differ, when weights are negative or not finite, when the model has no terms, when the model matrix is rank deficient (:rank, :columns, :tol and :singular-values in the data) and when there are no residual degrees of freedom (:observations, :parameters).

A constant response has no variance to explain: R-squared, adjusted R-squared, the F statistic and its p-value are ##NaN.

Returned record implementes IFn protocol and contains:

  • :model - :ols or :wls
  • :intercept? - whether intercept term is included or not
  • :xtxinv - (X^T X)^-1
  • :intercept - intercept term value
  • :beta - vector of model coefficients (without intercept)
  • :coefficients - coefficient analysis, a list of maps containing :estimate, :stderr, :t-value, :p-value and :confidence-interval
  • :weights - initial weights
  • :residuals - a map containing :raw and :weighted residuals, also :loocv
  • :fitted - fitted values for xss
  • :df - degrees of freedom: :residual, :model and :intercept
  • :observations - number of observations (rows)
  • :nobs - number of observations with a positive weight, used in degrees of freedom and information criteria
  • :r-squared and :adjusted-r-squared
  • :sigma and :sigma2 - deviance and variance
  • :msreg - regression mean squared
  • :rss, :regss, :tss - residual, regression and total sum of squares
  • :qt - (1-alpha/2) quantile of T distribution for residual degrees of freedom
  • :f-statistic and :p-value - F statistic and respective p-value
  • :ll - a map containing log-likelihood and AIC/BIC in two variants: based on log-likelihood and RSS
  • :analysis - leverage, residual and influence analysis - a delay
  • :decomposition - decomposition used
  • :augmentation - augmentation used
  • :cv - cross validation statistic
  • :effective-dimension - effective dimension of the model (sum of hat matrix diagonal)

Analysis, delay containing a map:

  • :residuals - :standardized and :studentized weighted residuals
  • :leverage - :hat, :sigmas and leveraged :coefficients (leave-one-out)
  • :influence - :cooks-distance, :dffits, :dfbetas and :covratio
  • :influential - list of influential observations (ids) for influence measures
  • :correlation - correlation matrix of estimated parameters
  • :normality - residuals normality tests: :skewness, :kurtosis, :durbin-watson (for raw and weighted), :jarque-berra and :omnibus (normality)
Fit a linear model using ordinary (OLS) or weighted (WLS) least squares.

Arguments:

* `ys` - response vector
* `xss` - terms of systematic component
* optional parameters

Parameters:

* `:tol` - tolerance of the matrix decomposition: the relative threshold of small singular values (rank deficiency of the model matrix) and the threshold of the QR/RRQR decomposition, default: `1.0e-8`
* `:weights` - optional weights for WLS, finite and non-negative; an observation with the weight 0 stays in `:fitted` and `:residuals` but it does not take part in the model (it is not counted in `:nobs` and degrees of freedom)
* `:offset` - optional offset
* `:alpha` - significance level, a number between 0 and 1, default: `0.05`
* `:intercept?` - should intercept term be included, default: `true`
* `:transformer` - an optional function which will be used to transform systematic component `xs` before fitting and prediction
* `:names` - sequence or string, used as name for coefficient when pretty-printing model, default `'X'`
* `:decomposition` - which matrix decomposition use to find solution, `:cholesky` (default), `:rrqr` (rank revealing) or `:qr`
* `:augmentation` and `augmentation-params` - regularization by data augmentation
    - `:ridge` - adds ridge regresion penalty (intercept is not penalized), default parameters `{:lambda 0.1}` 
    - `:diffs` - adds differences penalty, use with `b-spline-transformation` for smoothing, default parameters `{:lambda 1.0 :order 2}` 

Notes:

* SVD decomposition is used instead of more common QR
* intercept term is added implicitely if `intercept?` is set to `true` (by default)
* `xss` equal to `:intercept` fits a model with the intercept only: `:f-statistic` and `:p-value` are `##NaN` and R-squared is `0.0`
* Two variants of AIC/BIC are calculated, one based on log-likelihood, second on RSS/n

The fit does not depend on the units of the terms nor on the scale of the weights: columns of the model matrix and weights are scaled before the rank is checked and the system is solved.

Throws `ex-info` when an option is invalid (`:option`, `:value` and `:expected` in the data), when the response is empty or not finite, when the terms are not finite numbers or the rows have different lengths, when the lengths of `ys`, `xss`, `:weights` and `:offset` differ, when weights are negative or not finite, when the model has no terms, when the model matrix is rank deficient (`:rank`, `:columns`, `:tol` and `:singular-values` in the data) and when there are no residual degrees of freedom (`:observations`, `:parameters`).

A constant response has no variance to explain: R-squared, adjusted R-squared, the F statistic and its p-value are `##NaN`.

Returned record implementes `IFn` protocol and contains:

* `:model` - `:ols` or `:wls`
* `:intercept?` - whether intercept term is included or not
* `:xtxinv` - (X^T X)^-1
* `:intercept` - intercept term value
* `:beta` - vector of model coefficients (without intercept)
* `:coefficients` - coefficient analysis, a list of maps containing `:estimate`, `:stderr`, `:t-value`, `:p-value` and `:confidence-interval`
* `:weights` - initial weights
* `:residuals` - a map containing `:raw` and `:weighted` residuals, also `:loocv`
* `:fitted` - fitted values for xss
* `:df` - degrees of freedom: `:residual`, `:model` and `:intercept`
* `:observations` - number of observations (rows)
* `:nobs` - number of observations with a positive weight, used in degrees of freedom and information criteria
* `:r-squared` and `:adjusted-r-squared`
* `:sigma` and `:sigma2` - deviance and variance
* `:msreg` - regression mean squared
* `:rss`, `:regss`, `:tss` - residual, regression and total sum of squares
* `:qt` - (1-alpha/2) quantile of T distribution for residual degrees of freedom
* `:f-statistic` and `:p-value` - F statistic and respective p-value
* `:ll` - a map containing log-likelihood and AIC/BIC in two variants: based on log-likelihood and RSS
* `:analysis` - leverage, residual and influence analysis - a delay
* `:decomposition` - decomposition used
* `:augmentation` - augmentation used
* `:cv` - cross validation statistic
* `:effective-dimension` - effective dimension of the model (sum of hat matrix diagonal)

Analysis, delay containing a map:

* `:residuals` - `:standardized` and `:studentized` weighted residuals
* `:leverage` - `:hat`, `:sigmas` and leveraged `:coefficients` (leave-one-out)
* `:influence` - `:cooks-distance`, `:dffits`, `:dfbetas` and `:covratio`
* `:influential` - list of influential observations (ids) for influence measures
* `:correlation` - correlation matrix of estimated parameters
* `:normality` - residuals normality tests: `:skewness`, `:kurtosis`, `:durbin-watson` (for raw and weighted), `:jarque-berra` and `:omnibus` (normality)
raw docstring

pavaclj

(pava ys)
(pava ys order)
(pava ys ws order)

Isotonic regression, pool-adjacent-violators algorithm with up-and-down-blocks variant.

Isotonic regression minimizes the (weighted) L2 loss function with a constraint that result should be monotonic (ascending or descending).

Arguments:

  • ys - response variable data
  • ws - weights (optional)
  • order - :asc or :increasing (default), :desc or :decreasing, :non-decreasing and :non-increasing

Returns monotonic predicted values, an empty sequence for an empty ys.

Throws ex-info for a not finite response, for weights which are not finite and positive, for the weights of a different length than ys and for an unknown order.

Isotonic regression, pool-adjacent-violators algorithm with up-and-down-blocks variant.

Isotonic regression minimizes the (weighted) L2 loss function with a constraint that result should be monotonic (ascending or descending).

Arguments:

- `ys` - response variable data
- `ws` - weights (optional)
- `order` - `:asc` or `:increasing` (default), `:desc` or `:decreasing`, `:non-decreasing` and `:non-increasing`

Returns monotonic predicted values, an empty sequence for an empty `ys`.

Throws `ex-info` for a not finite response, for weights which are not finite and positive, for the weights of a different length than `ys` and for an unknown order.
raw docstring

polynomial-transformerclj

(polynomial-transformer xs degree)

Creates a transformer which expands a number into orthogonal polynomial terms, as poly(x, degree) in R.

Parameters:

  • xs - training values of the variable, the polynomials are orthogonal on them
  • degree - the degree of polynomial

Returns a function which accepts a one element data point [x] (a model :transformer) and returns a vector of degree terms. The terms of the training values are orthonormal (columns of poly(x, degree)), the same function can be evaluated outside the training values.

See also lm, glm, trigonometric-transformer, b-spline-transformer.

Creates a transformer which expands a number into orthogonal polynomial terms, as `poly(x, degree)` in R.

Parameters:

- `xs` - training values of the variable, the polynomials are orthogonal on them
- `degree` - the degree of polynomial

Returns a function which accepts a one element data point `[x]` (a model `:transformer`) and returns a vector of `degree` terms. The terms of the training values are orthonormal (columns of `poly(x, degree)`), the same function can be evaluated outside the training values.

See also [[lm]], [[glm]], [[trigonometric-transformer]], [[b-spline-transformer]].
raw docstring

predictclj

(predict model xs)
(predict model xs stderr?)

Predict from the given model and data point.

If stderr? is true, a map is returned with the keys :fit, :stderr (the standard error of the fit) and :confidence-interval (of the fit). For a GLM :fit is the mean, :link the linear predictor and the interval is calculated on the link scale and transformed back. For lm the map has also :prediction-interval, the interval of a new observation with the weight 1 (it is wider by the variance of the residual sigma2). If model is fitted with offset, first element of data point should contain provided offset.

Expected data point:

  • [x1,x2,...,xn] - when model was trained without offset
  • [offset,x1,x2,...,xn] - when offset was used for training
  • [] or nil - when model was trained with intercept only
  • [offset] - when model was trained with intercept and offset
Predict from the given model and data point.

If `stderr?` is true, a map is returned with the keys `:fit`, `:stderr` (the standard error of the fit) and `:confidence-interval` (of the fit). For a GLM `:fit` is the mean, `:link` the linear predictor and the interval is calculated on the link scale and transformed back. For `lm` the map has also `:prediction-interval`, the interval of a new observation with the weight 1 (it is wider by the variance of the residual `sigma2`).
If model is fitted with offset, first element of data point should contain provided offset.

Expected data point:

* `[x1,x2,...,xn]` - when model was trained without offset
* `[offset,x1,x2,...,xn]` - when offset was used for training
* `[]` or `nil` - when model was trained with intercept only
* `[offset]` - when model was trained with intercept and offset
raw docstring

quantile-residualsclj

(quantile-residuals {:keys [quantile-residuals-fun residuals dispersion]
                     :as model})

Quantile residuals of a GLM.

The residuals are standard normal when the model is correct. For discrete families (:binomial, :poisson, :nbinomial) they are randomized: a value is drawn in the interval of the cumulative distribution (with the global random generator, so the result differs between calls). For other families they are deterministic. A model without a family specific function gets standardized deviance residuals.

Parameters:

  • model - a model returned by glm

Returns a sequence of residuals.

See also analysis.

Quantile residuals of a GLM.

The residuals are standard normal when the model is correct. For discrete families (`:binomial`, `:poisson`, `:nbinomial`) they are randomized: a value is drawn in the interval of the cumulative distribution (with the global random generator, so the result differs between calls). For other families they are deterministic. A model without a family specific function gets standardized deviance residuals.

Parameters:

- `model` - a model returned by [[glm]]

Returns a sequence of residuals.

See also [[analysis]].
raw docstring

trigonometric-transformerclj

(trigonometric-transformer period degree)

Creates a transformer which expands a number into trigonometric (Fourier) terms.

Parameters:

  • period - the period of the variable
  • degree - the number of harmonics

Returns a function which accepts a one element data point [x] (a model :transformer) and returns a sequence of 2*degree terms: sin(2 pi k x / period) and cos(2 pi k x / period) for k=1..degree.

See also lm, glm, polynomial-transformer, b-spline-transformer.

Creates a transformer which expands a number into trigonometric (Fourier) terms.

Parameters:

- `period` - the period of the variable
- `degree` - the number of harmonics

Returns a function which accepts a one element data point `[x]` (a model `:transformer`) and returns a sequence of `2*degree` terms: `sin(2 pi k x / period)` and `cos(2 pi k x / period)` for `k=1..degree`.

See also [[lm]], [[glm]], [[polynomial-transformer]], [[b-spline-transformer]].
raw docstring

with-offsetclj

(with-offset xs offset?)

Splits a data point into an offset and terms.

Parameters:

  • xs - a data point: a sequence of terms, nil or [] for a model without terms
  • offset? - if true the first element of xs is the offset

Returns a pair [offset terms] where the terms are a vector. The offset is 0.0 when offset? is false.

Throws ex-info with the :offset when offset? is true and the first element is missing or is not a number.

See also predict.

Splits a data point into an offset and terms.

Parameters:

- `xs` - a data point: a sequence of terms, `nil` or `[]` for a model without terms
- `offset?` - if `true` the first element of `xs` is the offset

Returns a pair `[offset terms]` where the terms are a vector. The offset is `0.0` when `offset?` is `false`.

Throws `ex-info` with the `:offset` when `offset?` is `true` and the first element is missing or is not a number.

See also [[predict]].
raw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close