pub struct Loss;Expand description
Loss function implementations for neural network training.
Provides forward (loss computation) and backward (gradient computation) passes for common loss functions used in GNN training.
§Numerical Stability
All loss functions use epsilon clamping and gradient clipping to prevent numerical instability with extreme prediction values (near 0 or 1).
Implementations§
Source§impl Loss
impl Loss
Sourcepub fn compute(
loss_type: LossType,
predictions: &Array2<f32>,
targets: &Array2<f32>,
) -> Result<f32>
pub fn compute( loss_type: LossType, predictions: &Array2<f32>, targets: &Array2<f32>, ) -> Result<f32>
Compute the loss value between predictions and targets.
§Arguments
loss_type- The type of loss function to usepredictions- Model predictions as a 2D arraytargets- Ground truth targets as a 2D array (same shape as predictions)
§Returns
Ok(f32)- The computed scalar loss valueErr(GnnError)- If shapes don’t match or computation fails
§Example
use ndarray::Array2;
use ruvector_gnn::training::{Loss, LossType};
let predictions = Array2::from_shape_vec((2, 2), vec![0.9, 0.1, 0.2, 0.8]).unwrap();
let targets = Array2::from_shape_vec((2, 2), vec![1.0, 0.0, 0.0, 1.0]).unwrap();
let loss = Loss::compute(LossType::Mse, &predictions, &targets).unwrap();
assert!(loss >= 0.0);Sourcepub fn gradient(
loss_type: LossType,
predictions: &Array2<f32>,
targets: &Array2<f32>,
) -> Result<Array2<f32>>
pub fn gradient( loss_type: LossType, predictions: &Array2<f32>, targets: &Array2<f32>, ) -> Result<Array2<f32>>
Compute the gradient of the loss with respect to predictions.
§Arguments
loss_type- The type of loss function to usepredictions- Model predictions as a 2D arraytargets- Ground truth targets as a 2D array (same shape as predictions)
§Returns
Ok(Array2<f32>)- Gradient array with same shape as predictionsErr(GnnError)- If shapes don’t match or computation fails
§Example
use ndarray::Array2;
use ruvector_gnn::training::{Loss, LossType};
let predictions = Array2::from_shape_vec((2, 2), vec![0.9, 0.1, 0.2, 0.8]).unwrap();
let targets = Array2::from_shape_vec((2, 2), vec![1.0, 0.0, 0.0, 1.0]).unwrap();
let grad = Loss::gradient(LossType::Mse, &predictions, &targets).unwrap();
assert_eq!(grad.shape(), predictions.shape());Auto Trait Implementations§
impl Freeze for Loss
impl RefUnwindSafe for Loss
impl Send for Loss
impl Sync for Loss
impl Unpin for Loss
impl UnsafeUnpin for Loss
impl UnwindSafe for Loss
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more