Package 'softcats'

Title: Regression on Predicted Categories with Calibrated Probabilities
Description: Estimates the association between an outcome and a latent categorical group from calibrated class probabilities instead of predicted labels. Assigning each observation its most likely category or thresholding the probabilities distorts regression estimates (for a binary group it typically attenuates them) and can give confidence intervals whose coverage is far below the nominal level. The estimator partials the controls out of the outcome and the probabilities with cross-fitted machine learning nuisance functions and solves a Neyman-orthogonal moment equation, with heteroskedasticity- or cluster-robust standard errors and optional weights. Further functions report how much information the probabilities carry beyond the controls, test conditional calibration and direct effects of classifier features on labelled data, recalibrate the probabilities on such data, bound the bias from calibration error, and compare the estimate with hard-label regressions, including the distortion and the implied coverage of the cross-fitted hard-label estimate. Methods follow Kurbucz (2026) <doi:10.48550/arXiv.2608.11784> for several categories and coarsening, Kurbucz (2026) <doi:10.48550/arXiv.2605.12780> for confidence thresholding, and the cross-fitting of Chernozhukov et al. (2018) <doi:10.1111/ectj.12097>.
Authors: Marcell T. Kurbucz [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-0121-6781>), Economic and Social Research Council [fnd] (Grant UKRI5718)
Maintainer: Marcell T. Kurbucz <[email protected]>
License: GPL (>= 3)
Version: 1.0.0
Built: 2026-12-04 20:09:27 UTC
Source: https://github.com/cran/softcats

Help Index


Check Conditional Calibration on Labelled Data

Description

soft_lm() requires the class probabilities to be calibrated given the controls, E[1{G=k}∣p,X]=pkE[1\{G = k\} \mid p, X] = p_k, which is stronger than the marginal calibration targeted by Platt scaling or isotonic regression. calibration_check() tests both on a sample where the group is observed.

Usage

calibration_check(
  probs,
  group,
  data = NULL,
  controls = NULL,
  degree = 3L,
  by = NULL,
  bins = 10L,
  weights = NULL,
  min_cell = 25L
)

## S3 method for class 'softcats_calibration'
print(x, digits = 3L, ...)

## S3 method for class 'softcats_calibration'
plot(x, ...)

Arguments

probs

[mandatory] (matrix, data.frame, character, formula or numeric) Class probabilities for the labelled observations, in any form accepted by soft_lm().

group

[mandatory] (vector or character) Observed category labels: a vector or a column name of data. Labels must match the category names of probs; for a numeric probability vector use 0/1 or FALSE/TRUE.

data

[optional] (data.frame) Data frame holding the variables referred to by name (default: NULL).

controls

[optional] (formula, data.frame or matrix) Controls as a one-sided formula evaluated in data, or as a data frame or matrix. NULL tests marginal calibration only (default: NULL).

degree

[optional] (integer) Degree of the polynomial in the logit of the probability (default: 3).

by

[optional] (vector, character or formula) Grouping variable for subgroup calibration gaps: a vector, a column name of data or a one-sided formula (default: NULL).

bins

[optional] (integer) Number of equal-width probability bins for the ECE and the reliability curves (default: 10).

weights

[optional] (numeric, character or formula) Observation weights. With non-integer weights the likelihood-ratio tests are approximate (default: NULL).

min_cell

[optional] (integer) Smallest subgroup or bin size used for the largest gap (default: 25).

x

[mandatory] (softcats_calibration) Result of calibration_check().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

Details

For each category (one category suffices for a binary group), the indicator of that category is regressed by logistic regression on a polynomial in the logit of its probability and on the controls, with the logit as an offset, so that the null model is perfect calibration. This extends the logistic recalibration model of Cox (1958).

  • The overall test compares the full model with the offset-only model. It detects any departure from calibration, marginal or conditional.

  • The conditional test compares the full model with the model without the controls. It detects miscalibration that depends on the controls and that marginal recalibration does not remove.

Both are likelihood-ratio tests; p-values are Holm-adjusted across categories. The function also reports the expected calibration error (ECE, equal-width bins), the Brier score and the largest calibration gap, within subgroups if by is given and within score bins otherwise. Raw gaps in small cells are dominated by sampling noise, so each gap is also reported net of a Bonferroni-corrected multiple of its standard error under perfect calibration. The largest net gap is returned as delta_hat, an estimate of the drift magnitude for drift_sensitivity(); it is zero when no cell departs from calibration by more than chance. When the tests reject, recalibrate() recalibrates the probabilities on the score and the controls together.

Value

An object of class softcats_calibration: a list with table (one row per tested category), delta_hat, delta_source, reliability (binned mean probabilities and frequencies) and nobs. delta_hat is NA when no cell has at least min_cell observations. The print and plot methods return x invisibly.

References

Cox, D. R. (1958). Two further applications of a model for binary regression. Biometrika, 45(3–4), 562–565. doi:10.1093/biomet/45.3-4.562

Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian Journal of Statistics, 6(2), 65–70.

Kurbucz, M. T. (2026). When to trust confidence thresholding: Calibration diagnostics for pseudo-labelled regression. arXiv preprint. doi:10.48550/arXiv.2605.12780

Examples

# Example: Probabilities miscalibrated given the first control
d <- sim_softcats(n = 3000, K = 2, miscalibration = 0.8, seed = 7)
lab <- d[d$labelled, ]
cc <- calibration_check(probs = c("prob_A", "prob_B"), group = "group",
                        data = lab, controls = ~ x1 + x2 + x3)
cc
plot(cc)

Compare with Regressions on Predicted Labels

Description

Replacing the class probabilities by a predicted label (the most likely class, or a confidence threshold) is a coarsening of the probabilities. compare_hard() reports, next to the soft_lm() estimate, two hard-label estimates on the same data, the distortion that coarsening causes, and the coverage that hard-label confidence intervals can be expected to have.

