| Type: | Package |
| Title: | Regression on Predicted Categories with Calibrated Probabilities |
| Version: | 1.0.0 |
| 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>. |
| License: | GPL (≥ 3) |
| URL: | https://github.com/mtkurbucz/softcats, https://mtkurbucz.github.io/softcats/ |
| BugReports: | https://github.com/mtkurbucz/softcats/issues |
| Encoding: | UTF-8 |
| Language: | en-GB |
| Depends: | R (≥ 4.1.0) |
| Imports: | generics (≥ 0.1.0), graphics, ranger (≥ 0.12.0), stats |
| Suggests: | broom, glmnet, knitr, lmtest, modelsummary, rmarkdown, splines, testthat (≥ 3.0.0) |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| RoxygenNote: | 7.3.2 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-12 11:39:48 UTC; mtkurbucz |
| Author: | Marcell T. Kurbucz
|
| Maintainer: | Marcell T. Kurbucz <m.kurbucz@ucl.ac.uk> |
| Repository: | CRAN |
| Date/Publication: | 2026-12-04 16:30:02 UTC |
softcats: Regression on Predicted Categories with Calibrated Probabilities
Description
Many studies need the association between an outcome and a group that is not observed directly, such as an ethnic group inferred from names and places, a cell type assigned by an annotation model, or a household type predicted from administrative records. A common practice is to assign each observation its most likely category, or the category whose probability exceeds a confidence threshold, and to use these labels in a regression. This distorts the estimate (for a binary group it typically attenuates it) and can give confidence intervals whose coverage is far below the nominal level.
Details
softcats keeps the categories soft. soft_lm()
estimates the effect from the calibrated class probabilities themselves,
with cross-fitted nuisance functions, a Neyman-orthogonal score and robust
(optionally weighted and clustered) standard errors. Diagnostics report
whether the estimate can be trusted:
-
score_spectrum(): how much information the probabilities carry beyond the controls; -
exclusion_test(): whether the classifier features affect the outcome directly; -
calibration_check(): whether the probabilities are calibrated given the controls; -
recalibrate(): recalibration of the probabilities on labelled data, checked out of fold; -
drift_sensitivity(): how much calibration error the conclusion can tolerate; -
compare_hard()andkappa_curve(): what predicted labels would have given instead; -
soft_check(): all of the above in one report.
Fits work with the standard model methods of R and with broom,
modelsummary and lmtest::coeftest().
Author(s)
Maintainer: Marcell T. Kurbucz m.kurbucz@ucl.ac.uk (ORCID) [copyright holder]
Other contributors:
Economic and Social Research Council (Grant UKRI5718) [funder]
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
Useful links:
Report bugs at https://github.com/mtkurbucz/softcats/issues
Binned Probabilities and Frequencies
Description
Computes the weighted mean probability and observed frequency within equal-width probability bins.
Usage
binned(p, y, w, bins)
Arguments
p |
[mandatory] (numeric) Probability of the category. |
y |
[mandatory] (numeric) 0/1 indicator of the category. |
w |
[mandatory] (numeric) Observation weights. |
bins |
[mandatory] (integer) Number of equal-width bins. |
Value
A data frame with columns bin, probability,
frequency, weight and n.
Check Conditional Calibration on Labelled Data
Description
soft_lm() requires the class probabilities to be calibrated
given the controls, E[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 |
group |
[mandatory] (vector or character) Observed category labels: a
vector or a column name of |
data |
[optional] (data.frame) Data frame holding the variables
referred to by name (default: |
controls |
[optional] (formula, data.frame or matrix) Controls as a
one-sided formula evaluated in |
degree |
[optional] (integer) Degree of the polynomial in the logit of
the probability (default: |
by |
[optional] (vector, character or formula) Grouping variable for
subgroup calibration gaps: a vector, a column name of |
bins |
[optional] (integer) Number of equal-width probability bins
for the ECE and the reliability curves (default: |
weights |
[optional] (numeric, character or formula) Observation
weights. With non-integer weights the likelihood-ratio tests are
approximate (default: |
min_cell |
[optional] (integer) Smallest subgroup or bin size used for
the largest gap (default: |
x |
[mandatory] (softcats_calibration) Result of
|
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[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)
One Row of the Diagnostic Report
Description
Creates a one-row data frame for the summary of
soft_check().
Usage
check_row(check, status, detail)
Arguments
check |
[mandatory] (character) Name of the check. |
status |
[mandatory] (character) |
detail |
[mandatory] (character) Short description of the result. |
Value
A data frame with one row.
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
|
rule |
[optional] (character) |
threshold |
[optional] (numeric) Threshold for
|
level |
[optional] (numeric) Confidence level for the intervals and
the implied coverage (default: |
x |
[mandatory] (softcats_hard) Result of |
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[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 inexclusion_test(). This is the analysis most often run in practice. -
hard (cross-fitted): the same estimator assoft_lm()with the labelhin place of the probabilities, using the same learner, folds and standard errors. Under the assumptions ofsoft_lm()it converges toA \tau, whereA = E[a_h a_h^\top]^{-1} E[a_h a^\top]is the coarsening (distortion) matrix,a_hthe label after partialling out the controls andathe residualised probabilities. For two categoriesAis 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 s_j = v_j^\top A v_j along the
eigenvectors v_j of E[a a^\top] can differ across
directions and need not lie in [0, 1].
The implied coverage is an asymptotic approximation to the coverage of
nominal Wald intervals for the cross-fitted hard-label estimate,
\Phi(z - \nu) - \Phi(-z - \nu) with \nu the implied bias
(\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)
Eigen-Decomposition of the Score Information
Description
Computes the eigenvalues and eigenvectors of M = E[a a^\top] and
the canonical shares, the eigenvalues of C^{-1/2} M C^{-1/2} with
C the covariance of the scores.
Usage
compute_spectrum(M, C)
Arguments
M |
[mandatory] (matrix) Normalised Jacobian |
C |
[mandatory] (matrix) Weighted covariance of the scores. |
Value
A list with values, vectors, shares,
min_share, condition, M and score_cov.
Extract the Outcome and the Controls
Description
Evaluates the model formula and returns the outcome and the controls as a
data frame, possibly with zero columns. Matrix-valued terms such as
poly() or splines::ns() are split into one column per basis
function.
Usage
controls_frame(formula, data)
Arguments
formula |
[mandatory] (formula) Model formula. |
data |
[mandatory] (data.frame) Data. |
Value
A list with the outcome y, the controls x and the
terms object.
Cross-Fit the Nuisance Functions
Description
Estimates the outcome regression m(X) and the score regressions
r_k(X) out of fold.
Usage
crossfit_nuisances(y, Pq, x, w, fold_id, learners)
Arguments
y |
[mandatory] (numeric) Outcome. |
Pq |
[mandatory] (matrix) Class probabilities without the reference column. |
x |
[mandatory] (data.frame) Controls. |
w |
[mandatory] (numeric) Observation weights. |
fold_id |
[mandatory] (integer) Fold index of each observation. |
learners |
[mandatory] (list) Learners |
Value
A list with the out-of-fold predictions m_hat (vector) and
r_hat (matrix), and r_states, the state of the random
number generator before each score regression (by fold, then column).
Cross-Fitted Estimator with Other Scores
Description
Computes the cross-fitted estimate with other scores in place of the
class probabilities, such as hard labels or recalibrated probabilities,
using the folds, the outcome residuals and the seed stored in the fit.
With replay = TRUE, each regression of a score on the controls
starts from the state of the random number generator before the
corresponding regression of the fit, so that a stochastic learner draws
the same random numbers and scores equal to the probabilities reproduce
the estimate of the fit.
Usage
crossfit_scores(object, H, what = "hard labels", replay = FALSE)
Arguments
object |
[mandatory] (softcats) A fit returned by
|
H |
[mandatory] (matrix) Scores without the reference category. |
what |
[optional] (character) Name of the scores in error messages
(default: |
replay |
[optional] (logical) Whether to replay the random number
states of the fit; requires one score per probability column (default:
|
Value
A list with the estimate tau, its covariance vcov,
the distortion matrix A relative to the residualised
probabilities of the fit and the normalised Jacobian M, averaged
over splits.
Design Matrix for Linear Learners
Description
Builds treatment-coded dummies for factor controls and raw powers up to
degree for numeric controls. Rows are never dropped: a level not
seen in the training data gets zero dummies (the first level), and a
missing value gives missing dummies.
Usage
design_matrix(x, degree = 1L, xlev = NULL)
Arguments
x |
[mandatory] (data.frame) Controls. |
degree |
[optional] (integer) Highest power of each numeric control
(default: |
xlev |
[optional] (list) Factor levels from the training data
(default: |
Value
A numeric matrix without an intercept column and with one row per
row of x.
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
|
delta |
[optional] (numeric) Drift magnitude. If given, the bound and
the intervals widened by the bound are added (default: |
level |
[optional] (numeric) Confidence level (default:
|
x |
[mandatory] (softcats_sensitivity) Result of
|
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[optional] Not used. |
Details
Suppose that the probabilities are miscalibrated given the
controls, E[1\{G = k\} \mid p, X] = p_k + \eta_k(p, X) with
|\eta_k| \le \delta for every category. Then the estimator of
soft_lm() converges to
\tau + M^{-1} E[a \eta^\top] \tau with M = E[a a^\top], and
the bias of coefficient k is at most
\delta \, \|\tau\|_1 \, E\left|(M^{-1} a)_k\right| .
For two categories this is |\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\deltaat which the bound equals the absolute estimate. For two categories the bias is proportional to\tau, so a drift belowrvcannot 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)
Expected Calibration Error
Description
Computes the weighted mean absolute gap between the binned frequencies and probabilities.
Usage
ece(y, p, w, bins)
Arguments
y |
[mandatory] (numeric) 0/1 indicator of the category. |
p |
[mandatory] (numeric) Probability of the category. |
w |
[mandatory] (numeric) Observation weights. |
bins |
[mandatory] (integer) Number of equal-width bins. |
Value
A single number.
Solve the Orthogonal Moment Equation
Description
Solves \sum_i w_i a_i (R_i - a_i^\top \tau) = 0 for \tau,
where a = p - \hat r(X) and R = Y - \hat m(X), and computes the
sandwich covariance.
Usage
estimate_moment(y, Pq, w, m_hat, r_hat, cluster = NULL)
Arguments
y |
[mandatory] (numeric) Outcome. |
Pq |
[mandatory] (matrix) Class probabilities without the reference column. |
w |
[mandatory] (numeric) Observation weights. |
m_hat |
[mandatory] (numeric) Predictions of |
r_hat |
[mandatory] (matrix) Predictions of |
cluster |
[optional] (vector) Cluster identifier (default:
|
Value
A list with the estimate tau, its covariance vcov,
the residualised scores a and outcome R, the nuisance
predictions and the normalised Jacobian M.
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 |
group |
[mandatory] (vector or character) Observed category labels:
a vector or a column name of |
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 |
weights |
[optional] (numeric, character or formula) Observation
weights (default: |
cluster |
[optional] (vector, character or formula) Cluster
identifier for cluster-robust standard errors. Without clusters the
standard errors are HC1, with the factor |
x |
[mandatory] (softcats_exclusion) Result of
|
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[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)
Levels of Factor Controls
Description
Records the levels of the non-numeric controls.
Usage
factor_levels(x)
Arguments
x |
[mandatory] (data.frame) Controls. |
Value
A named list of character vectors.
Fit a Multinomial Logit by Newton-Raphson
Description
Maximises the weighted log-likelihood of a multinomial logit with an
offset, starting from zero coefficients, with step halving. Columns of
Z that are collinear in the data get zero coefficients.
Usage
fit_multinom(Z, Y, offset, w, maxit = 100L, tol = 1e-10)
Arguments
Z |
[mandatory] (matrix) Regressors. |
Y |
[mandatory] (matrix) 0/1 indicators of the categories, reference first. |
offset |
[mandatory] (matrix) Offset, one column per non-reference category. |
w |
[mandatory] (numeric) Observation weights. |
maxit |
[optional] (integer) Maximum number of iterations (default:
|
tol |
[optional] (numeric) Relative change of the log-likelihood at
which the iterations stop (default: |
Value
A list with the coefficients coefficients (one column per
non-reference category), the log-likelihood loglik, the
indicator converged and the number of iterations
iterations.
Fit a Learner and Predict Held-Out Rows
Description
Fits the learner on the training rows and predicts the test rows. Without controls, the prediction is the weighted mean of the training response.
Usage
fit_predict(learner, x, y, w, train, test)
Arguments
learner |
[mandatory] (softcats_learner) Learner. |
x |
[mandatory] (data.frame) Controls. |
y |
[mandatory] (numeric) Response. |
w |
[mandatory] (numeric) Observation weights. |
train |
[mandatory] (integer) Indices of the training rows. |
test |
[mandatory] (integer) Indices of the test rows. |
Value
A numeric vector of predictions for the test rows.
Format p-Values
Description
Formats p-values with three significant digits and a floor of
1e-4.
Usage
format_p(p)
Arguments
p |
[mandatory] (numeric) p-values. |
Value
A character vector.
Gauss-Hermite Quadrature for the Standard Normal
Description
Computes nodes and weights for E[f(Z)], Z \sim N(0, 1), with
the Golub-Welsch algorithm.
Usage
gauss_hermite(k)
Arguments
k |
[mandatory] (integer) Number of nodes. |
Value
A list with nodes and weights.
Grade a p-Value
Description
Grades a p-value as "problem" below 0.001, "warning" below
0.05 or if it is not finite, and "ok" otherwise.
Usage
grade_p(p)
Arguments
p |
[mandatory] (numeric) A p-value. |
Value
A character string.
Least Squares on Predicted Labels
Description
Regresses the outcome on the label dummies and the controls entered linearly, with robust (HC1) or cluster-robust (CR1) standard errors.
Usage
hard_ols(object, H)
Arguments
object |
[mandatory] (softcats) A fit returned by
|
H |
[mandatory] (matrix) Label dummies without the reference category. |
Value
A list with the label coefficients tau and their
covariance vcov.
Attenuation of Hard Labels Across Confidence Thresholds
Description
For a binary group, kappa_curve() evaluates the attenuation factor
\kappa(t) = E[\tilde a_t a] / E[\tilde a_t^2] of the label
1\{p > t\}, where p is the probability of the non-reference
category, \tilde a_t = 1\{p > t\} - E[1\{p > t\} \mid X] and
a = p - E[p \mid X], on a grid of thresholds t, together with the
cross-fitted hard-label estimate at each threshold. Under the assumptions
of soft_lm(), the hard estimate converges to
\kappa(t)\,\tau, so values of \kappa close to one mean that
thresholding at t 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
|
thresholds |
[optional] (numeric) Thresholds at which to evaluate the
curve (default: |
level |
[optional] (numeric) Confidence level for the hard-label
intervals (default: |
x |
[mandatory] (softcats_kappa) Result of |
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[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)
Label of the Learners
Description
Describes the learners of a fit for printed output.
Usage
learner_label(object)
Arguments
object |
[mandatory] (softcats) A fit returned by
|
Value
A character string.
Nuisance Learners
Description
Learners estimate the two nuisance functions of soft_lm():
the outcome regression m(X) = E[Y \mid X] and the score regressions
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:
|
mtry |
[optional] (integer) Number of controls considered at each
split, capped at the number of controls. |
min.node.size |
[optional] (integer) Minimum node size. |
num.threads |
[optional] (integer) Number of threads used by
ranger. One thread keeps results reproducible across machines
(default: |
... |
[optional] Further arguments passed to
|
degree |
[optional] (integer) Highest power of each numeric control
in the design matrix (default: |
alpha |
[optional] (numeric) Elastic-net mixing parameter: |
nfolds |
[optional] (integer) Number of folds for the internal
cross-validation of the penalty (default: |
s |
[optional] (character or numeric) Value of the penalty used for
prediction, as in
|
fit |
[mandatory] (function) A function |
predict |
[mandatory] (function) A function
|
name |
[optional] (character) A short label shown in printed output
(default: |
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
Log-Odds Against the Reference Category
Description
Computes the log-odds of each category against the first, with the
probabilities bounded below by 1e-6.
Usage
log_odds(P)
Arguments
P |
[mandatory] (matrix) Class probabilities, reference first. |
Value
A matrix with one column per non-reference category.
Assign Observations to Cross-Fitting Folds
Description
Draws balanced random folds. Whole clusters stay in one fold.
Usage
make_folds(n, folds, cluster = NULL)
Arguments
n |
[mandatory] (integer) Number of observations. |
folds |
[mandatory] (integer) Number of folds. |
cluster |
[optional] (vector) Cluster identifier (default:
|
Value
An integer vector of fold indices of length n.
Features of the Recalibration Map
Description
Builds the regressors of the map (an intercept, the standardised log-odds, the standardised controls and, optionally, their products) and the offset (the log-odds).
Usage
map_features(P, Xd, scaling, interactions)
Arguments
P |
[mandatory] (matrix) Class probabilities, reference first. |
Xd |
[mandatory] (matrix) Design matrix of the controls. |
scaling |
[mandatory] (list) Result of |
interactions |
[mandatory] (logical) Whether to include the products of the log-odds and the controls. |
Value
A list with the regressors Z and the offset offset.
Probabilities from a Multinomial Logit
Description
Computes class probabilities from the regressors, the offset and the coefficients of a multinomial logit with the first category as the reference.
Usage
map_probs(Z, offset, B)
Arguments
Z |
[mandatory] (matrix) Regressors. |
offset |
[mandatory] (matrix) Offset, one column per non-reference category. |
B |
[mandatory] (matrix) Coefficients, one column per non-reference category. |
Value
A matrix of class probabilities, reference first.
Standardisation of the Map Features
Description
Records the means and standard deviations of the log-odds and of the design of the controls in the labelled sample.
Usage
map_scaling(P, Xd)
Arguments
P |
[mandatory] (matrix) Class probabilities, reference first. |
Xd |
[mandatory] (matrix) Design matrix of the controls. |
Value
A list with elements L and X, each holding
centre and scale.
Match Probability Columns to the Categories of a Fit
Description
Checks that the probabilities have the categories of the fit and puts their columns in the order of the fit.
Usage
match_categories(mat, categories)
Arguments
mat |
[mandatory] (matrix) Class probabilities with named columns. |
categories |
[mandatory] (character) Categories of the fit, reference first. |
Value
The matrix with its columns in the order of categories.
Largest Calibration Gap
Description
Computes the largest calibration gap over subgroups (or score bins), raw and net of sampling noise. The adjusted gap subtracts a Bonferroni-corrected multiple of the standard error of the cell gap under perfect calibration, so it is zero when no cell departs from calibration by more than chance.
Usage
max_gap(y, p, w, by, bins, min_cell)
Arguments
y |
[mandatory] (numeric) 0/1 indicator of the category. |
p |
[mandatory] (numeric) Probability of the category. |
w |
[mandatory] (numeric) Observation weights. |
by |
[mandatory] (factor or |
bins |
[mandatory] (integer) Number of equal-width bins. |
min_cell |
[mandatory] (integer) Smallest cell size used. |
Value
A named vector with elements raw and adjusted.
Evaluate the Controls of a Fit in Other Data
Description
Evaluates the right-hand side of a model formula in other data. The stored
terms reproduce data-dependent bases such as poly(), and
matrix-valued terms are split into single columns as in
controls_frame().
Usage
model_controls(terms, data)
Arguments
terms |
[mandatory] (terms) Terms of the fit without the response. |
data |
[mandatory] (data.frame) Data. |
Value
A data frame of controls with one row per row of data.
Construct a Learner
Description
Creates an object of class softcats_learner.
Usage
new_learner(name, fit, predict, details = list())
Arguments
name |
[mandatory] (character) Label shown in printed output. |
fit |
[mandatory] (function) Fitting function
|
predict |
[mandatory] (function) Prediction function
|
details |
[optional] (list) Settings stored with the learner
(default: |
Value
An object of class softcats_learner.
Default for NULL Values
Description
Returns y if x is NULL and x otherwise.
Usage
x %||% y
Arguments
x |
[mandatory] (any) Value to test. |
y |
[mandatory] (any) Default value. |
Value
x, or y if x is NULL.
One-Hot Coding of Observed Labels
Description
Codes observed labels against the categories of a probability matrix.
Missing labels give rows of NA.
Usage
one_hot(labels, categories)
Arguments
labels |
[mandatory] (vector) Observed labels. |
categories |
[mandatory] (character) Category names. |
Value
A 0/1 matrix with one column per category.
Put the Reference Category First
Description
Reorders the columns of the probability matrix so that the reference category comes first.
Usage
order_reference(mat, reference)
Arguments
mat |
[mandatory] (matrix) Class probabilities. |
reference |
[mandatory] (character or integer) Reference category, by name or position. |
Value
The reordered matrix.
Format p-Values in Text
Description
Formats p-values for running text as "p = 0.0123" or
"p < 1e-04".
Usage
p_text(p)
Arguments
p |
[mandatory] (numeric) p-values. |
Value
A character vector.
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\} \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 |
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
|
probs |
[optional] (matrix, data.frame, character, formula or
numeric) Probabilities for the labelled observations, or for
|
interactions |
[optional] (logical) Whether the map includes the
products of the log-odds and the controls (default: |
folds |
[optional] (integer) Number of folds of the labelled sample
for the out-of-fold check, at least two (default: |
weights |
[optional] (numeric, character or formula) Weights of the
labelled observations: a vector, a column name of |
level |
[optional] (numeric) Confidence level of the intervals
(default: |
seed |
[optional] (integer) Seed for the folds of the labelled
sample. |
x |
[mandatory] (softcats_recalibration) Result of
|
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[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.
The labelled sample is split into
foldsfolds; two folds give the split-half design of Kurbucz (2026). Each fold is recalibrated by the map fitted on the other folds, andcalibration_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.The map fitted on the whole labelled sample recalibrates the probabilities of the estimation sample.
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, andupdate()with the probabilities frompredict()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 \mid G, p, X] = \mu(X) + \tau^\top g + d(p, X), the
estimate converges to \tau + M^{-1} E[a\,d] with
M = E[a a^\top]. A map that moves the probabilities towards their
conditional mean given the controls shrinks M and can amplify
this bias. The function therefore reports the eigenvalues of M 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"))
Objects exported from other packages
Description
These objects are imported from other packages. Follow the links below to see their documentation.
Resolve the Learner Argument
Description
Accepts a single learner or a list list(m = , r = ).
Usage
resolve_learner(learner)
Arguments
learner |
[mandatory] (softcats_learner or list) The |
Value
A list with the learners m and r.
Resolve the Class Probabilities
Description
Turns the probs argument into a numeric matrix with one column per
category.
Usage
resolve_probs(probs, data, n)
Arguments
probs |
[mandatory] (matrix, data.frame, character, formula or
numeric) Class probabilities in any form accepted by
|
data |
[mandatory] (data.frame or |
n |
[mandatory] (integer) Expected number of rows. |
Value
A list with the matrix mat, the form of the input
spec and the input itself raw.
Resolve an Optional Per-Row Vector
Description
Turns an argument given as NULL, a vector, a column name of
data or a one-sided formula evaluated in data into a vector.
Usage
resolve_vector(x, data, n, what)
Arguments
x |
[mandatory] (vector, character, formula or |
data |
[mandatory] (data.frame or |
n |
[mandatory] (integer) Expected length. |
what |
[mandatory] (character) Argument name used in error messages. |
Value
A vector of length n, or NULL.
Get the State of the Random Number Generator
Description
Returns the current state of the random number generator of the session without changing it.
Usage
rng_state()
Value
The value of .Random.seed, or NULL if it does not
exist.
Sandwich Covariance of an Estimating Equation
Description
Computes J^{-1} B J^{-1} for per-observation scores psi and
Jacobian J, with cluster sums and the small-sample factor
G / (G - 1) when cluster is given.
Usage
sandwich_vcov(psi, J, cluster = NULL)
Arguments
psi |
[mandatory] (matrix) Scores, one row per observation. |
J |
[mandatory] (matrix) Jacobian. |
cluster |
[optional] (vector) Cluster identifier (default:
|
Value
A symmetric covariance matrix.
Information in the Scores Beyond the Controls
Description
Identification in soft_lm() rests on the matrix
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[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
|
x |
[mandatory] (softcats_spectrum) Result of
|
digits |
[optional] (integer) Number of significant digits to print
(default: |
... |
[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[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 \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^*.
Value
An object of class softcats_spectrum: a list with
values (eigenvalues of 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)
Set the State of the Random Number Generator
Description
Restores a state returned by rng_state(). NULL removes the
state, as in a session that has not used the generator.
Usage
set_rng_state(state)
Arguments
state |
[mandatory] (integer or |
Value
NULL, invisibly; called for its side effect.
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:
|
K |
[optional] (integer) Number of categories (default: |
tau |
[optional] (numeric) Effects of categories 2 to |
n_controls |
[optional] (integer) Number of controls (default:
|
concentration |
[optional] (numeric) Dirichlet concentration; smaller
values give more dispersed probabilities and more information beyond the
controls (default: |
z_effect |
[optional] (numeric) Effect of |
direct_effect |
[optional] (numeric) Direct effect of |
miscalibration |
[optional] (numeric) Strength of the conditional
miscalibration of the returned probabilities (default: |
nonlinear |
[optional] (logical) If |
labelled_share |
[optional] (numeric) Share of observations flagged
in column |
seed |
[optional] (integer) Seed. The random number generator state
of the session is restored afterwards (default: |
Details
The controls X are independent standard normal variables,
and Z is a standard normal classifier feature that is not a
control. Class probabilities are drawn as p \sim
\mathrm{Dirichlet}(c\, \pi(X, Z)), where \pi is a multinomial
logit in X and Z and c is concentration. The
group is drawn from p, so the probabilities are calibrated given
X by construction. The outcome is Y = \mu(X) + \sum_k \tau_k
1\{G = k\} + \theta Z + \varepsilon with \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
X. With direct_effect different from zero, Z 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 \mid X]) and r_true (the true
E[p \mid X] of the calibrated probabilities), computed by
Gauss-Hermite quadrature over Z.
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:
-
Information beyond the controls (
score_spectrum()): the smallest canonical share of score variance not explained by the controls. -
Direct effects of classifier features (
exclusion_test()), ifextrais given. -
Calibration given the controls (
calibration_check()), if labelled data are given, graded by the overall test, which detects every departure fromE[1\{G = k\} \mid p, X] = p_k, whether or not it depends on the controls. -
Sensitivity to calibration drift (
drift_sensitivity()), at the driftdeltaor, 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
|
labelled |
[optional] (data.frame) Labelled observations (default:
|
group |
[optional] (vector or character) Observed category labels in
|
probs |
[optional] (matrix, data.frame, character, formula or
numeric) Probabilities for the labelled observations. |
extra |
[optional] (formula or character) Classifier features that
are not controls, for the exclusion test: a one-sided formula or column
names (default: |
by |
[optional] (vector, character or formula) Grouping variable for
subgroup calibration gaps (default: |
delta |
[optional] (numeric) Drift magnitude for the sensitivity
check (default: |
x |
[mandatory] (softcats_check) Result of |
... |
[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
|
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 |
[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: |
learner |
[optional] (softcats_learner or list) A learner (see
|
folds |
[optional] (integer) Number of cross-fitting folds, at least
two (default: |
n_rep |
[optional] (integer) Number of repetitions of cross-fitting
with new fold splits (default: |
weights |
[optional] (numeric, character or formula) Non-negative
observation weights, for example survey weights: a numeric vector, a
column name of |
cluster |
[optional] (vector, character or formula) Cluster
identifier for cluster-robust standard errors: a vector, a column name of
|
seed |
[optional] (integer) Seed for the fold splits and stochastic
learners. The random number generator state of the session is restored
afterwards (default: |
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 G with categories 1, \dots, K (category 1
is the reference) and class probabilities, or scores, p, the target
is \tau in the partially linear model
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\} \mid p, X] =
p_k. Under this condition and the exclusion condition
E[Y \mid G, p, X] = E[Y \mid G, X] (see Requirements), with
a = p - E[p \mid X] (reference column removed) and
m(X) = E[Y \mid X],
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[a
a^\top] is non-singular. For two categories, E[a a^\top] is the
residual score variance V^* = E[\mathrm{Var}(p \mid X)].
Estimation and inference
The nuisances m(X) and 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^{-1} E[u^2 a a^\top] M^{-1} / n, M = E[a a^\top] and
u = Y - m(X) - a^\top\tau, when both nuisance estimates are
consistent, their errors satisfy
\|\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) for G 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
|
... |
[optional] Not used. |
parm |
[optional] (character or integer) Coefficients to report, by name or position (default: all coefficients). |
level |
[optional] (numeric) Confidence level (default:
|
digits |
[optional] (integer) Number of significant digits to print
(default: |
conf.int |
[optional] (logical) Whether |
conf.level |
[optional] (numeric) Confidence level for |
which |
[optional] (character) For |
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")
Split Matrix-Valued Terms into Columns
Description
Replaces each matrix-valued column of a model frame, such as the basis of
poly(), by one column per basis function.
Usage
split_matrix_terms(x)
Arguments
x |
[mandatory] (data.frame) Columns of a model frame. |
Value
A data frame without matrix-valued columns.
Signal an Input Error
Description
Formats a message with sprintf() and stops without the call.
Usage
stop_input(...)
Arguments
... |
[mandatory] Format string and values passed to
|
Value
No return value, called for its error.
Remove a Shared Prefix from Column Names
Description
Removes a prefix shared by all names (such as "prob_" or
".pred_"), cut back to the last "_" or "." inside the
shared part. The names are kept if the result would be empty or
duplicated.
Usage
strip_common_prefix(x)
Arguments
x |
[mandatory] (character) Column names. |
Value
A character vector of the same length as x.
Validate and Normalise Class Probabilities
Description
Checks that the probabilities are finite, lie in [0, 1] and sum to
one in every row up to a tolerance, then clips and renormalises them.
Usage
validate_probs(mat, tol = 1e-04)
Arguments
mat |
[mandatory] (matrix) Class probabilities. |
tol |
[optional] (numeric) Tolerance (default: |
Value
The clipped and renormalised matrix.
Label of the Covariance Estimator
Description
Describes the standard errors of a fit for printed output.
Usage
vcov_label(object)
Arguments
object |
[mandatory] (softcats) A fit returned by
|
Value
A character string.
Weighted Column Means
Description
Computes the weighted mean of each column.
Usage
weighted_colmeans(m, w)
Arguments
m |
[mandatory] (matrix) Numeric matrix. |
w |
[mandatory] (numeric) Weights. |
Value
A numeric vector with one element per column.
Weighted Covariance Matrix
Description
Computes the weighted covariance of the columns, normalised by the sum of the weights.
Usage
weighted_cov(m, w)
Arguments
m |
[mandatory] (matrix) Numeric matrix. |
w |
[mandatory] (numeric) Weights. |
Value
A square matrix.
Evaluate Code with a Temporary Seed
Description
Evaluates code after setting the seed and restores the random number
generator state of the session afterwards. With seed = NULL, the
code is evaluated without changing the state.
Usage
with_seed(seed, code)
Arguments
seed |
[mandatory] (integer or |
code |
[mandatory] (expression) Code to evaluate. |
Value
The value of code.