torchcp.utils

Tools

calculate_conformal_value

Calculate the 1-alpha quantile of scores for conformal prediction.

get_device

Get the device of a PyTorch model.

Registry

A registry providing name -> object mapping, to support custom modules.

torchcp.utils.calculate_conformal_value(scores, alpha)

Calculate the 1-alpha quantile of scores for conformal prediction.

This function computes the threshold value (quantile) used to construct prediction sets based on the given non-conformity scores and significance level alpha. If the scores are empty or the quantile value exceeds 1, it returns the default_q_hat value.

Parameters:
  • scores (torch.Tensor) – Non-conformity scores.

  • alpha (float) – Significance level, must be between 0 and 1.

  • default_q_hat (torch.Tensor or str, optional) – Default threshold value to use if scores are empty or invalid. If set to “max”, it uses the maximum value of scores. Default is torch.inf.

Returns:

The threshold value used to construct prediction sets.

Return type:

torch.Tensor

Raises:

ValueError – If alpha is not between 0 and 1.

torchcp.utils.get_device(model)

Get the device of a PyTorch model.

This function determines the device (CPU or GPU) on which the model’s parameters are located. If the model is None, it defaults to using GPU if available, otherwise it uses CPU.

Parameters:

model (torch.nn.Module or None) – A PyTorch model. If None, the function checks for GPU availability.

Returns:

The device on which the model’s parameters are located, or the default device (CPU or GPU).

Return type:

torch.device

class torchcp.utils.Registry(name)

A registry providing name -> object mapping, to support custom modules.

To create a registry (e.g. a backbone registry):

BACKBONE_REGISTRY = Registry('BACKBONE')

To register an object:

@BACKBONE_REGISTRY.register()
class MyBackbone(nn.Module):
    ...

Or:

BACKBONE_REGISTRY.register(MyBackbone)