Usage

compare_hard(
  object,
  rule = c("argmax", "threshold"),
  threshold = 0.5,
  level = 0.95
)

## S3 method for class 'softcats_hard'
print(x, digits = 3L, ...)

Arguments

object

[mandatory] (softcats) A fit returned by soft_lm().

rule

[optional] (character) "argmax" assigns the most likely category; "threshold" (two categories only) assigns the non-reference category when its probability exceeds threshold (default: "argmax").

threshold

[optional] (numeric) Threshold for rule = "threshold" (default: 0.5).

level

[optional] (numeric) Confidence level for the intervals and the implied coverage (default: 0.95).

x

[mandatory] (softcats_hard) Result of compare_hard().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

Details

The two hard-label estimates are:

  • hard (OLS): least squares of the outcome on the label dummies and the controls entered linearly, with HC1 or, with clusters, CR1 standard errors as in exclusion_test(). This is the analysis most often run in practice.

  • hard (cross-fitted): the same estimator as soft_lm() with the label hh in place of the probabilities, using the same learner, folds and standard errors. Under the assumptions of soft_lm() it converges to AτA \tau, where A=E[ahah⊤]−1E[aha⊤]A = E[a_h a_h^\top]^{-1} E[a_h a^\top] is the coarsening (distortion) matrix, aha_h the label after partialling out the controls and aa the residualised probabilities. For two categories AA is the attenuation factor κ\kappa.

With more than two categories the distortion need not be uniform: the estimate for one category can also pick up the effects of the others, and the retention coefficients sj=vj⊤Avjs_j = v_j^\top A v_j along the eigenvectors vjv_j of E[aa⊤]E[a a^\top] can differ across directions and need not lie in [0,1][0, 1].

The implied coverage is an asymptotic approximation to the coverage of nominal Wald intervals for the cross-fitted hard-label estimate, Φ(z−ν)−Φ(−z−ν)\Phi(z - \nu) - \Phi(-z - \nu) with ν\nu the implied bias (A^−I)τ^(\hat A - I)\hat\tau divided by the hard-label standard error. It is an estimate: it uses the soft-label estimate in place of the true effects.

The regressions of the labels on the controls use the folds, the learner and the seed of the fit, so repeated calls on a fit with a seed give the same results.

Value

An object of class softcats_hard: a list with estimates (a data frame with columns method, term, estimate, std.error, conf.low, conf.high), the estimated distortion matrix distortion, the retention coefficients retention, and coverage, a data frame with the implied bias of the cross-fitted hard-label estimate and the implied coverage of its intervals. The print method returns x invisibly.

References

Kurbucz, M. T. (2026). Coarsening latent-class probabilities: Directional distortion and coverage loss. arXiv preprint. doi:10.48550/arXiv.2608.11784

Kurbucz, M. T. (2026). When to trust confidence thresholding: Calibration diagnostics for pseudo-labelled regression. arXiv preprint. doi:10.48550/arXiv.2605.12780

See Also

kappa_curve() for the attenuation across thresholds.

Examples

# Example: Most likely category with three categories
d <- sim_softcats(n = 2000, K = 3, seed = 5)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = ~ prob_A + prob_B + prob_C,
               data = d, learner = lrn_lm(degree = 3), seed = 5)
compare_hard(fit)

Sensitivity of the Estimate to Calibration Error

Description

Bounds the bias of the soft_lm() estimate when the probabilities are miscalibrated given the controls by at most δ\delta, and reports how much miscalibration the conclusion can tolerate.

Usage

drift_sensitivity(object, delta = NULL, level = 0.95)

## S3 method for class 'softcats_sensitivity'
print(x, digits = 3L, ...)

Arguments

object

[mandatory] (softcats) A fit returned by soft_lm().

delta

[optional] (numeric) Drift magnitude. If given, the bound and the intervals widened by the bound are added (default: NULL).

level

[optional] (numeric) Confidence level (default: 0.95).

x

[mandatory] (softcats_sensitivity) Result of drift_sensitivity().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

Details

Suppose that the probabilities are miscalibrated given the controls, E[1{G=k}∣p,X]=pk+ηk(p,X)E[1\{G = k\} \mid p, X] = p_k + \eta_k(p, X) with ∣ηk∣≤δ|\eta_k| \le \delta for every category. Then the estimator of soft_lm() converges to τ+M−1E[aη⊤]τ\tau + M^{-1} E[a \eta^\top] \tau with M=E[aa⊤]M = E[a a^\top], and the bias of coefficient kk is at most

δ ∥τ∥1 E∣(M−1a)k∣.\delta \, \|\tau\|_1 \, E\left|(M^{-1} a)_k\right| .

For two categories this is ∣τ∣ δ E∣a∣/V∗|\tau| \, \delta \, E|a| / V^*. drift_sensitivity() evaluates the factor multiplying δ\delta (the bias per unit of drift), using the estimate of τ\tau, and reports two robustness values in the spirit of Cinelli and Hazlett (2020):

  • rv: the drift δ\delta at which the bound equals the absolute estimate. For two categories the bias is proportional to τ\tau, so a drift below rv cannot reverse the sign of the effect;

  • rv_ci: the drift at which the bound equals the distance from zero to the end of the confidence interval nearest to zero, so that the interval widened by the bound includes zero.

The bound holds for every drift function within ±δ\pm\delta and is therefore conservative for any particular one. It is evaluated at the estimate of τ\tau, so the widened interval summarises sensitivity and is not a confidence interval with guaranteed coverage. A value of δ\delta can be taken from calibration_check() (delta_hat).

Value

