API Reference¶
Complete API documentation for all Nonconform modules and classes.
Core Modules¶
Estimation¶
nonconform.estimation ¶
Conformal anomaly detection estimators.
This module provides the core conformal anomaly detection classes that wrap PyOD detectors with uncertainty quantification capabilities.
BaseConformalDetector ¶
Bases: ABC
Abstract base class for all conformal anomaly detectors.
Defines the core interface that all conformal anomaly detection implementations must provide. This ensures consistent behavior across different conformal methods (standard, weighted, etc.) while maintaining flexibility.
Design Pattern:
All conformal detectors follow a two-phase workflow:
1. Calibration Phase: fit()
trains detector, computes calibration scores
2. Inference Phase: predict()
converts new data scores to valid p-values
Implementation Requirements:
Subclasses must implement both abstract methods to provide:
- Training/calibration logic in fit()
- P-value generation logic in predict()
Note
This is an abstract class and cannot be instantiated directly. Use concrete
implementations like StandardConformalDetector
or WeightedConformalDetector
.
fit
abstractmethod
¶
Fit the detector model(s) and compute calibration scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The dataset used for fitting the model(s) and determining calibration scores. |
required |
Source code in nonconform/estimation/base.py
predict
abstractmethod
¶
Generate anomaly estimates or p-values for new data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The new data instances for which to make anomaly estimates. |
required |
raw
|
bool
|
Whether to return raw anomaly scores or processed anomaly estimates (e.g., p-values). Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: An array containing the anomaly estimates. |
Source code in nonconform/estimation/base.py
ConformalDetector ¶
ConformalDetector(
detector: BaseDetector,
strategy: BaseStrategy,
weight_estimator: BaseWeightEstimator | None = None,
aggregation: Aggregation = Aggregation.MEDIAN,
seed: int | None = None,
)
Bases: BaseConformalDetector
Unified conformal anomaly detector with optional covariate shift handling.
Provides distribution-free anomaly detection with valid p-values and False Discovery Rate (FDR) control by wrapping any PyOD detector with conformal inference. Optionally handles covariate shift through importance weighting when a weight estimator is specified.
When no weight estimator is provided (standard conformal prediction): - Uses classical conformal inference for exchangeable data - Provides optimal performance and memory usage - Suitable when training and test data come from the same distribution
When a weight estimator is provided (weighted conformal prediction): - Handles distribution shift between calibration and test data - Estimates importance weights to maintain statistical validity - Slightly higher computational cost but robust to covariate shift
Examples:
Standard conformal prediction (no distribution shift):
from pyod.models.iforest import IForest
from nonconform.estimation import ConformalDetector
from nonconform.strategy import Split
# Create standard conformal detector
detector = ConformalDetector(
detector=IForest(), strategy=Split(n_calib=0.2), seed=42
)
# Fit on normal training data
detector.fit(X_train)
# Get p-values for test data
p_values = detector.predict(X_test)
Weighted conformal prediction (with distribution shift):
from nonconform.estimation.weight import LogisticWeightEstimator
# Create weighted conformal detector
detector = ConformalDetector(
detector=IForest(),
strategy=Split(n_calib=0.2),
weight_estimator=LogisticWeightEstimator(seed=42),
seed=42,
)
# Same usage as standard conformal
detector.fit(X_train)
p_values = detector.predict(X_test)
Attributes:
Name | Type | Description |
---|---|---|
detector |
BaseDetector
|
The underlying PyOD anomaly detection model. |
strategy |
BaseStrategy
|
The calibration strategy for computing p-values. |
weight_estimator |
BaseWeightEstimator | None
|
Optional weight estimator for handling covariate shift. |
aggregation |
Aggregation
|
Method for combining scores from multiple models. |
seed |
int | None
|
Random seed for reproducible results. |
detector_set |
list[BaseDetector]
|
List of trained detector models (populated after fit). |
calibration_set |
ndarray
|
Calibration scores for p-value computation (populated by fit). |
is_fitted |
bool
|
Whether the detector has been fitted. |
calibration_samples |
ndarray
|
Data instances used for calibration (only for weighted mode). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detector
|
BaseDetector
|
The base anomaly detection model to be used (e.g., an instance of a PyOD detector). |
required |
strategy
|
BaseStrategy
|
The conformal strategy to apply for fitting and calibration. |
required |
weight_estimator
|
BaseWeightEstimator | None
|
Weight estimator for handling covariate shift. If None, uses standard conformal prediction (equivalent to IdentityWeightEstimator). Defaults to None. |
None
|
aggregation
|
Aggregation
|
Method used for aggregating scores from multiple detector models. Defaults to Aggregation.MEDIAN. |
MEDIAN
|
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If seed is negative. |
TypeError
|
If aggregation is not an Aggregation enum. |
Source code in nonconform/estimation/conformal.py
detector_set
property
¶
Returns a copy of the list of trained detector models.
Returns:
Type | Description |
---|---|
list[BaseDetector]
|
list[PyODBaseDetector]: Copy of trained detectors populated after fit(). |
Note
Returns a defensive copy to prevent external modification of internal state.
calibration_set
property
¶
Returns a copy of the calibration scores.
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: Copy of calibration scores populated after fit(). |
Note
Returns a defensive copy to prevent external modification of internal state.
calibration_samples
property
¶
Returns a copy of the calibration samples used for weight computation.
Only available when using weighted conformal prediction (non-identity weight estimator). For standard conformal prediction, returns an empty array.
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: Copy of data instances used for calibration, or empty array if using standard conformal prediction. |
Note
Returns a defensive copy to prevent external modification of internal state.
is_fitted
property
¶
Returns whether the detector has been fitted.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if fit() has been called and models are trained. |
fit ¶
Fits the detector model(s) and computes calibration scores.
This method uses the specified strategy to train the base detector(s)
on parts of the provided data and then calculates non-conformity
scores on other parts (calibration set) to establish a baseline for
typical behavior. The resulting trained models and calibration scores
are stored in self._detector_set
and self._calibration_set
.
For weighted conformal prediction, calibration samples are also stored for weight computation during prediction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The dataset used for fitting the model(s) and determining calibration scores. The strategy will dictate how this data is split or used. |
required |
iteration_callback
|
callable | None
|
Optional callback function for strategies that support iteration tracking (e.g., Bootstrap). Called after each iteration with (iteration, scores). Defaults to None. |
None
|
Source code in nonconform/estimation/conformal.py
predict ¶
Generate anomaly estimates (p-values or raw scores) for new data.
Based on the fitted models and calibration scores, this method evaluates new data points. For standard conformal prediction, returns p-values based on the calibration distribution. For weighted conformal prediction, incorporates importance weights to handle covariate shift.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The new data instances for which to generate anomaly estimates. |
required |
raw
|
bool
|
Whether to return raw anomaly scores or p-values. Defaults to False. * If True: Returns the aggregated anomaly scores (non-conformity estimates) from the detector set for each data point. * If False: Returns the p-values for each data point based on the calibration set, optionally weighted for distribution shift. |
False
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: An array containing the anomaly estimates. The content of the |
ndarray
|
array depends on the |
ndarray
|
|
ndarray
|
|
Source code in nonconform/estimation/conformal.py
base ¶
BaseConformalDetector ¶
Bases: ABC
Abstract base class for all conformal anomaly detectors.
Defines the core interface that all conformal anomaly detection implementations must provide. This ensures consistent behavior across different conformal methods (standard, weighted, etc.) while maintaining flexibility.
Design Pattern:
All conformal detectors follow a two-phase workflow:
1. Calibration Phase: fit()
trains detector, computes calibration scores
2. Inference Phase: predict()
converts new data scores to valid p-values
Implementation Requirements:
Subclasses must implement both abstract methods to provide:
- Training/calibration logic in fit()
- P-value generation logic in predict()
Note
This is an abstract class and cannot be instantiated directly. Use concrete
implementations like StandardConformalDetector
or WeightedConformalDetector
.
fit
abstractmethod
¶
Fit the detector model(s) and compute calibration scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The dataset used for fitting the model(s) and determining calibration scores. |
required |
Source code in nonconform/estimation/base.py
predict
abstractmethod
¶
Generate anomaly estimates or p-values for new data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The new data instances for which to make anomaly estimates. |
required |
raw
|
bool
|
Whether to return raw anomaly scores or processed anomaly estimates (e.g., p-values). Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: An array containing the anomaly estimates. |
Source code in nonconform/estimation/base.py
conformal ¶
ConformalDetector ¶
ConformalDetector(
detector: BaseDetector,
strategy: BaseStrategy,
weight_estimator: BaseWeightEstimator | None = None,
aggregation: Aggregation = Aggregation.MEDIAN,
seed: int | None = None,
)
Bases: BaseConformalDetector
Unified conformal anomaly detector with optional covariate shift handling.
Provides distribution-free anomaly detection with valid p-values and False Discovery Rate (FDR) control by wrapping any PyOD detector with conformal inference. Optionally handles covariate shift through importance weighting when a weight estimator is specified.
When no weight estimator is provided (standard conformal prediction): - Uses classical conformal inference for exchangeable data - Provides optimal performance and memory usage - Suitable when training and test data come from the same distribution
When a weight estimator is provided (weighted conformal prediction): - Handles distribution shift between calibration and test data - Estimates importance weights to maintain statistical validity - Slightly higher computational cost but robust to covariate shift
Examples:
Standard conformal prediction (no distribution shift):
from pyod.models.iforest import IForest
from nonconform.estimation import ConformalDetector
from nonconform.strategy import Split
# Create standard conformal detector
detector = ConformalDetector(
detector=IForest(), strategy=Split(n_calib=0.2), seed=42
)
# Fit on normal training data
detector.fit(X_train)
# Get p-values for test data
p_values = detector.predict(X_test)
Weighted conformal prediction (with distribution shift):
from nonconform.estimation.weight import LogisticWeightEstimator
# Create weighted conformal detector
detector = ConformalDetector(
detector=IForest(),
strategy=Split(n_calib=0.2),
weight_estimator=LogisticWeightEstimator(seed=42),
seed=42,
)
# Same usage as standard conformal
detector.fit(X_train)
p_values = detector.predict(X_test)
Attributes:
Name | Type | Description |
---|---|---|
detector |
BaseDetector
|
The underlying PyOD anomaly detection model. |
strategy |
BaseStrategy
|
The calibration strategy for computing p-values. |
weight_estimator |
BaseWeightEstimator | None
|
Optional weight estimator for handling covariate shift. |
aggregation |
Aggregation
|
Method for combining scores from multiple models. |
seed |
int | None
|
Random seed for reproducible results. |
detector_set |
list[BaseDetector]
|
List of trained detector models (populated after fit). |
calibration_set |
ndarray
|
Calibration scores for p-value computation (populated by fit). |
is_fitted |
bool
|
Whether the detector has been fitted. |
calibration_samples |
ndarray
|
Data instances used for calibration (only for weighted mode). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detector
|
BaseDetector
|
The base anomaly detection model to be used (e.g., an instance of a PyOD detector). |
required |
strategy
|
BaseStrategy
|
The conformal strategy to apply for fitting and calibration. |
required |
weight_estimator
|
BaseWeightEstimator | None
|
Weight estimator for handling covariate shift. If None, uses standard conformal prediction (equivalent to IdentityWeightEstimator). Defaults to None. |
None
|
aggregation
|
Aggregation
|
Method used for aggregating scores from multiple detector models. Defaults to Aggregation.MEDIAN. |
MEDIAN
|
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If seed is negative. |
TypeError
|
If aggregation is not an Aggregation enum. |
Source code in nonconform/estimation/conformal.py
detector_set
property
¶
Returns a copy of the list of trained detector models.
Returns:
Type | Description |
---|---|
list[BaseDetector]
|
list[PyODBaseDetector]: Copy of trained detectors populated after fit(). |
Note
Returns a defensive copy to prevent external modification of internal state.
calibration_set
property
¶
Returns a copy of the calibration scores.
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: Copy of calibration scores populated after fit(). |
Note
Returns a defensive copy to prevent external modification of internal state.
calibration_samples
property
¶
Returns a copy of the calibration samples used for weight computation.
Only available when using weighted conformal prediction (non-identity weight estimator). For standard conformal prediction, returns an empty array.
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: Copy of data instances used for calibration, or empty array if using standard conformal prediction. |
Note
Returns a defensive copy to prevent external modification of internal state.
is_fitted
property
¶
Returns whether the detector has been fitted.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if fit() has been called and models are trained. |
fit ¶
Fits the detector model(s) and computes calibration scores.
This method uses the specified strategy to train the base detector(s)
on parts of the provided data and then calculates non-conformity
scores on other parts (calibration set) to establish a baseline for
typical behavior. The resulting trained models and calibration scores
are stored in self._detector_set
and self._calibration_set
.
For weighted conformal prediction, calibration samples are also stored for weight computation during prediction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The dataset used for fitting the model(s) and determining calibration scores. The strategy will dictate how this data is split or used. |
required |
iteration_callback
|
callable | None
|
Optional callback function for strategies that support iteration tracking (e.g., Bootstrap). Called after each iteration with (iteration, scores). Defaults to None. |
None
|
Source code in nonconform/estimation/conformal.py
predict ¶
Generate anomaly estimates (p-values or raw scores) for new data.
Based on the fitted models and calibration scores, this method evaluates new data points. For standard conformal prediction, returns p-values based on the calibration distribution. For weighted conformal prediction, incorporates importance weights to handle covariate shift.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The new data instances for which to generate anomaly estimates. |
required |
raw
|
bool
|
Whether to return raw anomaly scores or p-values. Defaults to False. * If True: Returns the aggregated anomaly scores (non-conformity estimates) from the detector set for each data point. * If False: Returns the p-values for each data point based on the calibration set, optionally weighted for distribution shift. |
False
|
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: An array containing the anomaly estimates. The content of the |
ndarray
|
array depends on the |
ndarray
|
|
ndarray
|
|
Source code in nonconform/estimation/conformal.py
weight ¶
Weight estimators for covariate shift in conformal prediction.
This module provides various weight estimation strategies for handling distribution shift between calibration and test data in weighted conformal prediction.
BaseWeightEstimator ¶
Bases: ABC
Abstract base class for weight estimators in weighted conformal prediction.
Weight estimators compute importance weights to correct for covariate shift between calibration and test distributions. They estimate density ratios w(x) = p_test(x) / p_calib(x) which are used to reweight conformal scores for better coverage guarantees under distribution shift.
Subclasses must implement the fit() and get_weights() methods to provide specific weight estimation strategies (e.g., logistic regression, random forest).
fit
abstractmethod
¶
ForestWeightEstimator ¶
ForestWeightEstimator(
n_estimators: int = 100,
max_depth: int | None = 5,
min_samples_leaf: int = 10,
clip_quantile: float = 0.05,
seed: int | None = None,
)
Bases: BaseWeightEstimator
Random Forest-based weight estimator for covariate shift.
Uses Random Forest classifier to estimate density ratios between calibration and test distributions. Random Forest can capture non-linear relationships and complex interactions between features, making it suitable for handling more complex covariate shift patterns than logistic regression.
The Random Forest is trained to distinguish between calibration and test samples, and the predicted probabilities are used to compute importance weights w(x) = p_test(x) / p_calib(x).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_estimators
|
int
|
Number of trees in the forest. Defaults to 100. |
100
|
max_depth
|
int
|
Maximum depth of trees. If None, nodes are expanded until all leaves are pure. Defaults to 5 to prevent overfitting. |
5
|
min_samples_leaf
|
int
|
Minimum number of samples required to be at a leaf node. Defaults to 10 to prevent overfitting. |
10
|
clip_quantile
|
float
|
Quantile for weight clipping. If 0.05, clips to 5th and 95th percentiles. If None, uses fixed [0.35, 45.0] range. |
0.05
|
seed
|
int
|
Random seed for reproducible results. |
None
|
Source code in nonconform/estimation/weight/forest.py
fit ¶
Fit the Random Forest weight estimator on calibration and test samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
calibration_samples
|
ndarray
|
Array of calibration data samples. |
required |
test_samples
|
ndarray
|
Array of test data samples. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If calibration_samples is empty. |
Source code in nonconform/estimation/weight/forest.py
get_weights ¶
Return computed weights.
Returns:
Type | Description |
---|---|
tuple[ndarray, ndarray]
|
Tuple of (calibration_weights, test_weights). |
Raises:
Type | Description |
---|---|
RuntimeError
|
If fit() has not been called. |
Source code in nonconform/estimation/weight/forest.py
IdentityWeightEstimator ¶
Bases: BaseWeightEstimator
Identity weight estimator that returns uniform weights.
This estimator assumes no covariate shift and returns weights of 1.0 for all samples. Useful as a baseline or when covariate shift is known to be minimal.
This effectively makes weighted conformal prediction equivalent to standard conformal prediction.
Source code in nonconform/estimation/weight/identity.py
fit ¶
Fit the identity weight estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
calibration_samples
|
ndarray
|
Array of calibration data samples. |
required |
test_samples
|
ndarray
|
Array of test data samples. |
required |
Source code in nonconform/estimation/weight/identity.py
get_weights ¶
Return uniform weights of 1.0 for all samples.
Returns:
Type | Description |
---|---|
tuple[ndarray, ndarray]
|
Tuple of (calibration_weights, test_weights) with all values = 1.0. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If fit() has not been called. |
Source code in nonconform/estimation/weight/identity.py
LogisticWeightEstimator ¶
LogisticWeightEstimator(
regularization="auto",
clip_quantile=0.05,
seed=None,
class_weight="balanced",
max_iter=1000,
)
Bases: BaseWeightEstimator
Logistic regression-based weight estimator for covariate shift.
Uses logistic regression to estimate density ratios between calibration and test distributions by training a classifier to distinguish between the two samples. The predicted probabilities are used to compute importance weights w(x) = p_test(x) / p_calib(x).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
regularization
|
str or float
|
Regularization parameter for logistic regression. If 'auto', uses default sklearn parameter. If float, uses as C parameter. |
'auto'
|
clip_quantile
|
float
|
Quantile for weight clipping. If 0.05, clips to 5th and 95th percentiles. If None, uses fixed [0.35, 45.0] range. |
0.05
|
seed
|
int
|
Random seed for reproducible results. |
None
|
class_weight
|
str or dict
|
Weights associated with classes like {class_label: weight}. If 'balanced', uses n_samples / (n_classes * np.bincount(y)). Defaults to 'balanced'. |
'balanced'
|
max_iter
|
int
|
Max. number of iterations for the solver to converge. Defaults to 1000. |
1000
|
Source code in nonconform/estimation/weight/logistic.py
fit ¶
Fit the weight estimator on calibration and test samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
calibration_samples
|
ndarray
|
Array of calibration data samples. |
required |
test_samples
|
ndarray
|
Array of test data samples. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If calibration_samples is empty. |
Source code in nonconform/estimation/weight/logistic.py
get_weights ¶
Return computed weights.
Returns:
Type | Description |
---|---|
tuple[ndarray, ndarray]
|
Tuple of (calibration_weights, test_weights). |
Raises:
Type | Description |
---|---|
RuntimeError
|
If fit() has not been called. |
Source code in nonconform/estimation/weight/logistic.py
base ¶
BaseWeightEstimator ¶
Bases: ABC
Abstract base class for weight estimators in weighted conformal prediction.
Weight estimators compute importance weights to correct for covariate shift between calibration and test distributions. They estimate density ratios w(x) = p_test(x) / p_calib(x) which are used to reweight conformal scores for better coverage guarantees under distribution shift.
Subclasses must implement the fit() and get_weights() methods to provide specific weight estimation strategies (e.g., logistic regression, random forest).
abstractmethod
¶forest ¶
ForestWeightEstimator ¶
ForestWeightEstimator(
n_estimators: int = 100,
max_depth: int | None = 5,
min_samples_leaf: int = 10,
clip_quantile: float = 0.05,
seed: int | None = None,
)
Bases: BaseWeightEstimator
Random Forest-based weight estimator for covariate shift.
Uses Random Forest classifier to estimate density ratios between calibration and test distributions. Random Forest can capture non-linear relationships and complex interactions between features, making it suitable for handling more complex covariate shift patterns than logistic regression.
The Random Forest is trained to distinguish between calibration and test samples, and the predicted probabilities are used to compute importance weights w(x) = p_test(x) / p_calib(x).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_estimators
|
int
|
Number of trees in the forest. Defaults to 100. |
100
|
max_depth
|
int
|
Maximum depth of trees. If None, nodes are expanded until all leaves are pure. Defaults to 5 to prevent overfitting. |
5
|
min_samples_leaf
|
int
|
Minimum number of samples required to be at a leaf node. Defaults to 10 to prevent overfitting. |
10
|
clip_quantile
|
float
|
Quantile for weight clipping. If 0.05, clips to 5th and 95th percentiles. If None, uses fixed [0.35, 45.0] range. |
0.05
|
seed
|
int
|
Random seed for reproducible results. |
None
|
Source code in nonconform/estimation/weight/forest.py
Fit the Random Forest weight estimator on calibration and test samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
calibration_samples
|
ndarray
|
Array of calibration data samples. |
required |
test_samples
|
ndarray
|
Array of test data samples. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If calibration_samples is empty. |
Source code in nonconform/estimation/weight/forest.py
Return computed weights.
Returns:
Type | Description |
---|---|
tuple[ndarray, ndarray]
|
Tuple of (calibration_weights, test_weights). |
Raises:
Type | Description |
---|---|
RuntimeError
|
If fit() has not been called. |
Source code in nonconform/estimation/weight/forest.py
identity ¶
IdentityWeightEstimator ¶
Bases: BaseWeightEstimator
Identity weight estimator that returns uniform weights.
This estimator assumes no covariate shift and returns weights of 1.0 for all samples. Useful as a baseline or when covariate shift is known to be minimal.
This effectively makes weighted conformal prediction equivalent to standard conformal prediction.
Source code in nonconform/estimation/weight/identity.py
Fit the identity weight estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
calibration_samples
|
ndarray
|
Array of calibration data samples. |
required |
test_samples
|
ndarray
|
Array of test data samples. |
required |
Source code in nonconform/estimation/weight/identity.py
Return uniform weights of 1.0 for all samples.
Returns:
Type | Description |
---|---|
tuple[ndarray, ndarray]
|
Tuple of (calibration_weights, test_weights) with all values = 1.0. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If fit() has not been called. |
Source code in nonconform/estimation/weight/identity.py
logistic ¶
LogisticWeightEstimator ¶
LogisticWeightEstimator(
regularization="auto",
clip_quantile=0.05,
seed=None,
class_weight="balanced",
max_iter=1000,
)
Bases: BaseWeightEstimator
Logistic regression-based weight estimator for covariate shift.
Uses logistic regression to estimate density ratios between calibration and test distributions by training a classifier to distinguish between the two samples. The predicted probabilities are used to compute importance weights w(x) = p_test(x) / p_calib(x).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
regularization
|
str or float
|
Regularization parameter for logistic regression. If 'auto', uses default sklearn parameter. If float, uses as C parameter. |
'auto'
|
clip_quantile
|
float
|
Quantile for weight clipping. If 0.05, clips to 5th and 95th percentiles. If None, uses fixed [0.35, 45.0] range. |
0.05
|
seed
|
int
|
Random seed for reproducible results. |
None
|
class_weight
|
str or dict
|
Weights associated with classes like {class_label: weight}. If 'balanced', uses n_samples / (n_classes * np.bincount(y)). Defaults to 'balanced'. |
'balanced'
|
max_iter
|
int
|
Max. number of iterations for the solver to converge. Defaults to 1000. |
1000
|
Source code in nonconform/estimation/weight/logistic.py
Fit the weight estimator on calibration and test samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
calibration_samples
|
ndarray
|
Array of calibration data samples. |
required |
test_samples
|
ndarray
|
Array of test data samples. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If calibration_samples is empty. |
Source code in nonconform/estimation/weight/logistic.py
Return computed weights.
Returns:
Type | Description |
---|---|
tuple[ndarray, ndarray]
|
Tuple of (calibration_weights, test_weights). |
Raises:
Type | Description |
---|---|
RuntimeError
|
If fit() has not been called. |
Source code in nonconform/estimation/weight/logistic.py
Strategy¶
nonconform.strategy ¶
Conformal calibration strategies.
This module provides different strategies for conformal calibration including split conformal, cross-validation, bootstrap, and jackknife methods.
Bootstrap ¶
Bootstrap(
resampling_ratio: float | None = None,
n_bootstraps: int | None = None,
n_calib: int | None = None,
plus: bool = True,
)
Bases: BaseStrategy
Implements bootstrap-based conformal anomaly detection.
This strategy uses bootstrap resampling to create multiple training sets and calibration sets. For each bootstrap iteration: 1. A random subset of the data is sampled with replacement for training 2. The remaining samples are used for calibration 3. Optionally, a fixed number of calibration samples can be selected
The strategy can operate in two modes: 1. Standard mode: Uses a single model trained on all data for prediction 2. Plus mode: Uses an ensemble of models, each trained on a bootstrap sample
Attributes:
Name | Type | Description |
---|---|---|
_resampling_ratio |
float
|
Proportion of data to use for training in each bootstrap iteration |
_n_bootstraps |
int
|
Number of bootstrap iterations |
_n_calib |
int | None
|
Optional fixed number of calibration samples to use |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors |
_calibration_set |
list[float]
|
List of calibration scores |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
Exactly two of resampling_ratio
, n_bootstraps
, and n_calib
should be provided. The third will be calculated by _configure
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resampling_ratio
|
float | None
|
The proportion of
data to use for training in each bootstrap. Defaults to |
None
|
n_bootstraps
|
int | None
|
The number of bootstrap
iterations. Defaults to |
None
|
n_calib
|
int | None
|
The desired size of the final
calibration set. If set, collected scores/IDs might be
subsampled. Defaults to |
None
|
plus
|
bool
|
If |
True
|
Source code in nonconform/strategy/experimental/bootstrap.py
calibration_ids
property
¶
Returns a copy of the list of indices used for calibration.
These are indices relative to the original input data x
provided to
:meth:fit_calibrate
. The list contains indices of all out-of-bag
samples encountered during bootstrap iterations. If _n_calib
was
set and weighted
was True
in fit_calibrate
, this list might
be a subsample of all encountered IDs, corresponding to the
subsampled _calibration_set
.
Returns:
Type | Description |
---|---|
list[int]
|
List[int]: A copy of integer indices. |
Note
Returns a defensive copy to prevent external modification of internal state.
resampling_ratio
property
¶
Returns the resampling ratio.
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
Proportion of data used for training in each bootstrap iteration. |
n_bootstraps
property
¶
Returns the number of bootstrap iterations.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bootstrap iterations. |
n_calib
property
¶
Returns the target calibration set size.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Target number of calibration samples. |
plus
property
¶
Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback: Callable[[int, ndarray], None]
| None = None,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate the detector using bootstrap resampling.
This method implements the bootstrap strategy by: 1. Creating multiple bootstrap samples of the data 2. For each bootstrap iteration: - Train the detector on the bootstrap sample - Use the out-of-bootstrap samples for calibration - Store calibration scores and optionally the trained model 3. If not in plus mode, train a final model on all data 4. Optionally subsample the calibration set to a fixed size
The method provides robust calibration scores by using multiple bootstrap iterations, which helps account for the variability in the data and model training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
weighted
|
bool
|
Whether to use weighted calibration. If True, calibration scores are weighted by their sample indices. Defaults to False. |
False
|
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
iteration_callback
|
Callable[[int, ndarray], None]
|
Optional callback function that gets called after each bootstrap iteration with the iteration number and calibration scores. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detectors (either n_bootstraps models in plus mode or a single model in standard mode) * Array of calibration scores from all bootstrap iterations |
Raises:
Type | Description |
---|---|
ValueError
|
If resampling_ratio is not between 0 and 1, or if n_bootstraps is less than 1, or if n_calib is less than 1 when specified. |
Source code in nonconform/strategy/experimental/bootstrap.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
|
Randomized ¶
Randomized(
n_iterations: int | None = None,
n_calib: int | None = None,
sampling_distr: Distribution = Distribution.UNIFORM,
holdout_size_range: tuple[float, float] | None = None,
beta_params: tuple[float, float] | None = None,
grid_probs: tuple[list[int], list[float]] | None = None,
plus: bool = True,
)
Bases: BaseStrategy
Implements randomized leave-p-out (rLpO) conformal anomaly detection.
This strategy uses randomized leave-p-out resampling where on each iteration a validation set size p is drawn at random, then a size-p validation set is sampled without replacement, the detector is trained on the rest, and calibration scores are computed. This approach smoothly interpolates between leave-one-out (p=1) and larger holdout strategies.
The strategy can operate in two modes: 1. Standard mode: Uses a single model trained on all data for prediction 2. Plus mode: Uses an ensemble of models, each trained on a different subset
Attributes:
Name | Type | Description |
---|---|---|
_sampling_distr |
Distribution
|
Distribution type for drawing holdout sizes |
_n_iterations |
int | None
|
Number of rLpO iterations |
_holdout_size_range |
tuple
|
Range of holdout sizes (relative or absolute) |
_beta_params |
tuple
|
Alpha and beta parameters for beta distribution |
_grid_probs |
tuple
|
Holdout sizes and probabilities for grid distribution |
_n_calib |
int | None
|
Target number of calibration samples |
_use_n_calib_mode |
bool
|
Whether to use n_calib mode vs n_iterations mode |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors |
_calibration_set |
list[float]
|
List of calibration scores |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_iterations
|
int | None
|
Number of rLpO iterations to perform. Cannot be used together with n_calib. Defaults to None. |
None
|
n_calib
|
int | None
|
Target number of calibration samples. Iterations will stop when this target is reached or exceeded, then subsample to exactly this size. Cannot be used with n_iterations. Defaults to None. |
None
|
sampling_distr
|
Distribution
|
Distribution for drawing holdout set sizes. Options: Distribution.BETA_BINOMIAL, Distribution.UNIFORM, Distribution.GRID. Defaults to Distribution.UNIFORM. |
UNIFORM
|
holdout_size_range
|
tuple[float, float]
|
Min and max holdout set sizes. Values in ]0, 1[ are interpreted as fractions of dataset size. Values >= 1 are interpreted as absolute sample counts. If None, defaults to (0.1, 0.5) for relative sizing. Defaults to None. |
None
|
beta_params
|
tuple[float, float]
|
Alpha and beta parameters for Beta distribution used to draw holdout size fractions. If None and sampling_distr is BETA_BINOMIAL, defaults to (2.0, 5.0). Common parameterizations: - (1.0, 1.0): Uniform sampling (equivalent to UNIFORM distribution) - (2.0, 5.0): Right-skewed, favors smaller holdout sizes [DEFAULT] - (5.0, 2.0): Left-skewed, favors larger holdout sizes - (2.0, 2.0): Bell-shaped, concentrated around middle sizes - (0.5, 0.5): U-shaped, concentrated at extremes Defaults to None. |
None
|
grid_probs
|
tuple[list[int], list[float]]
|
Holdout sizes and corresponding probabilities for grid distribution. Required if sampling_distr is Distribution.GRID. Defaults to None. |
None
|
plus
|
bool
|
If True, uses ensemble of models trained on different subsets. If False, uses single model trained on all data. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If required parameters for the chosen distribution are missing, if both n_iterations and n_calib are specified, or neither. |
Source code in nonconform/strategy/experimental/randomized.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
|
calibration_ids
property
¶
Returns a copy of the list of indices used for calibration.
These are indices relative to the original input data x
provided to
:meth:fit_calibrate
. The list contains indices of all holdout
samples encountered during rLpO iterations.
Returns:
Type | Description |
---|---|
list[int]
|
list[int]: A copy of integer indices for calibration samples. |
Note
Returns a defensive copy to prevent external modification of internal state.
n_iterations
property
¶
Returns the number of iterations.
Returns:
Type | Description |
---|---|
int | None
|
int | None: Number of iterations, or None if using n_calib mode. |
n_calib
property
¶
Returns the target calibration set size.
Returns:
Type | Description |
---|---|
int | None
|
int | None: Target number of calibration samples, |
int | None
|
or None if using n_iterations mode. |
sampling_distr
property
¶
Returns the sampling distribution type.
Returns:
Name | Type | Description |
---|---|---|
Distribution |
Distribution
|
Distribution used for drawing holdout sizes. |
holdout_size_range
property
¶
Returns the holdout size range.
Returns:
Type | Description |
---|---|
tuple[float, float]
|
tuple[float, float]: Min and max holdout set sizes. |
beta_params
property
¶
Returns the beta distribution parameters.
Returns:
Type | Description |
---|---|
tuple[float, float] | None
|
tuple[float, float] | None: Alpha and beta parameters, |
tuple[float, float] | None
|
or None if not using beta distribution. |
grid_probs
property
¶
Returns the grid probabilities.
Returns:
Type | Description |
---|---|
tuple[list[int], list[float]] | None
|
tuple[list[int], list[float]] | None: Holdout sizes and probabilities, or None if not using grid distribution. |
plus
property
¶
Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback: Callable[[int, ndarray], None]
| None = None,
track_p_values: bool = False,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate the detector using randomized leave-p-out resampling.
This method implements the rLpO strategy by: 1. For each iteration, drawing a random holdout set size 2. Sampling a holdout set of that size without replacement 3. Training the detector on the remaining samples 4. Computing calibration scores on the holdout set 5. Optionally storing the trained model (in plus mode) 6. If using n_calib mode, stopping when target calibration size is reached
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
weighted
|
bool
|
Whether to store calibration sample indices. Defaults to False. |
False
|
iteration_callback
|
Callable[[int, ndarray], None]
|
Optional callback function called after each iteration with the iteration number and calibration scores. Defaults to None. |
None
|
track_p_values
|
bool
|
If True, stores the holdout sizes and per-iteration scores for performance analysis. Can be accessed via get_iteration_info(). Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detectors (either multiple models in plus mode or a single model in standard mode) * Array of calibration scores from all iterations |
Raises:
Type | Description |
---|---|
ValueError
|
If holdout set size would leave insufficient training data. |
Source code in nonconform/strategy/experimental/randomized.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
|
get_iteration_info ¶
Get holdout sizes and per-iteration scores if tracking was enabled.
This method provides access to the holdout set sizes used in each iteration and the corresponding anomaly scores. This information can be used for performance analysis, plotting vs. holdout size, or understanding the distribution of holdout set sizes used.
Returns:
Type | Description |
---|---|
tuple[list[int], list[list[float]]] | None
|
tuple[list[int], list[list[float]]] | None: A tuple containing: * List of holdout sizes for each iteration * List of score arrays, one per iteration Returns None if track_p_values was False during fit_calibrate. |
Example
from nonconform.utils.func.enums import Distribution strategy = Randomized(n_calib=1000) strategy.fit_calibrate(X, detector, track_p_values=True) holdout_sizes, scores = strategy.get_iteration_info()
holdout_sizes[i] is the holdout set size for iteration i¶
scores[i] are the anomaly scores for iteration i¶
Source code in nonconform/strategy/experimental/randomized.py
BaseStrategy ¶
Bases: ABC
Abstract base class for anomaly detection calibration strategies.
This class provides a common interface for various calibration strategies applied to anomaly detectors. Subclasses must implement the core calibration logic and define how calibration data is identified and used.
Attributes:
Name | Type | Description |
---|---|---|
_plus |
bool
|
A flag, typically set during initialization, that may influence calibration behavior in subclasses (e.g., by applying an adjustment). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
plus
|
bool
|
A flag that enables the "plus" variant which
maintains statistical validity by retaining calibration models for
inference. Strongly recommended for proper conformal guarantees.
Defaults to |
True
|
Source code in nonconform/strategy/base.py
calibration_ids
abstractmethod
property
¶
Provides the indices of the data points used for calibration.
This abstract property must be implemented by subclasses. It should
return a list of integer indices identifying which samples from the
original input data (provided to fit_calibrate
) were selected or
designated as the calibration set.
Returns:
Type | Description |
---|---|
list[int]
|
List[int]: A list of integer indices for the calibration data. |
Raises:
Type | Description |
---|---|
NotImplementedError
|
If the subclass does not implement this property. |
fit_calibrate
abstractmethod
¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fits the detector and performs calibration.
This abstract method must be implemented by subclasses to define the
specific procedure for fitting the anomaly detector (if necessary)
and then calibrating it using data derived from x
. Calibration often
involves determining thresholds or adjusting scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The input data, which may be used for both fitting the detector and deriving calibration data. |
required |
detector
|
BaseDetector
|
The PyOD anomaly detection model to be fitted and/or calibrated. |
required |
weighted
|
bool | None
|
A flag indicating whether a weighted approach should be used during calibration, if applicable to the subclass implementation. |
False
|
seed
|
int | None
|
A random seed for ensuring reproducibility in stochastic parts of the fitting or calibration process. Defaults to None. |
None
|
iteration_callback
|
callable | None
|
Optional callback function for strategies that support iteration tracking. Defaults to None. |
None
|
Raises:
Type | Description |
---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Source code in nonconform/strategy/base.py
CrossValidation ¶
Bases: BaseStrategy
Implements k-fold cross-validation for conformal anomaly detection.
This strategy splits the data into k folds and uses each fold as a calibration set while training on the remaining folds. This approach provides more robust calibration scores by utilizing all available data. The strategy can operate in two modes: 1. Standard mode: Uses a single model trained on all data for prediction 2. Plus mode: Uses an ensemble of k models, each trained on k-1 folds
Attributes:
Name | Type | Description |
---|---|---|
_k |
int
|
Number of folds for cross-validation |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors |
_calibration_set |
list[float]
|
List of calibration scores |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
k
|
int
|
The number of folds for cross-validation. Must be at least 2. Higher values provide more robust calibration but increase computational cost. |
required |
plus
|
bool
|
If |
True
|
Source code in nonconform/strategy/cross_val.py
calibration_ids
property
¶
Returns a copy of the list of indices from x
used for calibration.
In k-fold cross-validation, every sample in the input data x
is
used exactly once as part of a calibration set (when its fold is
the hold-out set). This property returns a list of all these indices,
typically covering all indices from 0 to len(x)-1, but ordered by
fold processing.
Returns:
Type | Description |
---|---|
list[int]
|
list[int]: A copy of integer indices. |
Note
Returns a defensive copy to prevent external modification of internal state.
k
property
¶
Returns the number of folds for cross-validation.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of folds specified during initialization. |
plus
property
¶
Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate the detector using k-fold cross-validation.
This method implements the cross-validation strategy by: 1. Splitting the data into k folds 2. For each fold: - Train the detector on k-1 folds - Use the remaining fold for calibration - Store calibration scores and optionally the trained model 3. If not in plus mode, train a final model on all data
The method ensures that each sample is used exactly once for calibration, providing a more robust estimate of the calibration scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
weighted
|
bool
|
Whether to use weighted calibration. Currently not implemented for cross-validation. Defaults to False. |
False
|
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
iteration_callback
|
callable
|
Not used in CrossValidation strategy. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detectors (either k models in plus mode or a single model in standard mode) * Array of calibration scores from all folds |
Raises:
Type | Description |
---|---|
ValueError
|
If k is less than 2 or if the data size is too small for the specified number of folds. |
Source code in nonconform/strategy/cross_val.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
|
Jackknife ¶
Bases: BaseStrategy
Jackknife (leave-one-out) conformal anomaly detection strategy.
This strategy implements conformal prediction using the jackknife method, which is a special case of k-fold cross-validation where k equals the number of samples in the dataset (leave-one-out). For each sample, a model is trained on all other samples, and the left-out sample is used for calibration.
It internally uses a :class:~nonconform.strategy.cross_val.CrossValidation
strategy, dynamically setting its _k
parameter to the dataset size.
Attributes:
Name | Type | Description |
---|---|---|
_plus |
bool
|
If |
_strategy |
CrossValidation
|
An instance of the
:class: |
_calibration_ids |
list[int] | None
|
Indices of the samples from
the input data |
_detector_list |
List[BaseDetector]
|
A list of trained detector models,
populated by :meth: |
_calibration_set |
ndarray
|
An array of calibration scores, one for
each sample, populated by :meth: |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
plus
|
bool
|
If |
True
|
Source code in nonconform/strategy/jackknife.py
calibration_ids
property
¶
Returns a copy of indices from x
used for calibration via jackknife.
These are the indices of samples used to obtain calibration scores.
In jackknife (leave-one-out), each sample is used once for
calibration. The list is populated after fit_calibrate
is called.
Returns:
Type | Description |
---|---|
list[int] | None
|
list[int] | None: A copy of integer indices, or |
Note
Returns a defensive copy to prevent external modification of internal state.
plus
property
¶
Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
weighted: bool = False,
seed: int | None = None,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fits detector(s) and gets calibration scores using jackknife.
This method configures the internal
:class:~nonconform.strategy.cross_val.CrossValidation
strategy to
perform leave-one-out cross-validation by setting its number of
folds (_k
) to the total number of samples in x
. It then delegates
the fitting and calibration process to this internal strategy.
The results (trained models and calibration scores) and calibration sample IDs are retrieved from the internal strategy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The input data. |
required |
detector
|
BaseDetector
|
The PyOD base detector instance. |
required |
weighted
|
bool
|
Passed to the internal |
False
|
seed
|
int | None
|
Random seed, passed to the internal
|
None
|
iteration_callback
|
callable
|
Not used in Jackknife strategy. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], np.ndarray]: A tuple containing:
* A list of trained PyOD detector models.
* An array of calibration scores (one per sample in |
Source code in nonconform/strategy/jackknife.py
JackknifeBootstrap ¶
JackknifeBootstrap(
n_bootstraps: int = 100,
aggregation_method: Aggregation = Aggregation.MEAN,
plus: bool = True,
)
Bases: BaseStrategy
Implements Jackknife+-after-Bootstrap (JaB+) conformal anomaly detection.
This strategy implements the JaB+ method which provides predictive inference for ensemble models trained on bootstrap samples. The key insight is that JaB+ uses the out-of-bag (OOB) samples from bootstrap iterations to compute calibration scores without requiring additional model training.
The strategy can operate in two modes: 1. Plus mode (plus=True): Uses ensemble of models for prediction (recommended) 2. Standard mode (plus=False): Uses single model trained on all data
Attributes:
Name | Type | Description |
---|---|---|
_n_bootstraps |
int
|
Number of bootstrap iterations |
_aggregation_method |
Aggregation
|
How to aggregate OOB predictions |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors (ensemble/single) |
_calibration_set |
list[float]
|
List of calibration scores from JaB+ procedure |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
_bootstrap_models |
list[BaseDetector]
|
Models trained on each bootstrap sample |
_oob_mask |
ndarray
|
Boolean matrix of shape (n_bootstraps, n_samples) indicating out-of-bag status |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_bootstraps
|
int
|
Number of bootstrap iterations. Defaults to 100. |
100
|
aggregation_method
|
Aggregation
|
Method to aggregate out-of-bag predictions. Options are Aggregation.MEAN or Aggregation.MEDIAN. Defaults to Aggregation.MEAN. |
MEAN
|
plus
|
bool
|
If True, uses ensemble of bootstrap models for prediction (maintains statistical validity). If False, uses single model trained on all data. Strongly recommended to use True. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If aggregation_method is not a valid Aggregation enum value. |
ValueError
|
If n_bootstraps is less than 1. |
Source code in nonconform/strategy/jackknife_bootstrap.py
calibration_ids
property
¶
Returns a copy of the list of indices used for calibration.
In JaB+, all original training samples contribute to calibration through the out-of-bag mechanism.
Returns:
Type | Description |
---|---|
list[int]
|
list[int]: Copy of integer indices (0 to n_samples-1). |
Note
Returns a defensive copy to prevent external modification of internal state.
aggregation_method
property
¶
Returns the aggregation method used for OOB predictions.
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback: Callable[[int, ndarray], None]
| None = None,
n_jobs: int | None = None,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate using Jackknife+-after-Bootstrap method.
This method implements the JaB+ algorithm: 1. Generate bootstrap samples and train models 2. For each sample, compute out-of-bag predictions 3. Aggregate OOB predictions to get calibration scores 4. Train final model on all data
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
weighted
|
bool
|
Not used in JaB+ method. Defaults to False. |
False
|
iteration_callback
|
Callable[[int, ndarray], None]
|
Optional callback function that gets called after each bootstrap iteration with the iteration number and current calibration scores. Defaults to None. |
None
|
n_jobs
|
int
|
Number of parallel jobs for bootstrap training. If None, uses sequential processing. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detector models (if plus=True, single if plus=False) * Array of calibration scores from JaB+ procedure |
Source code in nonconform/strategy/jackknife_bootstrap.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
Split ¶
Bases: BaseStrategy
Split conformal strategy for fast anomaly detection with statistical guarantees.
Implements the classical split conformal approach by dividing training data into separate fitting and calibration sets. This provides the fastest conformal inference at the cost of using less data for calibration compared to other strategies.
Example
Attributes:
Name | Type | Description |
---|---|---|
_calib_size |
float | int
|
Size or proportion of data used for calibration. |
_calibration_ids |
list[int] | None
|
Indices of calibration samples (for weighted conformal). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_calib
|
float | int
|
The size or proportion
of the dataset to use for the calibration set. If a float,
it must be between 0.0 and 1.0 (exclusive of 0.0 and 1.0
in practice for |
0.1
|
Source code in nonconform/strategy/split.py
calibration_ids
property
¶
Returns a copy of indices from x
used for the calibration set.
This property provides the list of indices corresponding to the samples
that were allocated to the calibration set during the fit_calibrate
method. It will be None
if fit_calibrate
was called with
weighted=False
or if fit_calibrate
has not yet been called.
Returns:
Type | Description |
---|---|
list[int] | None
|
list[int] | None: A copy of integer indices, or |
Note
Returns a defensive copy to prevent external modification of internal state.
calib_size
property
¶
Returns the calibration size or proportion.
Returns:
Type | Description |
---|---|
float | int
|
float | int: The calibration size as specified during initialization. If float (0.0-1.0), represents proportion of data. If int, represents absolute number of samples. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
weighted: bool = False,
seed: int | None = None,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fits a detector and generates calibration scores using a data split.
The input data x
is split into a training set and a calibration
set according to _calib_size
. The provided detector
is trained
on the training set. Non-conformity scores are then computed using
the trained detector on the calibration set.
If weighted
is True
, the indices of the calibration samples
are stored in _calibration_ids
. Otherwise, _calibration_ids
remains None
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The input data. |
required |
detector
|
BaseDetector
|
The PyOD base detector instance to train. This instance is modified in place by fitting. |
required |
weighted
|
bool
|
If |
False
|
seed
|
int | None
|
Random seed for reproducibility of the train-test split. Defaults to None. |
None
|
iteration_callback
|
callable
|
Not used in Split strategy. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], np.ndarray]: A tuple containing: * A list containing the single trained PyOD detector instance. * An array of calibration scores from the calibration set. |
Source code in nonconform/strategy/split.py
base ¶
BaseStrategy ¶
Bases: ABC
Abstract base class for anomaly detection calibration strategies.
This class provides a common interface for various calibration strategies applied to anomaly detectors. Subclasses must implement the core calibration logic and define how calibration data is identified and used.
Attributes:
Name | Type | Description |
---|---|---|
_plus |
bool
|
A flag, typically set during initialization, that may influence calibration behavior in subclasses (e.g., by applying an adjustment). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
plus
|
bool
|
A flag that enables the "plus" variant which
maintains statistical validity by retaining calibration models for
inference. Strongly recommended for proper conformal guarantees.
Defaults to |
True
|
Source code in nonconform/strategy/base.py
calibration_ids
abstractmethod
property
¶
Provides the indices of the data points used for calibration.
This abstract property must be implemented by subclasses. It should
return a list of integer indices identifying which samples from the
original input data (provided to fit_calibrate
) were selected or
designated as the calibration set.
Returns:
Type | Description |
---|---|
list[int]
|
List[int]: A list of integer indices for the calibration data. |
Raises:
Type | Description |
---|---|
NotImplementedError
|
If the subclass does not implement this property. |
fit_calibrate
abstractmethod
¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fits the detector and performs calibration.
This abstract method must be implemented by subclasses to define the
specific procedure for fitting the anomaly detector (if necessary)
and then calibrating it using data derived from x
. Calibration often
involves determining thresholds or adjusting scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The input data, which may be used for both fitting the detector and deriving calibration data. |
required |
detector
|
BaseDetector
|
The PyOD anomaly detection model to be fitted and/or calibrated. |
required |
weighted
|
bool | None
|
A flag indicating whether a weighted approach should be used during calibration, if applicable to the subclass implementation. |
False
|
seed
|
int | None
|
A random seed for ensuring reproducibility in stochastic parts of the fitting or calibration process. Defaults to None. |
None
|
iteration_callback
|
callable | None
|
Optional callback function for strategies that support iteration tracking. Defaults to None. |
None
|
Raises:
Type | Description |
---|---|
NotImplementedError
|
If the subclass does not implement this method. |
Source code in nonconform/strategy/base.py
cross_val ¶
CrossValidation ¶
Bases: BaseStrategy
Implements k-fold cross-validation for conformal anomaly detection.
This strategy splits the data into k folds and uses each fold as a calibration set while training on the remaining folds. This approach provides more robust calibration scores by utilizing all available data. The strategy can operate in two modes: 1. Standard mode: Uses a single model trained on all data for prediction 2. Plus mode: Uses an ensemble of k models, each trained on k-1 folds
Attributes:
Name | Type | Description |
---|---|---|
_k |
int
|
Number of folds for cross-validation |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors |
_calibration_set |
list[float]
|
List of calibration scores |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
k
|
int
|
The number of folds for cross-validation. Must be at least 2. Higher values provide more robust calibration but increase computational cost. |
required |
plus
|
bool
|
If |
True
|
Source code in nonconform/strategy/cross_val.py
calibration_ids
property
¶
Returns a copy of the list of indices from x
used for calibration.
In k-fold cross-validation, every sample in the input data x
is
used exactly once as part of a calibration set (when its fold is
the hold-out set). This property returns a list of all these indices,
typically covering all indices from 0 to len(x)-1, but ordered by
fold processing.
Returns:
Type | Description |
---|---|
list[int]
|
list[int]: A copy of integer indices. |
Note
Returns a defensive copy to prevent external modification of internal state.
k
property
¶
Returns the number of folds for cross-validation.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of folds specified during initialization. |
plus
property
¶
Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate the detector using k-fold cross-validation.
This method implements the cross-validation strategy by: 1. Splitting the data into k folds 2. For each fold: - Train the detector on k-1 folds - Use the remaining fold for calibration - Store calibration scores and optionally the trained model 3. If not in plus mode, train a final model on all data
The method ensures that each sample is used exactly once for calibration, providing a more robust estimate of the calibration scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
weighted
|
bool
|
Whether to use weighted calibration. Currently not implemented for cross-validation. Defaults to False. |
False
|
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
iteration_callback
|
callable
|
Not used in CrossValidation strategy. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detectors (either k models in plus mode or a single model in standard mode) * Array of calibration scores from all folds |
Raises:
Type | Description |
---|---|
ValueError
|
If k is less than 2 or if the data size is too small for the specified number of folds. |
Source code in nonconform/strategy/cross_val.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
|
experimental ¶
bootstrap ¶
Bootstrap ¶
Bootstrap(
resampling_ratio: float | None = None,
n_bootstraps: int | None = None,
n_calib: int | None = None,
plus: bool = True,
)
Bases: BaseStrategy
Implements bootstrap-based conformal anomaly detection.
This strategy uses bootstrap resampling to create multiple training sets and calibration sets. For each bootstrap iteration: 1. A random subset of the data is sampled with replacement for training 2. The remaining samples are used for calibration 3. Optionally, a fixed number of calibration samples can be selected
The strategy can operate in two modes: 1. Standard mode: Uses a single model trained on all data for prediction 2. Plus mode: Uses an ensemble of models, each trained on a bootstrap sample
Attributes:
Name | Type | Description |
---|---|---|
_resampling_ratio |
float
|
Proportion of data to use for training in each bootstrap iteration |
_n_bootstraps |
int
|
Number of bootstrap iterations |
_n_calib |
int | None
|
Optional fixed number of calibration samples to use |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors |
_calibration_set |
list[float]
|
List of calibration scores |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
Exactly two of resampling_ratio
, n_bootstraps
, and n_calib
should be provided. The third will be calculated by _configure
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
resampling_ratio
|
float | None
|
The proportion of
data to use for training in each bootstrap. Defaults to |
None
|
n_bootstraps
|
int | None
|
The number of bootstrap
iterations. Defaults to |
None
|
n_calib
|
int | None
|
The desired size of the final
calibration set. If set, collected scores/IDs might be
subsampled. Defaults to |
None
|
plus
|
bool
|
If |
True
|
Source code in nonconform/strategy/experimental/bootstrap.py
property
¶Returns a copy of the list of indices used for calibration.
These are indices relative to the original input data x
provided to
:meth:fit_calibrate
. The list contains indices of all out-of-bag
samples encountered during bootstrap iterations. If _n_calib
was
set and weighted
was True
in fit_calibrate
, this list might
be a subsample of all encountered IDs, corresponding to the
subsampled _calibration_set
.
Returns:
Type | Description |
---|---|
list[int]
|
List[int]: A copy of integer indices. |
Note
Returns a defensive copy to prevent external modification of internal state.
property
¶Returns the resampling ratio.
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
Proportion of data used for training in each bootstrap iteration. |
property
¶Returns the number of bootstrap iterations.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of bootstrap iterations. |
property
¶Returns the target calibration set size.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Target number of calibration samples. |
property
¶Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback: Callable[[int, ndarray], None]
| None = None,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate the detector using bootstrap resampling.
This method implements the bootstrap strategy by: 1. Creating multiple bootstrap samples of the data 2. For each bootstrap iteration: - Train the detector on the bootstrap sample - Use the out-of-bootstrap samples for calibration - Store calibration scores and optionally the trained model 3. If not in plus mode, train a final model on all data 4. Optionally subsample the calibration set to a fixed size
The method provides robust calibration scores by using multiple bootstrap iterations, which helps account for the variability in the data and model training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
weighted
|
bool
|
Whether to use weighted calibration. If True, calibration scores are weighted by their sample indices. Defaults to False. |
False
|
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
iteration_callback
|
Callable[[int, ndarray], None]
|
Optional callback function that gets called after each bootstrap iteration with the iteration number and calibration scores. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detectors (either n_bootstraps models in plus mode or a single model in standard mode) * Array of calibration scores from all bootstrap iterations |
Raises:
Type | Description |
---|---|
ValueError
|
If resampling_ratio is not between 0 and 1, or if n_bootstraps is less than 1, or if n_calib is less than 1 when specified. |
Source code in nonconform/strategy/experimental/bootstrap.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
|
randomized ¶
Randomized ¶
Randomized(
n_iterations: int | None = None,
n_calib: int | None = None,
sampling_distr: Distribution = Distribution.UNIFORM,
holdout_size_range: tuple[float, float] | None = None,
beta_params: tuple[float, float] | None = None,
grid_probs: tuple[list[int], list[float]] | None = None,
plus: bool = True,
)
Bases: BaseStrategy
Implements randomized leave-p-out (rLpO) conformal anomaly detection.
This strategy uses randomized leave-p-out resampling where on each iteration a validation set size p is drawn at random, then a size-p validation set is sampled without replacement, the detector is trained on the rest, and calibration scores are computed. This approach smoothly interpolates between leave-one-out (p=1) and larger holdout strategies.
The strategy can operate in two modes: 1. Standard mode: Uses a single model trained on all data for prediction 2. Plus mode: Uses an ensemble of models, each trained on a different subset
Attributes:
Name | Type | Description |
---|---|---|
_sampling_distr |
Distribution
|
Distribution type for drawing holdout sizes |
_n_iterations |
int | None
|
Number of rLpO iterations |
_holdout_size_range |
tuple
|
Range of holdout sizes (relative or absolute) |
_beta_params |
tuple
|
Alpha and beta parameters for beta distribution |
_grid_probs |
tuple
|
Holdout sizes and probabilities for grid distribution |
_n_calib |
int | None
|
Target number of calibration samples |
_use_n_calib_mode |
bool
|
Whether to use n_calib mode vs n_iterations mode |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors |
_calibration_set |
list[float]
|
List of calibration scores |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_iterations
|
int | None
|
Number of rLpO iterations to perform. Cannot be used together with n_calib. Defaults to None. |
None
|
n_calib
|
int | None
|
Target number of calibration samples. Iterations will stop when this target is reached or exceeded, then subsample to exactly this size. Cannot be used with n_iterations. Defaults to None. |
None
|
sampling_distr
|
Distribution
|
Distribution for drawing holdout set sizes. Options: Distribution.BETA_BINOMIAL, Distribution.UNIFORM, Distribution.GRID. Defaults to Distribution.UNIFORM. |
UNIFORM
|
holdout_size_range
|
tuple[float, float]
|
Min and max holdout set sizes. Values in ]0, 1[ are interpreted as fractions of dataset size. Values >= 1 are interpreted as absolute sample counts. If None, defaults to (0.1, 0.5) for relative sizing. Defaults to None. |
None
|
beta_params
|
tuple[float, float]
|
Alpha and beta parameters for Beta distribution used to draw holdout size fractions. If None and sampling_distr is BETA_BINOMIAL, defaults to (2.0, 5.0). Common parameterizations: - (1.0, 1.0): Uniform sampling (equivalent to UNIFORM distribution) - (2.0, 5.0): Right-skewed, favors smaller holdout sizes [DEFAULT] - (5.0, 2.0): Left-skewed, favors larger holdout sizes - (2.0, 2.0): Bell-shaped, concentrated around middle sizes - (0.5, 0.5): U-shaped, concentrated at extremes Defaults to None. |
None
|
grid_probs
|
tuple[list[int], list[float]]
|
Holdout sizes and corresponding probabilities for grid distribution. Required if sampling_distr is Distribution.GRID. Defaults to None. |
None
|
plus
|
bool
|
If True, uses ensemble of models trained on different subsets. If False, uses single model trained on all data. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If required parameters for the chosen distribution are missing, if both n_iterations and n_calib are specified, or neither. |
Source code in nonconform/strategy/experimental/randomized.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
|
property
¶Returns a copy of the list of indices used for calibration.
These are indices relative to the original input data x
provided to
:meth:fit_calibrate
. The list contains indices of all holdout
samples encountered during rLpO iterations.
Returns:
Type | Description |
---|---|
list[int]
|
list[int]: A copy of integer indices for calibration samples. |
Note
Returns a defensive copy to prevent external modification of internal state.
property
¶Returns the number of iterations.
Returns:
Type | Description |
---|---|
int | None
|
int | None: Number of iterations, or None if using n_calib mode. |
property
¶Returns the target calibration set size.
Returns:
Type | Description |
---|---|
int | None
|
int | None: Target number of calibration samples, |
int | None
|
or None if using n_iterations mode. |
property
¶Returns the sampling distribution type.
Returns:
Name | Type | Description |
---|---|---|
Distribution |
Distribution
|
Distribution used for drawing holdout sizes. |
property
¶Returns the holdout size range.
Returns:
Type | Description |
---|---|
tuple[float, float]
|
tuple[float, float]: Min and max holdout set sizes. |
property
¶Returns the beta distribution parameters.
Returns:
Type | Description |
---|---|
tuple[float, float] | None
|
tuple[float, float] | None: Alpha and beta parameters, |
tuple[float, float] | None
|
or None if not using beta distribution. |
property
¶Returns the grid probabilities.
Returns:
Type | Description |
---|---|
tuple[list[int], list[float]] | None
|
tuple[list[int], list[float]] | None: Holdout sizes and probabilities, or None if not using grid distribution. |
property
¶Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback: Callable[[int, ndarray], None]
| None = None,
track_p_values: bool = False,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate the detector using randomized leave-p-out resampling.
This method implements the rLpO strategy by: 1. For each iteration, drawing a random holdout set size 2. Sampling a holdout set of that size without replacement 3. Training the detector on the remaining samples 4. Computing calibration scores on the holdout set 5. Optionally storing the trained model (in plus mode) 6. If using n_calib mode, stopping when target calibration size is reached
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
weighted
|
bool
|
Whether to store calibration sample indices. Defaults to False. |
False
|
iteration_callback
|
Callable[[int, ndarray], None]
|
Optional callback function called after each iteration with the iteration number and calibration scores. Defaults to None. |
None
|
track_p_values
|
bool
|
If True, stores the holdout sizes and per-iteration scores for performance analysis. Can be accessed via get_iteration_info(). Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detectors (either multiple models in plus mode or a single model in standard mode) * Array of calibration scores from all iterations |
Raises:
Type | Description |
---|---|
ValueError
|
If holdout set size would leave insufficient training data. |
Source code in nonconform/strategy/experimental/randomized.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
|
Get holdout sizes and per-iteration scores if tracking was enabled.
This method provides access to the holdout set sizes used in each iteration and the corresponding anomaly scores. This information can be used for performance analysis, plotting vs. holdout size, or understanding the distribution of holdout set sizes used.
Returns:
Type | Description |
---|---|
tuple[list[int], list[list[float]]] | None
|
tuple[list[int], list[list[float]]] | None: A tuple containing: * List of holdout sizes for each iteration * List of score arrays, one per iteration Returns None if track_p_values was False during fit_calibrate. |
Example
from nonconform.utils.func.enums import Distribution strategy = Randomized(n_calib=1000) strategy.fit_calibrate(X, detector, track_p_values=True) holdout_sizes, scores = strategy.get_iteration_info()
holdout_sizes[i] is the holdout set size for iteration i¶
scores[i] are the anomaly scores for iteration i¶
Source code in nonconform/strategy/experimental/randomized.py
jackknife ¶
Jackknife ¶
Bases: BaseStrategy
Jackknife (leave-one-out) conformal anomaly detection strategy.
This strategy implements conformal prediction using the jackknife method, which is a special case of k-fold cross-validation where k equals the number of samples in the dataset (leave-one-out). For each sample, a model is trained on all other samples, and the left-out sample is used for calibration.
It internally uses a :class:~nonconform.strategy.cross_val.CrossValidation
strategy, dynamically setting its _k
parameter to the dataset size.
Attributes:
Name | Type | Description |
---|---|---|
_plus |
bool
|
If |
_strategy |
CrossValidation
|
An instance of the
:class: |
_calibration_ids |
list[int] | None
|
Indices of the samples from
the input data |
_detector_list |
List[BaseDetector]
|
A list of trained detector models,
populated by :meth: |
_calibration_set |
ndarray
|
An array of calibration scores, one for
each sample, populated by :meth: |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
plus
|
bool
|
If |
True
|
Source code in nonconform/strategy/jackknife.py
calibration_ids
property
¶
Returns a copy of indices from x
used for calibration via jackknife.
These are the indices of samples used to obtain calibration scores.
In jackknife (leave-one-out), each sample is used once for
calibration. The list is populated after fit_calibrate
is called.
Returns:
Type | Description |
---|---|
list[int] | None
|
list[int] | None: A copy of integer indices, or |
Note
Returns a defensive copy to prevent external modification of internal state.
plus
property
¶
Returns whether the plus variant is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if using ensemble mode, False if using single model. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
weighted: bool = False,
seed: int | None = None,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fits detector(s) and gets calibration scores using jackknife.
This method configures the internal
:class:~nonconform.strategy.cross_val.CrossValidation
strategy to
perform leave-one-out cross-validation by setting its number of
folds (_k
) to the total number of samples in x
. It then delegates
the fitting and calibration process to this internal strategy.
The results (trained models and calibration scores) and calibration sample IDs are retrieved from the internal strategy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The input data. |
required |
detector
|
BaseDetector
|
The PyOD base detector instance. |
required |
weighted
|
bool
|
Passed to the internal |
False
|
seed
|
int | None
|
Random seed, passed to the internal
|
None
|
iteration_callback
|
callable
|
Not used in Jackknife strategy. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], np.ndarray]: A tuple containing:
* A list of trained PyOD detector models.
* An array of calibration scores (one per sample in |
Source code in nonconform/strategy/jackknife.py
jackknife_bootstrap ¶
JackknifeBootstrap ¶
JackknifeBootstrap(
n_bootstraps: int = 100,
aggregation_method: Aggregation = Aggregation.MEAN,
plus: bool = True,
)
Bases: BaseStrategy
Implements Jackknife+-after-Bootstrap (JaB+) conformal anomaly detection.
This strategy implements the JaB+ method which provides predictive inference for ensemble models trained on bootstrap samples. The key insight is that JaB+ uses the out-of-bag (OOB) samples from bootstrap iterations to compute calibration scores without requiring additional model training.
The strategy can operate in two modes: 1. Plus mode (plus=True): Uses ensemble of models for prediction (recommended) 2. Standard mode (plus=False): Uses single model trained on all data
Attributes:
Name | Type | Description |
---|---|---|
_n_bootstraps |
int
|
Number of bootstrap iterations |
_aggregation_method |
Aggregation
|
How to aggregate OOB predictions |
_plus |
bool
|
Whether to use the plus variant (ensemble of models) |
_detector_list |
list[BaseDetector]
|
List of trained detectors (ensemble/single) |
_calibration_set |
list[float]
|
List of calibration scores from JaB+ procedure |
_calibration_ids |
list[int]
|
Indices of samples used for calibration |
_bootstrap_models |
list[BaseDetector]
|
Models trained on each bootstrap sample |
_oob_mask |
ndarray
|
Boolean matrix of shape (n_bootstraps, n_samples) indicating out-of-bag status |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_bootstraps
|
int
|
Number of bootstrap iterations. Defaults to 100. |
100
|
aggregation_method
|
Aggregation
|
Method to aggregate out-of-bag predictions. Options are Aggregation.MEAN or Aggregation.MEDIAN. Defaults to Aggregation.MEAN. |
MEAN
|
plus
|
bool
|
If True, uses ensemble of bootstrap models for prediction (maintains statistical validity). If False, uses single model trained on all data. Strongly recommended to use True. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
ValueError
|
If aggregation_method is not a valid Aggregation enum value. |
ValueError
|
If n_bootstraps is less than 1. |
Source code in nonconform/strategy/jackknife_bootstrap.py
calibration_ids
property
¶
Returns a copy of the list of indices used for calibration.
In JaB+, all original training samples contribute to calibration through the out-of-bag mechanism.
Returns:
Type | Description |
---|---|
list[int]
|
list[int]: Copy of integer indices (0 to n_samples-1). |
Note
Returns a defensive copy to prevent external modification of internal state.
aggregation_method
property
¶
Returns the aggregation method used for OOB predictions.
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
seed: int | None = None,
weighted: bool = False,
iteration_callback: Callable[[int, ndarray], None]
| None = None,
n_jobs: int | None = None,
) -> tuple[list[BaseDetector], np.ndarray]
Fit and calibrate using Jackknife+-after-Bootstrap method.
This method implements the JaB+ algorithm: 1. Generate bootstrap samples and train models 2. For each sample, compute out-of-bag predictions 3. Aggregate OOB predictions to get calibration scores 4. Train final model on all data
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
Input data matrix of shape (n_samples, n_features). |
required |
detector
|
BaseDetector
|
The base anomaly detector to be used. |
required |
seed
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
weighted
|
bool
|
Not used in JaB+ method. Defaults to False. |
False
|
iteration_callback
|
Callable[[int, ndarray], None]
|
Optional callback function that gets called after each bootstrap iteration with the iteration number and current calibration scores. Defaults to None. |
None
|
n_jobs
|
int
|
Number of parallel jobs for bootstrap training. If None, uses sequential processing. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], list[float]]: A tuple containing: * List of trained detector models (if plus=True, single if plus=False) * Array of calibration scores from JaB+ procedure |
Source code in nonconform/strategy/jackknife_bootstrap.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
|
split ¶
Split ¶
Bases: BaseStrategy
Split conformal strategy for fast anomaly detection with statistical guarantees.
Implements the classical split conformal approach by dividing training data into separate fitting and calibration sets. This provides the fastest conformal inference at the cost of using less data for calibration compared to other strategies.
Example
Attributes:
Name | Type | Description |
---|---|---|
_calib_size |
float | int
|
Size or proportion of data used for calibration. |
_calibration_ids |
list[int] | None
|
Indices of calibration samples (for weighted conformal). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_calib
|
float | int
|
The size or proportion
of the dataset to use for the calibration set. If a float,
it must be between 0.0 and 1.0 (exclusive of 0.0 and 1.0
in practice for |
0.1
|
Source code in nonconform/strategy/split.py
calibration_ids
property
¶
Returns a copy of indices from x
used for the calibration set.
This property provides the list of indices corresponding to the samples
that were allocated to the calibration set during the fit_calibrate
method. It will be None
if fit_calibrate
was called with
weighted=False
or if fit_calibrate
has not yet been called.
Returns:
Type | Description |
---|---|
list[int] | None
|
list[int] | None: A copy of integer indices, or |
Note
Returns a defensive copy to prevent external modification of internal state.
calib_size
property
¶
Returns the calibration size or proportion.
Returns:
Type | Description |
---|---|
float | int
|
float | int: The calibration size as specified during initialization. If float (0.0-1.0), represents proportion of data. If int, represents absolute number of samples. |
fit_calibrate ¶
fit_calibrate(
x: DataFrame | ndarray,
detector: BaseDetector,
weighted: bool = False,
seed: int | None = None,
iteration_callback=None,
) -> tuple[list[BaseDetector], np.ndarray]
Fits a detector and generates calibration scores using a data split.
The input data x
is split into a training set and a calibration
set according to _calib_size
. The provided detector
is trained
on the training set. Non-conformity scores are then computed using
the trained detector on the calibration set.
If weighted
is True
, the indices of the calibration samples
are stored in _calibration_ids
. Otherwise, _calibration_ids
remains None
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
DataFrame | ndarray
|
The input data. |
required |
detector
|
BaseDetector
|
The PyOD base detector instance to train. This instance is modified in place by fitting. |
required |
weighted
|
bool
|
If |
False
|
seed
|
int | None
|
Random seed for reproducibility of the train-test split. Defaults to None. |
None
|
iteration_callback
|
callable
|
Not used in Split strategy. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
tuple[list[BaseDetector], ndarray]
|
tuple[list[BaseDetector], np.ndarray]: A tuple containing: * A list containing the single trained PyOD detector instance. * An array of calibration scores from the calibration set. |
Source code in nonconform/strategy/split.py
Utils¶
nonconform.utils ¶
Utility modules for nonconform.
This module provides data handling, functional programming utilities, and statistical functions used throughout the nonconform package.
data ¶
Data utilities for nonconform.
Dataset ¶
Bases: Enum
Available datasets for anomaly detection experiments.
This enumeration provides all built-in datasets that can be loaded using the load() function. Each dataset is preprocessed for anomaly detection tasks with normal and anomalous samples.
Usage
from nonconform.utils.data import load, Dataset df = load(Dataset.FRAUD, setup=True, seed=42)
DatasetInfo
dataclass
¶
DatasetInfo(
name: str,
description: str,
filename: str,
samples: int,
features: int,
anomaly_rate: float,
)
Metadata for a dataset.
clear_cache ¶
Clear dataset cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
str | None
|
Specific dataset name to clear. If None, clears all. |
None
|
all_versions
|
bool
|
If True, clears cache for all dataset versions. |
False
|
Examples:
>>> clear_cache("breast") # Clear specific dataset
>>> clear_cache() # Clear all datasets
>>> clear_cache(all_versions=True) # Clear all versions
Source code in nonconform/utils/data/load.py
get_cache_location ¶
Get the cache directory path.
Returns:
Type | Description |
---|---|
str
|
String path to the cache directory. |
Examples:
Source code in nonconform/utils/data/load.py
get_info ¶
Get detailed metadata for a specific dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
Dataset
|
The dataset to get info for (use Dataset enum values). |
required |
Returns:
Type | Description |
---|---|
DatasetInfo
|
DatasetInfo object with dataset metadata. |
Examples:
>>> from nonconform.utils.data import Dataset
>>> info = get_info(Dataset.BREAST)
>>> print(info.description)
Source code in nonconform/utils/data/load.py
list_available ¶
Get a list of all available dataset names.
Returns:
Type | Description |
---|---|
list[str]
|
Sorted list of dataset names. |
Examples:
Source code in nonconform/utils/data/load.py
generator ¶
Data generators for conformal anomaly detection.
This module provides batch and online data generators for streaming and batch processing scenarios in conformal anomaly detection.
BaseDataGenerator ¶
BaseDataGenerator(
load_data_func: Callable[[], DataFrame],
anomaly_proportion: float,
anomaly_mode: Literal[
"proportional", "probabilistic"
] = "proportional",
n_batches: int | None = None,
train_size: float = 0.5,
seed: int | None = None,
)
Bases: ABC
Abstract base class for data generators with anomaly contamination.
This class defines the interface for generating data with controlled anomaly contamination. It supports both batch and online generation modes with different anomaly proportion control strategies.
load_data_func : Callable[[], pd.DataFrame] Function from nonconform.utils.data.load (e.g., load_shuttle, load_breast). anomaly_proportion : float Target proportion of anomalies (0.0 to 1.0). anomaly_mode : {"proportional", "probabilistic"}, default="proportional" How to control anomaly proportions: - "proportional": Fixed proportion per batch/instance - "probabilistic": Probabilistic with global target over all items n_batches : int, optional Number of batches/instances for "probabilistic" mode. Required when anomaly_mode="probabilistic". train_size : float, default=0.5 Proportion of normal instances to use for training. seed : int, optional Seed for random number generator.
x_train : pd.DataFrame Training data (normal instances only). x_normal : pd.DataFrame Normal instances for generation. x_anomaly : pd.DataFrame Anomalous instances for generation. n_normal : int Number of normal instances available. n_anomaly : int Number of anomalous instances available. rng : np.random.Generator Random number generator.
Source code in nonconform/utils/data/generator/base.py
Get training data (normal instances only).
pd.DataFrame Training data without anomalies.
Reset the generator to initial state.
abstractmethod
¶Generate data items.
This method must be implemented by subclasses to define the specific generation behavior (batch vs online).
BatchGenerator ¶
BatchGenerator(
load_data_func: Callable[[], DataFrame],
batch_size: int,
anomaly_proportion: float,
anomaly_mode: Literal[
"proportional", "probabilistic"
] = "proportional",
n_batches: int | None = None,
train_size: float = 0.5,
seed: int | None = None,
)
Bases: BaseDataGenerator
Generate batches with configurable anomaly contamination.
load_data_func : Callable[[], pd.DataFrame] Function from nonconform.utils.data.load (e.g., load_shuttle). batch_size : int Number of instances per batch. anomaly_proportion : float Target proportion of anomalies (0.0 to 1.0). anomaly_mode : {"proportional", "probabilistic"}, default="proportional" How to control anomaly proportions. n_batches : int, optional Number of batches to generate. - Required for "probabilistic" mode - Optional for "proportional" mode (if None, generates indefinitely) train_size : float, default=0.5 Proportion of normal instances to use for training. seed : int, optional Seed for random number generator.
Examples:
from nonconform.utils.data.load import load_shuttle from nonconform.utils.data.generator import BatchGenerator
Proportional mode - 10% anomalies per batch¶
batch_gen = BatchGenerator( ... load_data_func=load_shuttle, batch_size=100, anomaly_proportion=0.1, seed=42 ... )
Proportional mode with limited batches - 10% anomalies for exactly 5 batches¶
batch_gen = BatchGenerator( ... load_data_func=load_shuttle, ... batch_size=100, ... anomaly_proportion=0.1, ... anomaly_mode="proportional", ... n_batches=5, ... seed=42, ... )
Probabilistic mode - 5% anomalies across 10 batches¶
batch_gen = BatchGenerator( ... load_data_func=load_shuttle, ... batch_size=100, ... anomaly_proportion=0.05, ... anomaly_mode="probabilistic", ... n_batches=10, ... seed=42, ... )
Get training data¶
x_train = batch_gen.get_training_data()
Generate batches (infinite for proportional mode)¶
for i, (x_batch, y_batch) in enumerate(batch_gen.generate()): ... print(f"Batch: {x_batch.shape}, Anomalies: {y_batch.sum()}") ... if i >= 4: # Stop after 5 batches ... break
Proportional mode with n_batches - automatic stopping after 5 batches¶
for x_batch, y_batch in batch_gen.generate(): ... print(f"Batch: {x_batch.shape}, Anomalies: {y_batch.sum()}")
Probabilistic mode - automatic stopping after n_batches¶
for x_batch, y_batch in batch_gen.generate(): ... print(f"Batch: {x_batch.shape}, Anomalies: {y_batch.sum()}")
Source code in nonconform/utils/data/generator/batch.py
Generate batches with mixed normal and anomalous instances.
- For proportional mode: generates batches indefinitely if n_batches=None, or exactly n_batches batches if specified in constructor
- For probabilistic mode: generates exactly n_batches batches (required in constructor)
x_batch : pd.DataFrame Feature matrix for the batch. y_batch : pd.Series Labels for the batch (0=normal, 1=anomaly).
Source code in nonconform/utils/data/generator/batch.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
OnlineGenerator ¶
OnlineGenerator(
load_data_func: Callable[[], DataFrame],
anomaly_proportion: float,
n_instances: int,
train_size: float = 0.5,
seed: int | None = None,
)
Bases: BaseDataGenerator
Generate single instances with probabilistic anomaly contamination for streaming.
Online generators use probabilistic anomaly control to ensure exact global proportion over a specified number of instances.
load_data_func : Callable[[], pd.DataFrame] Function from nonconform.utils.data.load (e.g., load_shuttle). anomaly_proportion : float Target proportion of anomalies (0.0 to 1.0). n_instances : int Number of instances to ensure exact global proportion. train_size : float, default=0.5 Proportion of normal instances to use for training. seed : int, optional Seed for random number generator.
Examples:
from nonconform.utils.data.load import load_shuttle from nonconform.utils.data.generator import OnlineGenerator
Exactly 1% anomalies over 1000 instances¶
online_gen = OnlineGenerator( ... load_data_func=load_shuttle, ... anomaly_proportion=0.01, ... n_instances=1000, ... seed=42, ... )
Get training data¶
x_train = online_gen.get_training_data()
Generate instances - exactly 10 anomalies in 1000 instances¶
for x_instance, y_label in online_gen.generate(n_instances=1000): ... print(f"Instance: {x_instance.shape}, Label: {y_label}")
Source code in nonconform/utils/data/generator/online.py
Generate stream of single instances with exact anomaly proportion.
n_instances : int, optional Number of instances to generate. If None, generates up to max_instances.
x_instance : pd.DataFrame Single instance feature vector. y_label : int Label for the instance (0=normal, 1=anomaly).
Source code in nonconform/utils/data/generator/online.py
base ¶
Abstract base class for data generators with anomaly contamination control.
BaseDataGenerator(
load_data_func: Callable[[], DataFrame],
anomaly_proportion: float,
anomaly_mode: Literal[
"proportional", "probabilistic"
] = "proportional",
n_batches: int | None = None,
train_size: float = 0.5,
seed: int | None = None,
)
Bases: ABC
Abstract base class for data generators with anomaly contamination.
This class defines the interface for generating data with controlled anomaly contamination. It supports both batch and online generation modes with different anomaly proportion control strategies.
load_data_func : Callable[[], pd.DataFrame] Function from nonconform.utils.data.load (e.g., load_shuttle, load_breast). anomaly_proportion : float Target proportion of anomalies (0.0 to 1.0). anomaly_mode : {"proportional", "probabilistic"}, default="proportional" How to control anomaly proportions: - "proportional": Fixed proportion per batch/instance - "probabilistic": Probabilistic with global target over all items n_batches : int, optional Number of batches/instances for "probabilistic" mode. Required when anomaly_mode="probabilistic". train_size : float, default=0.5 Proportion of normal instances to use for training. seed : int, optional Seed for random number generator.
x_train : pd.DataFrame Training data (normal instances only). x_normal : pd.DataFrame Normal instances for generation. x_anomaly : pd.DataFrame Anomalous instances for generation. n_normal : int Number of normal instances available. n_anomaly : int Number of anomalous instances available. rng : np.random.Generator Random number generator.
Source code in nonconform/utils/data/generator/base.py
Get training data (normal instances only).
pd.DataFrame Training data without anomalies.
Reset the generator to initial state.
abstractmethod
¶Generate data items.
This method must be implemented by subclasses to define the specific generation behavior (batch vs online).
batch ¶
BatchGenerator(
load_data_func: Callable[[], DataFrame],
batch_size: int,
anomaly_proportion: float,
anomaly_mode: Literal[
"proportional", "probabilistic"
] = "proportional",
n_batches: int | None = None,
train_size: float = 0.5,
seed: int | None = None,
)
Bases: BaseDataGenerator
Generate batches with configurable anomaly contamination.
load_data_func : Callable[[], pd.DataFrame] Function from nonconform.utils.data.load (e.g., load_shuttle). batch_size : int Number of instances per batch. anomaly_proportion : float Target proportion of anomalies (0.0 to 1.0). anomaly_mode : {"proportional", "probabilistic"}, default="proportional" How to control anomaly proportions. n_batches : int, optional Number of batches to generate. - Required for "probabilistic" mode - Optional for "proportional" mode (if None, generates indefinitely) train_size : float, default=0.5 Proportion of normal instances to use for training. seed : int, optional Seed for random number generator.
Examples:
from nonconform.utils.data.load import load_shuttle from nonconform.utils.data.generator import BatchGenerator
Proportional mode - 10% anomalies per batch¶
batch_gen = BatchGenerator( ... load_data_func=load_shuttle, batch_size=100, anomaly_proportion=0.1, seed=42 ... )
Proportional mode with limited batches - 10% anomalies for exactly 5 batches¶
batch_gen = BatchGenerator( ... load_data_func=load_shuttle, ... batch_size=100, ... anomaly_proportion=0.1, ... anomaly_mode="proportional", ... n_batches=5, ... seed=42, ... )
Probabilistic mode - 5% anomalies across 10 batches¶
batch_gen = BatchGenerator( ... load_data_func=load_shuttle, ... batch_size=100, ... anomaly_proportion=0.05, ... anomaly_mode="probabilistic", ... n_batches=10, ... seed=42, ... )
Get training data¶
x_train = batch_gen.get_training_data()
Generate batches (infinite for proportional mode)¶
for i, (x_batch, y_batch) in enumerate(batch_gen.generate()): ... print(f"Batch: {x_batch.shape}, Anomalies: {y_batch.sum()}") ... if i >= 4: # Stop after 5 batches ... break
Proportional mode with n_batches - automatic stopping after 5 batches¶
for x_batch, y_batch in batch_gen.generate(): ... print(f"Batch: {x_batch.shape}, Anomalies: {y_batch.sum()}")
Probabilistic mode - automatic stopping after n_batches¶
for x_batch, y_batch in batch_gen.generate(): ... print(f"Batch: {x_batch.shape}, Anomalies: {y_batch.sum()}")
Source code in nonconform/utils/data/generator/batch.py
Generate batches with mixed normal and anomalous instances.
- For proportional mode: generates batches indefinitely if n_batches=None, or exactly n_batches batches if specified in constructor
- For probabilistic mode: generates exactly n_batches batches (required in constructor)
x_batch : pd.DataFrame Feature matrix for the batch. y_batch : pd.Series Labels for the batch (0=normal, 1=anomaly).
Source code in nonconform/utils/data/generator/batch.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
online ¶
OnlineGenerator(
load_data_func: Callable[[], DataFrame],
anomaly_proportion: float,
n_instances: int,
train_size: float = 0.5,
seed: int | None = None,
)
Bases: BaseDataGenerator
Generate single instances with probabilistic anomaly contamination for streaming.
Online generators use probabilistic anomaly control to ensure exact global proportion over a specified number of instances.
load_data_func : Callable[[], pd.DataFrame] Function from nonconform.utils.data.load (e.g., load_shuttle). anomaly_proportion : float Target proportion of anomalies (0.0 to 1.0). n_instances : int Number of instances to ensure exact global proportion. train_size : float, default=0.5 Proportion of normal instances to use for training. seed : int, optional Seed for random number generator.
Examples:
from nonconform.utils.data.load import load_shuttle from nonconform.utils.data.generator import OnlineGenerator
Exactly 1% anomalies over 1000 instances¶
online_gen = OnlineGenerator( ... load_data_func=load_shuttle, ... anomaly_proportion=0.01, ... n_instances=1000, ... seed=42, ... )
Get training data¶
x_train = online_gen.get_training_data()
Generate instances - exactly 10 anomalies in 1000 instances¶
for x_instance, y_label in online_gen.generate(n_instances=1000): ... print(f"Instance: {x_instance.shape}, Label: {y_label}")
Source code in nonconform/utils/data/generator/online.py
Generate stream of single instances with exact anomaly proportion.
n_instances : int, optional Number of instances to generate. If None, generates up to max_instances.
x_instance : pd.DataFrame Single instance feature vector. y_label : int Label for the instance (0=normal, 1=anomaly).
Source code in nonconform/utils/data/generator/online.py
load ¶
Modern dataset loading module with DatasetManager architecture.
DatasetManager ¶
Manages dataset loading, caching, and metadata.
Source code in nonconform/utils/data/load.py
property
¶Returns the number of datasets cached in memory.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
Number of datasets currently in memory cache. |
property
¶Returns whether disk caching is enabled.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if cache directory exists and is writable. |
load(
dataset: Dataset,
setup: bool = False,
seed: int | None = None,
) -> (
pd.DataFrame
| tuple[pd.DataFrame, pd.DataFrame, pd.Series]
)
Load a dataset by enum value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
Dataset
|
The dataset to load (use Dataset enum values). |
required |
setup
|
bool
|
If True, splits the data into training and testing sets for anomaly detection tasks. |
False
|
seed
|
int | None
|
Random seed for data splitting if setup is True. |
None
|
Returns:
Type | Description |
---|---|
DataFrame | tuple[DataFrame, DataFrame, Series]
|
If setup is False, returns the complete dataset as a DataFrame. |
DataFrame | tuple[DataFrame, DataFrame, Series]
|
If setup is True, returns a tuple: (x_train, x_test, y_test). |
Raises:
Type | Description |
---|---|
ValueError
|
If the dataset is not found in the registry. |
URLError
|
If dataset download fails. |
Source code in nonconform/utils/data/load.py
Clear dataset cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
str | None
|
Specific dataset name to clear. If None, clears all. |
None
|
all_versions
|
bool
|
If True, clears cache for all dataset versions. |
False
|
Source code in nonconform/utils/data/load.py
Get a list of all available dataset names.
Returns:
Type | Description |
---|---|
list[str]
|
Sorted list of dataset names. |
Get metadata for a specific dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
Dataset
|
The dataset to get info for (use Dataset enum values). |
required |
Returns:
Type | Description |
---|---|
DatasetInfo
|
DatasetInfo object with dataset metadata. |
Raises:
Type | Description |
---|---|
ValueError
|
If the dataset is not found. |
Source code in nonconform/utils/data/load.py
Get the cache directory path.
Returns:
Type | Description |
---|---|
str
|
String path to the cache directory. |
load ¶
load(
dataset: Dataset,
setup: bool = False,
seed: int | None = None,
) -> (
pd.DataFrame
| tuple[pd.DataFrame, pd.DataFrame, pd.Series]
)
Load a benchmark anomaly detection dataset.
Provides access to curated datasets commonly used for anomaly detection research. Datasets are automatically downloaded and cached locally for efficient reuse.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
Dataset
|
Dataset to load using Dataset enum (e.g., Dataset.SHUTTLE, ...). |
required |
setup
|
bool
|
If True, automatically splits data for anomaly detection workflow. Returns (x_train, x_test, y_test), x_train contains only normal samples. |
False
|
seed
|
int | None
|
Random seed for reproducible train/test splitting when setup=True. |
None
|
Returns:
Type | Description |
---|---|
DataFrame | tuple[DataFrame, DataFrame, Series]
|
|
DataFrame | tuple[DataFrame, DataFrame, Series]
|
|
Examples:
Load complete dataset for exploration:
from nonconform.utils.data import load, Dataset
# Load full dataset with labels
df = load(Dataset.MAMMOGRAPHY)
print(f"Dataset shape: {df.shape}")
print(f"Anomaly rate: {df['label'].mean():.1%}")
Load split data ready for conformal detection:
# Get training/test split for anomaly detection
x_train, x_test, y_test = load(Dataset.SHUTTLE, setup=True, seed=42)
# x_train contains only normal samples for detector training
print(f"Training samples: {len(x_train)} (all normal)")
print(f"Test samples: {len(x_test)} ({np.sum(y_test)} anomalies)")
Available Datasets
Use list_available()
to see all available datasets, or check enum values:
Dataset.MAMMOGRAPHY, Dataset.SHUTTLE, Dataset.FRAUD, etc.
Source code in nonconform/utils/data/load.py
list_available ¶
Get a list of all available dataset names.
Returns:
Type | Description |
---|---|
list[str]
|
Sorted list of dataset names. |
Examples:
Source code in nonconform/utils/data/load.py
get_info ¶
Get detailed metadata for a specific dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
Dataset
|
The dataset to get info for (use Dataset enum values). |
required |
Returns:
Type | Description |
---|---|
DatasetInfo
|
DatasetInfo object with dataset metadata. |
Examples:
>>> from nonconform.utils.data import Dataset
>>> info = get_info(Dataset.BREAST)
>>> print(info.description)
Source code in nonconform/utils/data/load.py
clear_cache ¶
Clear dataset cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset
|
str | None
|
Specific dataset name to clear. If None, clears all. |
None
|
all_versions
|
bool
|
If True, clears cache for all dataset versions. |
False
|
Examples:
>>> clear_cache("breast") # Clear specific dataset
>>> clear_cache() # Clear all datasets
>>> clear_cache(all_versions=True) # Clear all versions
Source code in nonconform/utils/data/load.py
get_cache_location ¶
Get the cache directory path.
Returns:
Type | Description |
---|---|
str
|
String path to the cache directory. |
Examples:
Source code in nonconform/utils/data/load.py
func ¶
Functional programming utilities for nonconform.
This module provides decorators, enumerations, and parameter utilities used throughout the nonconform package.
Aggregation ¶
Bases: Enum
Aggregation functions for combining multiple model outputs or scores.
This enumeration lists strategies for aggregating data, commonly employed in ensemble methods to combine predictions or scores from several models.
Attributes:
Name | Type | Description |
---|---|---|
MEAN |
Represents aggregation by calculating the arithmetic mean.
The underlying value is typically |
|
MEDIAN |
Represents aggregation by calculating the median.
The underlying value is typically |
|
MINIMUM |
Represents aggregation by selecting the minimum value.
The underlying value is typically |
|
MAXIMUM |
Represents aggregation by selecting the maximum value.
The underlying value is typically |
decorator ¶
enums ¶
Distribution ¶
Bases: Enum
Probability distributions for validation set sizes in randomized strategies.
This enumeration defines the available distribution types for selecting validation set sizes in randomized leave-p-out conformal prediction strategies.
Attributes:
Name | Type | Description |
---|---|---|
BETA_BINOMIAL |
Beta-binomial distribution for drawing validation fractions. Allows tunable mean and variance through alpha/beta parameters. |
|
UNIFORM |
Discrete uniform distribution over a specified range. Simple and controlled selection within [p_min, p_max]. |
|
GRID |
Discrete distribution over a specified set of values. Targeted control with custom probabilities for each p value. |
Aggregation ¶
Bases: Enum
Aggregation functions for combining multiple model outputs or scores.
This enumeration lists strategies for aggregating data, commonly employed in ensemble methods to combine predictions or scores from several models.
Attributes:
Name | Type | Description |
---|---|---|
MEAN |
Represents aggregation by calculating the arithmetic mean.
The underlying value is typically |
|
MEDIAN |
Represents aggregation by calculating the median.
The underlying value is typically |
|
MINIMUM |
Represents aggregation by selecting the minimum value.
The underlying value is typically |
|
MAXIMUM |
Represents aggregation by selecting the maximum value.
The underlying value is typically |
Dataset ¶
Bases: Enum
Available datasets for anomaly detection experiments.
This enumeration provides all built-in datasets that can be loaded using the load() function. Each dataset is preprocessed for anomaly detection tasks with normal and anomalous samples.
Usage
from nonconform.utils.data import load, Dataset df = load(Dataset.FRAUD, setup=True, seed=42)
logger ¶
Logging utilities for the nonconform package.
get_logger ¶
Get a logger for the nonconform package.
name : str The name of the logger, typically the module name.
logging.Logger A logger instance for the nonconform package.
Notes: This function creates loggers with the naming convention "nonconform.{name}". By default, shows INFO level and above (INFO, WARNING, ERROR, CRITICAL). Users can control verbosity with standard logging: logging.getLogger("nonconform").setLevel(level).
Examples:
logger = get_logger("estimation.standard_conformal") logger.info("Calibration completed successfully")
To silence warnings:¶
logging.getLogger("nonconform").setLevel(logging.ERROR)
To enable debug:¶
logging.getLogger("nonconform").setLevel(logging.DEBUG)
Source code in nonconform/utils/func/logger.py
params ¶
Manages and configures anomaly detection models from the PyOD library.
This module provides utilities for setting up PyOD detector models, including handling a list of models that are restricted or unsupported for use with conformal anomaly detection.
Attributes:
Name | Type | Description |
---|---|---|
forbidden_model_list |
list[type[BaseDetector]]
|
A list of PyOD detector
classes that are considered unsupported or restricted for use by
the |
stat ¶
Statistical utilities for conformal anomaly detection.
This module provides statistical functions including aggregation methods, extreme value theory functions, evaluation metrics, and general statistical operations used in conformal prediction.
false_discovery_rate ¶
Calculate the False Discovery Rate (FDR) for binary classification.
The False Discovery Rate is the proportion of false positives among all instances predicted as positive. It is calculated as: FDR = FP / (FP + TP), where FP is false positives and TP is true positives. If the total number of predicted positives (FP + TP) is zero, FDR is defined as 0.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y
|
ndarray
|
True binary labels, where 1 indicates an actual positive (e.g., anomaly) and 0 indicates an actual negative (e.g., normal). |
required |
y_hat
|
ndarray
|
Predicted binary labels, where 1 indicates a predicted positive and 0 indicates a predicted negative. |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
The calculated False Discovery Rate. |
Source code in nonconform/utils/stat/metrics.py
statistical_power ¶
Calculate statistical power (recall or true positive rate).
Statistical power, also known as recall or true positive rate (TPR), measures the proportion of actual positives that are correctly identified by the classifier. It is calculated as: Power (TPR) = TP / (TP + FN), where TP is true positives and FN is false negatives. If the total number of actual positives (TP + FN) is zero, power is defined as 0.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y
|
ndarray
|
True binary labels, where 1 indicates an actual positive (e.g., anomaly) and 0 indicates an actual negative (e.g., normal). |
required |
y_hat
|
ndarray
|
Predicted binary labels, where 1 indicates a predicted positive and 0 indicates a predicted negative. |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
The calculated statistical power. |
Source code in nonconform/utils/stat/metrics.py
aggregate ¶
Aggregate anomaly scores using a specified method.
This function applies a chosen aggregation technique to a 2D array of anomaly scores, where each row typically represents scores from a different model or source, and each column corresponds to a data sample.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
Aggregation
|
The aggregation method to apply. Must be a
member of the :class: |
required |
scores
|
ndarray
|
A 2D NumPy array of anomaly scores.
It is expected that scores are arranged such that rows correspond
to different sets of scores (e.g., from different models) and
columns correspond to individual data points/samples.
Aggregation is performed along |
required |
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: An array of aggregated anomaly scores. The length of the
array will correspond to the number of columns in the input |
Raises:
Type | Description |
---|---|
ValueError
|
If the |
Source code in nonconform/utils/stat/aggregation.py
calculate_p_val ¶
Calculate p-values for scores based on a calibration set.
This function computes a p-value for each score in the scores
array by
comparing it against the distribution of scores in the calibration_set
.
The p-value represents the proportion of calibration scores that are
greater than or equal to the given score, with a small adjustment.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scores
|
ndarray
|
A 1D array of test scores for which p-values are to be calculated. |
required |
calibration_set
|
ndarray
|
A 1D array of calibration scores used as the reference distribution. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: An array of p-values, each corresponding to an input score
from |
Notes
The p-value for each score is computed using the formula:
p_value = (1 + count(calibration_score >= score)) / (1 + N_calibration)
where N_calibration is the total number of scores in calibration_set
.
Source code in nonconform/utils/stat/statistical.py
aggregation ¶
aggregate ¶
Aggregate anomaly scores using a specified method.
This function applies a chosen aggregation technique to a 2D array of anomaly scores, where each row typically represents scores from a different model or source, and each column corresponds to a data sample.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
Aggregation
|
The aggregation method to apply. Must be a
member of the :class: |
required |
scores
|
ndarray
|
A 2D NumPy array of anomaly scores.
It is expected that scores are arranged such that rows correspond
to different sets of scores (e.g., from different models) and
columns correspond to individual data points/samples.
Aggregation is performed along |
required |
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: An array of aggregated anomaly scores. The length of the
array will correspond to the number of columns in the input |
Raises:
Type | Description |
---|---|
ValueError
|
If the |
Source code in nonconform/utils/stat/aggregation.py
metrics ¶
false_discovery_rate ¶
Calculate the False Discovery Rate (FDR) for binary classification.
The False Discovery Rate is the proportion of false positives among all instances predicted as positive. It is calculated as: FDR = FP / (FP + TP), where FP is false positives and TP is true positives. If the total number of predicted positives (FP + TP) is zero, FDR is defined as 0.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y
|
ndarray
|
True binary labels, where 1 indicates an actual positive (e.g., anomaly) and 0 indicates an actual negative (e.g., normal). |
required |
y_hat
|
ndarray
|
Predicted binary labels, where 1 indicates a predicted positive and 0 indicates a predicted negative. |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
The calculated False Discovery Rate. |
Source code in nonconform/utils/stat/metrics.py
statistical_power ¶
Calculate statistical power (recall or true positive rate).
Statistical power, also known as recall or true positive rate (TPR), measures the proportion of actual positives that are correctly identified by the classifier. It is calculated as: Power (TPR) = TP / (TP + FN), where TP is true positives and FN is false negatives. If the total number of actual positives (TP + FN) is zero, power is defined as 0.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y
|
ndarray
|
True binary labels, where 1 indicates an actual positive (e.g., anomaly) and 0 indicates an actual negative (e.g., normal). |
required |
y_hat
|
ndarray
|
Predicted binary labels, where 1 indicates a predicted positive and 0 indicates a predicted negative. |
required |
Returns:
Name | Type | Description |
---|---|---|
float |
float
|
The calculated statistical power. |
Source code in nonconform/utils/stat/metrics.py
statistical ¶
calculate_p_val ¶
Calculate p-values for scores based on a calibration set.
This function computes a p-value for each score in the scores
array by
comparing it against the distribution of scores in the calibration_set
.
The p-value represents the proportion of calibration scores that are
greater than or equal to the given score, with a small adjustment.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scores
|
ndarray
|
A 1D array of test scores for which p-values are to be calculated. |
required |
calibration_set
|
ndarray
|
A 1D array of calibration scores used as the reference distribution. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: An array of p-values, each corresponding to an input score
from |
Notes
The p-value for each score is computed using the formula:
p_value = (1 + count(calibration_score >= score)) / (1 + N_calibration)
where N_calibration is the total number of scores in calibration_set
.
Source code in nonconform/utils/stat/statistical.py
calculate_weighted_p_val ¶
calculate_weighted_p_val(
scores: ndarray,
calibration_set: ndarray,
w_scores: ndarray,
w_calib: ndarray,
) -> np.ndarray
Calculate weighted p-values for scores using a weighted calibration set.
This function computes p-values by comparing input scores
(with
corresponding w_scores
weights) against a calibration_set
(with
w_calib
weights). The calculation involves a weighted count of
calibration scores exceeding each test score, incorporating the weights
of both the test scores and calibration scores.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
scores
|
ndarray
|
A 1D array of test scores. |
required |
calibration_set
|
ndarray
|
A 1D array of calibration scores. |
required |
w_scores
|
ndarray
|
A 1D array of weights corresponding to each
score in |
required |
w_calib
|
ndarray
|
A 1D array of weights corresponding to each
score in |
required |
Returns:
Type | Description |
---|---|
ndarray
|
numpy.ndarray: An array of weighted p-values corresponding to the input
|