Utils Module
- safe_pfl_distance.utils.model_loader.load_model(node_id: int, model_type: str, model_path_prefix: str = './models')
Loads a PyTorch model from a specified file path.
- Args:
node_id (int): Identifier for the specific model node.
model_type (str): Type of the model (e.g., “classification”, “regression”).
model_path_prefix (str, optional): Base directory where model files are stored. Defaults to “./models”.
- Returns:
torch.nn.Module or None: The loaded PyTorch model if successful, otherwise None.
- Raises:
ValueError: If input parameters are invalid.
- safe_pfl_distance.utils.cosine.cosine_distance(u, v)
Calculates the cosine distance between two vectors.
- Args:
u (array-like): First input vector.
v (array-like): Second input vector.
- Returns:
- str: The cosine distance between u and v, formatted to two decimal places.
Returns “1.00” if either input vector is all zeros, as cosine distance is undefined in this case.
- Raises:
TypeError: If inputs are not array-like. ValueError: If input vectors have different lengths. Exception: if any other exception occurs during cosine calculation.
- Example:
>>> cosine_distance([1, 0, 0], [0, 1, 0]) '1.00' >>> cosine_distance([1, 0, 0], [1, 0, 0]) '0.00' >>> cosine_distance([1, 2, 3], [4, 5, 6]) '0.02'
- safe_pfl_distance.utils.euclidean.euclidean_distance(u, v)
Calculates the Euclidean distance between two vectors.
- Args:
u (array-like): The first input vector. v (array-like): The second input vector.
- Returns:
float: The Euclidean distance between u and v.
- Raises:
TypeError: If inputs are not array-like. ValueError: If input vectors have different lengths.
- Example:
>>> euclidean_distance([0, 0], [3, 4]) 5.0 >>> euclidean_distance([1, 2, 3], [4, 5, 6]) 5.196152422706632
- safe_pfl_distance.utils.jensen_shannon.jensen_shannon_distance(u, v)
Calculates the Jensen-Shannon distance between two probability distributions.
This function computes the Jensen-Shannon distance between two 1D probability distributions. It normalizes the input vectors to ensure they represent valid probability distributions and clips values to avoid numerical instability (division by zero or log of zero).
- Args:
u (array-like): First 1D probability distribution. v (array-like): Second 1D probability distribution.
- Returns:
float: The Jensen-Shannon distance between u and v. Returns NaN if either input is all zeros after abs().
- Raises:
TypeError: If inputs are not array-like. ValueError: If input distributions have different shapes.
- Example:
>>> jensen_shannon_distance([0, 1, 0], [0, 0, 1]) 0.7071067811865476 >>> jensen_shannon_distance([1, 0, 0], [1, 0, 0]) 0.0 >>> jensen_shannon_distance([0, 0, 0], [0, 0, 0]) nan
- safe_pfl_distance.utils.wasserstein.wasserstein_distance()