A data frame of class softcats_sensitivity with columns term, estimate, std.error, bias_per_delta, rv, rv_ci and, if delta is given, bound, conf.low and conf.high (the confidence interval widened by the bound on each side). The print method returns x invisibly.

References

Kurbucz, M. T. (2026). Coarsening latent-class probabilities: Directional distortion and coverage loss. arXiv preprint. doi:10.48550/arXiv.2608.11784

Cinelli, C. and Hazlett, C. (2020). Making sense of sensitivity: Extending omitted variable bias. Journal of the Royal Statistical Society Series B, 82(1), 39–67. doi:10.1111/rssb.12348

Kurbucz, M. T. (2026). When to trust confidence thresholding: Calibration diagnostics for pseudo-labelled regression. arXiv preprint. doi:10.48550/arXiv.2605.12780

Examples

# Example: Robustness values and the bound at a drift of 0.02
d <- sim_softcats(n = 2000, K = 2, seed = 9)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = d$prob_B, data = d,
               learner = lrn_lm(degree = 3), seed = 9)
drift_sensitivity(fit)
drift_sensitivity(fit, delta = 0.02)

Test Whether Classifier Features Affect the Outcome Directly

Description

The classifier behind the probabilities must use features beyond the controls, and these features must affect the outcome only through the group. If an extra feature has its own effect on the outcome, the model of soft_lm() is misspecified and the estimate is biased. On labelled data this is testable: exclusion_test() regresses the outcome on the observed group, the controls and the extra features by least squares, and reports a robust Wald test that the coefficients of the extra features are zero.

Usage

exclusion_test(
  formula,
  group,
  extra,
  data,
  reference = NULL,
  weights = NULL,
  cluster = NULL
)

## S3 method for class 'softcats_exclusion'
print(x, digits = 3L, ...)

Arguments

formula

[mandatory] (formula) A formula outcome ~ controls, as in soft_lm().

group

[mandatory] (vector or character) Observed category labels: a vector or a column name of data.

extra

[mandatory] (formula or character) The classifier features that are not controls: a one-sided formula or a character vector of column names.

data

[mandatory] (data.frame) A data frame of labelled observations.

reference

[optional] (character) Reference level of group. NULL uses the first level (default: NULL).

weights

[optional] (numeric, character or formula) Observation weights (default: NULL).

cluster

[optional] (vector, character or formula) Cluster identifier for cluster-robust standard errors. Without clusters the standard errors are HC1, with the factor n/(n−p)n / (n - p) for pp regressors; with clusters they are CR1, with the factors (n−1)/(n−p)(n - 1) / (n - p) and G/(G−1)G / (G - 1) for GG clusters (default: NULL).

x

[mandatory] (softcats_exclusion) Result of exclusion_test().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

Details

The test is linear in the extra features and in the terms of formula. Add transformations to formula or extra to test other forms of dependence.

Value

An object of class softcats_exclusion with the Wald statistic, its degrees of freedom df, the p.value, the coefficients of the extra features and nobs. The print method returns x invisibly.

Examples

# Example: The classifier feature z affects the outcome directly
d <- sim_softcats(n = 3000, K = 2, direct_effect = 0.5, seed = 8)
lab <- d[d$labelled, ]
exclusion_test(y ~ x1 + x2 + x3, group = "group", extra = ~ z, data = lab)

Attenuation of Hard Labels Across Confidence Thresholds

Description

For a binary group, kappa_curve() evaluates the attenuation factor κ(t)=E[a~ta]/E[a~t2]\kappa(t) = E[\tilde a_t a] / E[\tilde a_t^2] of the label 1{p>t}1\{p > t\}, where pp is the probability of the non-reference category, a~t=1{p>t}−E[1{p>t}∣X]\tilde a_t = 1\{p > t\} - E[1\{p > t\} \mid X] and a=p−E[p∣X]a = p - E[p \mid X], on a grid of thresholds tt, together with the cross-fitted hard-label estimate at each threshold. Under the assumptions of soft_lm(), the hard estimate converges to κ(t) τ\kappa(t)\,\tau, so values of κ\kappa close to one mean that thresholding at tt loses little, and values well below one that it attenuates the coefficient. As in compare_hard(), the label regressions use the folds, the learner and the seed of the fit.

Usage

kappa_curve(object, thresholds = seq(0.5, 0.95, by = 0.05), level = 0.95)

## S3 method for class 'softcats_kappa'
print(x, digits = 3L, ...)

## S3 method for class 'softcats_kappa'
plot(x, ...)

Arguments

object

[mandatory] (softcats) A fit returned by soft_lm() with two categories.

thresholds

[optional] (numeric) Thresholds at which to evaluate the curve (default: seq(0.5, 0.95, by = 0.05)).

level

[optional] (numeric) Confidence level for the hard-label intervals (default: 0.95).

x

[mandatory] (softcats_kappa) Result of kappa_curve().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

Value

A data frame of class softcats_kappa with columns threshold, share_positive (weighted share labelled as the non-reference category), kappa, estimate_hard, std.error_hard, conf.low, conf.high and estimate_soft. Thresholds at which the label does not vary give NA. The print and plot methods return x invisibly.

References

Kurbucz, M. T. (2026). When to trust confidence thresholding: Calibration diagnostics for pseudo-labelled regression. arXiv preprint. doi:10.48550/arXiv.2605.12780

Examples

# Example: Attenuation at four thresholds for a binary group
d <- sim_softcats(n = 2000, K = 2, seed = 6)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = d$prob_B, data = d,
               learner = lrn_lm(degree = 3), seed = 6)
kc <- kappa_curve(fit, thresholds = c(0.5, 0.6, 0.7, 0.8))
kc
plot(kc)

Nuisance Learners

Description

Learners estimate the two nuisance functions of soft_lm(): the outcome regression m(X)=E[Y∣X]m(X) = E[Y \mid X] and the score regressions rk(X)=E[pk∣X]r_k(X) = E[p_k \mid X]. Each learner is an object of class softcats_learner that knows how to fit a regression of a numeric response on a data frame of controls and how to predict from that fit. All learners accept observation weights.

  • lrn_ranger() fits a random forest with ranger. It is the default because valid inference requires the nuisances to be estimated well, and both nuisances are typically non-linear.

  • lrn_lm() fits least squares on the controls, optionally with raw polynomial terms of the numeric controls. It is fast and deterministic, and appropriate when the nuisances are close to polynomial.

  • lrn_glmnet() fits a penalised regression with glmnet on a polynomial expansion of the controls, with the penalty chosen by cross-validation.

  • lrn_custom() wraps any user-supplied pair of fit and predict functions.

Usage

lrn_ranger(
  num.trees = 500L,
  mtry = NULL,
  min.node.size = NULL,
  num.threads = 1L,
  ...
)

lrn_lm(degree = 1L)

lrn_glmnet(alpha = 0, degree = 2L, nfolds = 5L, s = "lambda.min", ...)

lrn_custom(fit, predict, name = "custom")

## S3 method for class 'softcats_learner'
print(x, ...)

Arguments

num.trees

[optional] (integer) Number of trees (default: 500).

mtry

[optional] (integer) Number of controls considered at each split, capped at the number of controls. NULL uses the ranger default (default: NULL).

min.node.size

[optional] (integer) Minimum node size. NULL uses the ranger default (default: NULL).

num.threads

[optional] (integer) Number of threads used by ranger. One thread keeps results reproducible across machines (default: 1).

...

[optional] Further arguments passed to ranger::ranger() or glmnet::cv.glmnet(), except those set by the learner (x, y, the weights, seed and verbose). Use the seed argument of soft_lm() for reproducible forests.

degree

[optional] (integer) Highest power of each numeric control in the design matrix (default: 1 for lrn_lm() and 2 for lrn_glmnet()).

alpha

[optional] (numeric) Elastic-net mixing parameter: 0 is ridge, 1 is lasso (default: 0).

nfolds

[optional] (integer) Number of folds for the internal cross-validation of the penalty (default: 5).

s

[optional] (character or numeric) Value of the penalty used for prediction, as in glmnet::predict.cv.glmnet() (default: "lambda.min").

fit

[mandatory] (function) A function function(x, y, w) that returns a fitted model. x is a data frame of controls, y a numeric vector and w a vector of non-negative weights.

predict

[mandatory] (function) A function function(model, newdata) that returns a numeric vector of predictions.

name

[optional] (character) A short label shown in printed output (default: "custom").

x

[mandatory] (softcats_learner) A learner.

Details

The learner can be different for the two nuisances: pass learner = list(m = lrn_ranger(), r = lrn_lm(degree = 2)) to soft_lm().

In lrn_lm() and lrn_glmnet(), factor and character controls enter as treatment-coded dummies. A level that does not occur in a training fold is predicted as the first level.

Value

An object of class softcats_learner. The print method returns x invisibly.

Examples

# Example: Built-in learners
lrn_lm(degree = 2)
lrn_ranger(num.trees = 200)

# Example: Natural splines in the first control, linear in the others
lrn_spline <- lrn_custom(
  fit = function(x, y, w) {
    stats::lm(y ~ splines::ns(x1, df = 4) + x2 + x3,
              data = cbind(x, y = y), weights = w)
  },
  predict = function(model, newdata) {
    stats::predict(model, newdata = newdata)
  },
  name = "natural splines"
)
lrn_spline

Recalibrate the Class Probabilities on Labelled Data

Description

soft_lm() requires the class probabilities to be calibrated given the controls. When calibration_check() rejects this, a sample in which the group is observed can be used to recalibrate them. recalibrate() estimates the recalibration map E[1{G=k}∣p,X]E[1\{G = k\} \mid p, X] on the labelled sample, checks the recalibrated probabilities out of fold, and recomputes the estimate of the fit with them. It implements the recalibration experiment of Kurbucz (2026, arXiv:2608.11784), which also helps to tell which condition of the estimator fails.

Usage

recalibrate(
  object,
  labelled,
  group,
  probs = NULL,
  interactions = TRUE,
  folds = 5L,
  weights = NULL,
  level = 0.95,
  seed = NULL
)

## S3 method for class 'softcats_recalibration'
print(x, digits = 3L, ...)

## S3 method for class 'softcats_recalibration'
predict(object, newdata, probs = NULL, ...)

Arguments

object

[mandatory] (softcats or softcats_recalibration) A fit returned by soft_lm(); for predict(), the result of recalibrate().

labelled

[mandatory] (data.frame) Labelled observations with the controls of the fit, the probabilities and the observed group.

group

[mandatory] (vector or character) Observed category labels in labelled: a column name or a vector. Labels must match the category names of the fit; for a fit with a numeric probability vector use 0/1 or FALSE/TRUE.

probs

[optional] (matrix, data.frame, character, formula or numeric) Probabilities for the labelled observations, or for newdata in predict(), in any form accepted by soft_lm(). NULL reuses the probs specification of the fit, or of the labelled sample in predict(), which works when it was given as column names or a formula (default: NULL).

interactions

[optional] (logical) Whether the map includes the products of the log-odds and the controls (default: TRUE).

folds

[optional] (integer) Number of folds of the labelled sample for the out-of-fold check, at least two (default: 5).

weights

[optional] (numeric, character or formula) Weights of the labelled observations: a vector, a column name of labelled or a one-sided formula (default: NULL).

level

[optional] (numeric) Confidence level of the intervals (default: 0.95).

seed

[optional] (integer) Seed for the folds of the labelled sample. NULL uses the seed of the fit (default: NULL).

x

[mandatory] (softcats_recalibration) Result of recalibrate().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

newdata

[mandatory] (data.frame) Data with the controls and the probabilities to recalibrate.

Details

The map is a multinomial logistic regression of the observed group on the log-odds of the probabilities against the reference category, the controls and, with interactions = TRUE, the products of the log-odds and the controls. It is fitted by maximum likelihood with the log-odds as an offset, so that zero coefficients leave the probabilities unchanged. For two categories and without controls, the map is the logistic recalibration model of Cox (1958). Factor controls enter as dummies, and a level that does not occur in the labelled sample is treated as the first level. Columns that are collinear in the labelled sample are dropped. With few labelled observations, or when the miscalibration does not depend on the controls, interactions = FALSE gives a map with fewer parameters.

The function proceeds in three steps.

  1. The labelled sample is split into folds folds; two folds give the split-half design of Kurbucz (2026). Each fold is recalibrated by the map fitted on the other folds, and calibration_check() is run on the original and on these out-of-fold probabilities, so that the check does not reuse the observations that fitted the map. The maps of the folds are fitted on fewer observations than the final map, so the check is somewhat conservative.

  2. The map fitted on the whole labelled sample recalibrates the probabilities of the estimation sample.

  3. The estimate is recomputed with the recalibrated probabilities, using the folds, the outcome residuals and the learner of the fit. Only the regressions of the probabilities on the controls are refitted, and each starts from the state of the random number generator before the corresponding regression of the fit, so a stochastic learner such as lrn_ranger() draws the same random numbers. The two estimates thus differ only through the recalibration, and update() with the probabilities from predict() and the seed of the fit gives the same estimate.

Recalibration targets calibration given the controls, not the exclusion condition. If the classifier features affect the outcome directly, E[Y∣G,p,X]=μ(X)+τ⊤g+d(p,X)E[Y \mid G, p, X] = \mu(X) + \tau^\top g + d(p, X), the estimate converges to τ+M−1E[a d]\tau + M^{-1} E[a\,d] with M=E[aa⊤]M = E[a a^\top]. A map that moves the probabilities towards their conditional mean given the controls shrinks MM and can amplify this bias. The function therefore reports the eigenvalues of MM and the smallest canonical share before and after recalibration, and the print method notes when recalibration halves the smallest eigenvalue or more. Read together with calibration_check() and exclusion_test(), the change in the estimate indicates which condition fails.

The standard errors after recalibration treat the map as known. They do not include its estimation error and can therefore be too small, especially when the labelled sample is small compared with the estimation sample. The function warns when the labelled sample has fewer than ten observations per parameter of the map.

predict() applies the map fitted on the whole labelled sample to other data, for example to refit the model with update().

Value

recalibrate() returns an object of class softcats_recalibration: a list with estimates (a data frame with columns probabilities, term, estimate, std.error, conf.low and conf.high), calibration (the results of calibration_check() on the labelled sample, original and recalibrated out of fold), spectrum (the score spectra of the estimation sample, original and recalibrated, as returned by score_spectrum()), probs (the recalibrated probabilities of the estimation sample, reference category first), probs_labelled (the out-of-fold recalibrated probabilities of the complete labelled observations), map (the fitted map) and nobs_labelled. predict() returns a matrix of recalibrated probabilities with one row per row of newdata, NA where an input is missing, and the columns in the order of probs. The print method returns x invisibly.

References

Kurbucz, M. T. (2026). Coarsening latent-class probabilities: Directional distortion and coverage loss. arXiv preprint. doi:10.48550/arXiv.2608.11784

Cox, D. R. (1958). Two further applications of a model for binary regression. Biometrika, 45(3–4), 562–565. doi:10.1093/biomet/45.3-4.562

See Also

calibration_check() for the calibration tests, exclusion_test() for direct effects of the classifier features.

Examples

# Example: Probabilities miscalibrated given the first control
d <- sim_softcats(n = 3000, K = 2, miscalibration = 1.5,
                  labelled_share = 0.3, seed = 8)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = c("prob_A", "prob_B"), data = d,
               learner = lrn_lm(degree = 3), seed = 8)
rc <- recalibrate(fit, labelled = d[d$labelled, ], group = "group")
rc
attr(d, "tau")

# Example: Refit with the recalibrated probabilities of all observations
d[, c("rprob_A", "rprob_B")] <- predict(rc, d)
update(fit, probs = c("rprob_A", "rprob_B"))

Information in the Scores Beyond the Controls

Description

Identification in soft_lm() rests on the matrix E[aa⊤]E[a a^\top], the covariance of the class probabilities after the controls have been partialled out. score_spectrum() reports its eigenvalues and eigenvectors, and the canonical shares: the eigenvalues of E[aa⊤]E[a a^\top] relative to the covariance of the scores, that is, for each canonical direction, the fraction of score variance that the controls do not explain.

Usage

score_spectrum(object)

## S3 method for class 'softcats_spectrum'
print(x, digits = 3L, ...)

Arguments

object

[mandatory] (softcats) A fit returned by soft_lm().

x

[mandatory] (softcats_spectrum) Result of score_spectrum().

digits

[optional] (integer) Number of significant digits to print (default: 3).

...

[optional] Not used.

Details

A share near zero means that, in that direction, the scores are almost a function of the controls and the corresponding contrast is weakly identified. E[aa⊤]E[a a^\top] is then nearly singular, and the eigenvector of its smallest eigenvalue shows which categories the weak direction involves.

The shares are estimated from the cross-fitted residuals, which also contain the estimation error of E[p∣X]E[p \mid X]. When the controls explain little of the scores, a share can therefore exceed one slightly.

The canonical shares and the following thresholds are conventions of the package. As rules of thumb, a smallest share below 0.05 deserves attention and one below 0.01 means the estimate should not be used. For two categories the single eigenvalue is the residual score variance V∗V^*.

Value

An object of class softcats_spectrum: a list with values (eigenvalues of E[aa⊤]E[a a^\top], decreasing), vectors (eigenvectors, one column per direction), shares (canonical shares, decreasing), min_share, condition (ratio of the largest to the smallest eigenvalue), M and score_cov (covariance of the scores). The print method returns x invisibly.

References

Kurbucz, M. T. (2026). Coarsening latent-class probabilities: Directional distortion and coverage loss. arXiv preprint. doi:10.48550/arXiv.2608.11784

Examples

# Example: Canonical shares with three categories
d <- sim_softcats(n = 2000, K = 3, seed = 4)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = ~ prob_A + prob_B + prob_C,
               data = d, learner = lrn_lm(degree = 3), seed = 4)
score_spectrum(fit)

Simulate Data with Calibrated Class Probabilities

Description

Generates data that satisfy the assumptions of soft_lm(), with options to break them. It is used in the examples, the tests and the vignette.

Usage

sim_softcats(
  n = 2000L,
  K = 2L,
  tau = NULL,
  n_controls = 3L,
  concentration = 5,
  z_effect = 1.5,
  direct_effect = 0,
  miscalibration = 0,
  nonlinear = FALSE,
  labelled_share = 0.2,
  seed = NULL
)

Arguments

n

[optional] (integer) Number of observations (default: 2000).

K

[optional] (integer) Number of categories (default: 2).

tau

[optional] (numeric) Effects of categories 2 to K relative to category 1. NULL uses the first K - 1 values of c(1, -0.5, 0.75, -0.25, 0.5), recycled (default: NULL).

n_controls

[optional] (integer) Number of controls (default: 3).

concentration

[optional] (numeric) Dirichlet concentration; smaller values give more dispersed probabilities and more information beyond the controls (default: 5).

z_effect

[optional] (numeric) Effect of ZZ on the class probabilities (default: 1.5).

direct_effect

[optional] (numeric) Direct effect of ZZ on the outcome (default: 0).

miscalibration

[optional] (numeric) Strength of the conditional miscalibration of the returned probabilities (default: 0).

nonlinear

[optional] (logical) If TRUE, the outcome regression and the class probabilities are non-linear in the controls (default: FALSE).

labelled_share

[optional] (numeric) Share of observations flagged in column labelled, for use as a labelled sample (default: 0.2).

seed

[optional] (integer) Seed. The random number generator state of the session is restored afterwards (default: NULL).

Details

The controls XX are independent standard normal variables, and ZZ is a standard normal classifier feature that is not a control. Class probabilities are drawn as p∼Dirichlet(c π(X,Z))p \sim \mathrm{Dirichlet}(c\, \pi(X, Z)), where π\pi is a multinomial logit in XX and ZZ and cc is concentration. The group is drawn from pp, so the probabilities are calibrated given XX by construction. The outcome is Y=μ(X)+∑kτk1{G=k}+θZ+εY = \mu(X) + \sum_k \tau_k 1\{G = k\} + \theta Z + \varepsilon with ε∼N(0,1)\varepsilon \sim N(0, 1) and θ\theta = direct_effect.

With miscalibration different from zero, the returned probabilities are distorted: the logit of the second category is shifted by miscalibration * x1, so they are no longer calibrated given XX. With direct_effect different from zero, ZZ affects the outcome directly and the exclusion restriction fails.

Value

A data frame with the outcome y, controls x1, x2, ..., the classifier feature z, the latent group group (a factor with levels A, B, ...), probabilities prob_A, prob_B, ... and a logical labelled. Attributes: tau (the true effects), m_true (the true E[Y∣X]E[Y \mid X]) and r_true (the true E[p∣X]E[p \mid X] of the calibrated probabilities), computed by Gauss-Hermite quadrature over ZZ.

Examples

# Example: Three categories with the true effects
d <- sim_softcats(n = 500, K = 3, seed = 11)
head(d)
attr(d, "tau")

Diagnostic Report for a softcats Fit

Description

Collects the checks that decide whether a soft_lm() estimate can be trusted, and grades each as ok, warning or problem:

  1. Information beyond the controls (score_spectrum()): the smallest canonical share of score variance not explained by the controls.

  2. Direct effects of classifier features (exclusion_test()), if extra is given.

  3. Calibration given the controls (calibration_check()), if labelled data are given, graded by the overall test, which detects every departure from E[1{G=k}∣p,X]=pkE[1\{G = k\} \mid p, X] = p_k, whether or not it depends on the controls.

  4. Sensitivity to calibration drift (drift_sensitivity()), at the drift delta or, if it is not given, at the largest calibration gap beyond sampling noise found by the calibration check.

Usage

soft_check(
  object,
  labelled = NULL,
  group = NULL,
  probs = NULL,
  extra = NULL,
  by = NULL,
  delta = NULL
)

## S3 method for class 'softcats_check'
print(x, ...)

Arguments

object

[mandatory] (softcats) A fit returned by soft_lm().

labelled

[optional] (data.frame) Labelled observations (default: NULL).

group

[optional] (vector or character) Observed category labels in labelled: a column name or a vector. Required with labelled (default: NULL).

probs

[optional] (matrix, data.frame, character, formula or numeric) Probabilities for the labelled observations. NULL reuses the probs specification of the fit, which works when it was given as column names or a formula (default: NULL).

extra

[optional] (formula or character) Classifier features that are not controls, for the exclusion test: a one-sided formula or column names (default: NULL).

by

[optional] (vector, character or formula) Grouping variable for subgroup calibration gaps (default: NULL).

delta

[optional] (numeric) Drift magnitude for the sensitivity check (default: NULL).

x

[mandatory] (softcats_check) Result of soft_check().

...

[optional] Not used.

Details

The first check needs only the fit. The others need a labelled sample in which the group is observed, with the outcome, the controls and the probabilities. These checks are unweighted and use standard errors that are not cluster-robust; call exclusion_test() and calibration_check() directly to use weights or clusters. The drift check is skipped when delta is not given and the calibration check finds no cell large enough to estimate the gap. When calibration fails, recalibrate() recalibrates the probabilities on the labelled sample.

The grading thresholds are rules of thumb. Information: problem below a share of 0.01, warning below 0.05. Exclusion and calibration: problem below p = 0.001, warning below p = 0.05. Drift: problem if delta reaches the robustness value rv, at which the bias bound equals the estimate, and warning if it reaches rv_ci, at which the widened interval includes zero.

Value

An object of class softcats_check: a list with summary (a data frame with columns check, status and detail) and the component results spectrum, calibration, exclusion and sensitivity (NULL when not run). The print method returns x invisibly.

Examples

# Example: All checks on the labelled subsample
d <- sim_softcats(n = 3000, K = 2, seed = 10)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = c("prob_A", "prob_B"), data = d,
               learner = lrn_lm(degree = 3), seed = 10)
soft_check(fit, labelled = d[d$labelled, ], group = "group", extra = ~ z)

Regression on Predicted Categories with Calibrated Class Probabilities

Description

Estimates the partial association between a latent categorical group and an outcome when the group is not observed, but a classifier supplies calibrated class probabilities for every observation. It replaces the common practice of regressing the outcome on the predicted label (argmax or a confidence threshold), which distorts the estimate (for a binary group it typically attenuates it) and can give confidence intervals whose coverage is far below the nominal level.

Usage

soft_lm(
  formula,
  probs,
  data,
  reference = 1L,
  learner = lrn_ranger(),
  folds = 5L,
  n_rep = 1L,
  weights = NULL,
  cluster = NULL,
  seed = NULL
)

Arguments

formula

[mandatory] (formula) A two-sided formula outcome ~ controls. The right-hand side lists the controls; their functional form is left to the learner. Matrix-valued terms such as poly(x, 2) enter as one control per column. Use outcome ~ 1 for no controls.

probs

[mandatory] (matrix, data.frame, character, formula or numeric) Class probabilities, one column per category and rows summing to one: a matrix or data frame, a character vector of column names in data, a one-sided formula such as ~ p_a + p_b + p_c, or, for a binary group, a numeric vector of probabilities of the second category, in which case the categories are named "0" and "1". A prefix shared by all column names (such as prob_ or .pred_) is removed to obtain category labels.

data

[mandatory] (data.frame) A data frame containing the outcome and the controls.

reference

[optional] (character or integer) The reference category, by name or position (default: 1, the first column of probs).

learner

[optional] (softcats_learner or list) A learner (see learners) used for both nuisances, or a list list(m = , r = ) with separate learners for the outcome regression and the score regressions (default: lrn_ranger()).

folds

[optional] (integer) Number of cross-fitting folds, at least two (default: 5).

n_rep

[optional] (integer) Number of repetitions of cross-fitting with new fold splits (default: 1).

weights

[optional] (numeric, character or formula) Non-negative observation weights, for example survey weights: a numeric vector, a column name of data or a one-sided formula (default: NULL).

cluster

[optional] (vector, character or formula) Cluster identifier for cluster-robust standard errors: a vector, a column name of data or a one-sided formula (default: NULL).

seed

[optional] (integer) Seed for the fold splits and stochastic learners. The random number generator state of the session is restored afterwards (default: NULL).

Value

An object of class softcats, with methods for print(), summary(), coef(), vcov(), confint(), nobs(), residuals(), fitted(), formula(), plot(), generics::tidy() and generics::glance(). It works with update(), broom, modelsummary and lmtest::coeftest().

Model

For a latent group GG with categories 1,…,K1, \dots, K (category 1 is the reference) and class probabilities, or scores, pp, the target is τ\tau in the partially linear model

E[Y∣G,X]=μ(X)+∑k=2Kτk1{G=k},E[Y \mid G, X] = \mu(X) + \sum_{k = 2}^{K} \tau_k 1\{G = k\},

where μ\mu is unrestricted. The probabilities must be calibrated conditionally on the controls, E[1{G=k}∣p,X]=pkE[1\{G = k\} \mid p, X] = p_k. Under this condition and the exclusion condition E[Y∣G,p,X]=E[Y∣G,X]E[Y \mid G, p, X] = E[Y \mid G, X] (see Requirements), with a=p−E[p∣X]a = p - E[p \mid X] (reference column removed) and m(X)=E[Y∣X]m(X) = E[Y \mid X],

E[a (Y−m(X))]=E[aa⊤] τ,E[a\,(Y - m(X))] = E[a a^\top]\,\tau ,

so τ\tau is identified from the unlabelled data whenever the scores vary beyond what the controls explain, that is, whenever E[aa⊤]E[a a^\top] is non-singular. For two categories, E[aa⊤]E[a a^\top] is the residual score variance V∗=E[Var(p∣X)]V^* = E[\mathrm{Var}(p \mid X)].

Estimation and inference

The nuisances m(X)m(X) and E[pk∣X]E[p_k \mid X] are estimated by cross-fitting with the chosen learner. The estimator solves the sample version of the moment equation above, whose estimating function is Neyman-orthogonal in both nuisances. This is the partialling-out estimator of Robinson (1988), with cross-fitted nuisance estimates and the probabilities as regressors. Without weights or clusters, the estimate is asymptotically normal with variance M−1E[u2aa⊤]M−1/nM^{-1} E[u^2 a a^\top] M^{-1} / n, M=E[aa⊤]M = E[a a^\top] and u=Y−m(X)−a⊤τu = Y - m(X) - a^\top\tau, when both nuisance estimates are consistent, their errors satisfy ∥m^−m∥2∥r^−r∥2+∥r^−r∥22=oP(n−1/2)\|\hat m - m\|_2 \|\hat r - r\|_2 + \|\hat r - r\|_2^2 = o_P(n^{-1/2}) and further regularity conditions hold (Chernozhukov et al. 2018; Kurbucz 2026, arXiv:2608.11784). Standard errors are sandwich estimates, heteroskedasticity-robust (HC0) by default and cluster-robust (CR1, with the factor G/(G−1)G / (G - 1) for GG clusters) when cluster is supplied. With cluster, folds are formed from whole clusters. With n_rep > 1, cross-fitting is repeated with new fold splits; estimates are averaged and the variance includes the spread across splits. With random forests, several splits (for example n_rep = 5) are advisable, because in simulations the variance from a single split understates the variability of the estimate.

Requirements

The classifier must use information beyond the controls (classifier features that are not in formula), otherwise the scores are a function of the controls and the effect is not identified; score_spectrum() reports how much information is left. These extra features must not affect the outcome directly; exclusion_test() checks this on labelled data. Conditional calibration can be checked with calibration_check() and repaired on labelled data with recalibrate(), and drift_sensitivity() bounds the bias from calibration error. The estimand is a partial association, not a causal effect.

References

Kurbucz, M. T. (2026). Coarsening latent-class probabilities: Directional distortion and coverage loss. arXiv preprint. doi:10.48550/arXiv.2608.11784

Kurbucz, M. T. (2026). When to trust confidence thresholding: Calibration diagnostics for pseudo-labelled regression. arXiv preprint. doi:10.48550/arXiv.2605.12780

Chernozhukov, V., Chetverikov, D., Demirer, M., Duflo, E., Hansen, C., Newey, W. and Robins, J. (2018). Double/debiased machine learning for treatment and structural parameters. The Econometrics Journal, 21(1), C1–C68. doi:10.1111/ectj.12097

Robinson, P. M. (1988). Root-N-consistent semiparametric regression. Econometrica, 56(4), 931–954. doi:10.2307/1912705

See Also

compare_hard() for the cost of using predicted labels instead, soft_check() for a one-page diagnostic report.

Examples

# Example: Three categories, probabilities given as column names
d <- sim_softcats(n = 2000, K = 3, seed = 1)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = c("prob_A", "prob_B", "prob_C"),
               data = d, learner = lrn_lm(degree = 3), seed = 1)
fit
summary(fit)
confint(fit)
attr(d, "tau")

# Example: Binary group, probability of the second category as a vector
b <- sim_softcats(n = 2000, K = 2, seed = 2)
soft_lm(y ~ x1 + x2 + x3, probs = b$prob_B, data = b,
        learner = lrn_lm(degree = 3), seed = 2)

Methods for softcats Fits

Description

Standard methods for objects returned by soft_lm(). Inference is based on the normal approximation, so summary() reports z statistics and confint() normal-theory intervals.

Usage

## S3 method for class 'softcats'
coef(object, ...)

## S3 method for class 'softcats'
vcov(object, ...)

## S3 method for class 'softcats'
nobs(object, ...)

## S3 method for class 'softcats'
formula(x, ...)

## S3 method for class 'softcats'
residuals(object, ...)

## S3 method for class 'softcats'
fitted(object, ...)

## S3 method for class 'softcats'
confint(object, parm, level = 0.95, ...)

## S3 method for class 'softcats'
print(x, digits = max(3L, getOption("digits") - 3L), ...)

## S3 method for class 'softcats'
summary(object, ...)

## S3 method for class 'summary.softcats'
print(x, digits = max(3L, getOption("digits") - 3L), ...)

## S3 method for class 'softcats'
tidy(x, conf.int = FALSE, conf.level = 0.95, ...)

## S3 method for class 'softcats'
glance(x, ...)

## S3 method for class 'softcats'
plot(x, which = c("coef", "spectrum"), level = 0.95, ...)

Arguments

object, x

[mandatory] (softcats) A fit returned by soft_lm(); for print.summary.softcats(), an object of class summary.softcats.

...

[optional] Not used.

parm

[optional] (character or integer) Coefficients to report, by name or position (default: all coefficients).

level

[optional] (numeric) Confidence level (default: 0.95).

digits

[optional] (integer) Number of significant digits to print (default: max(3, getOption("digits") - 3)).

conf.int

[optional] (logical) Whether tidy() adds confidence limits (default: FALSE).

conf.level

[optional] (numeric) Confidence level for tidy() (default: 0.95).

which

[optional] (character) For plot(): "coef" draws the estimates with confidence intervals, "spectrum" the share of score variation that the controls do not explain, by direction (default: "coef").

Value

coef() a named vector; vcov() a matrix; confint() a matrix with one row per coefficient; nobs() an integer; formula() the model formula; residuals() and fitted() numeric vectors; summary() an object of class summary.softcats; tidy() and glance() data frames. The print and plot methods return x invisibly.

Examples

# Example: Standard methods on a fit with three categories
d <- sim_softcats(n = 1500, K = 3, seed = 3)
fit <- soft_lm(y ~ x1 + x2 + x3, probs = ~ prob_A + prob_B + prob_C,
               data = d, learner = lrn_lm(degree = 3), seed = 3)
coef(fit)
vcov(fit)
confint(fit, level = 0.9)
tidy(fit, conf.int = TRUE)
glance(fit)
plot(fit)
plot(fit, which = "spectrum")