Struct LpLoss
pub struct LpLoss {
pub p: f64,
}Expand description
Computes the Lp Loss between predictions and targets.
This loss function computes the element-wise p-th power of absolute errors, then reduces them via mean or sum.
§Mathematical Definition
For predictions ŷ and targets y, the element-wise loss is:
Lᵢ = |ŷᵢ - yᵢ|ᵖWith mean reduction (default), the final loss is:
L = (1/n) × Σᵢ |ŷᵢ - yᵢ|ᵖ§Notes
- This implementation computes
|error|^p, not the Lp norm(Σ|error|^p)^(1/p). - The
p = 1case uses an optimizedabs()operation. - The
p = 2case uses an optimized computationerror * errorinstead ofpowf.
§Example
use burn_nn::loss::{LpLossConfig, Reduction};
use burn::tensor::Tensor;
// Create L2 loss
let l2_loss = LpLossConfig::l2();
let predictions: Tensor<Backend, 2> = /* model output */;
let targets: Tensor<Backend, 2> = /* ground truth */;
// Compute loss with mean reduction (MSE)
let mse = l2_loss.forward(predictions.clone(), targets.clone(), Reduction::Mean);
// Compute loss with sum reduction (SSE)
let sse = l2_loss.forward(predictions.clone(), targets.clone(), Reduction::Sum);
// Compute loss with no reduction
let unreduced_l2_loss = l2_loss.forward_no_reduction(predictions, targets);Fields§
§p: f64The order of the norm (e.g., 1 for L1, 2 for L2).
Equivalently, the exponent p for computing |error|^p.
Implementations§
§impl LpLoss
impl LpLoss
pub fn forward<const D: usize, B>(
&self,
predictions: Tensor<B, D>,
targets: Tensor<B, D>,
reduction: Reduction,
) -> Tensor<B, 1>where
B: Backend,
pub fn forward<const D: usize, B>(
&self,
predictions: Tensor<B, D>,
targets: Tensor<B, D>,
reduction: Reduction,
) -> Tensor<B, 1>where
B: Backend,
Computes the element-wise loss |error|^p with reduction.
§Arguments
predictions- The model’s predicted values.targets- The ground truth target values.reduction- Specifies how to reduce the element-wise losses:Reduction::MeanorReduction::Auto: Returns the mean of all element-wise losses.Reduction::Sum: Returns the sum of all element-wise losses.
§Returns
A scalar tensor containing the reduced loss value.
§Shapes
- predictions:
[...dims]- Any shape - targets:
[...dims]- Must match predictions shape - output:
[1]- Scalar loss value
pub fn forward_no_reduction<const D: usize, B>(
&self,
predictions: Tensor<B, D>,
targets: Tensor<B, D>,
) -> Tensor<B, D>where
B: Backend,
pub fn forward_no_reduction<const D: usize, B>(
&self,
predictions: Tensor<B, D>,
targets: Tensor<B, D>,
) -> Tensor<B, D>where
B: Backend,
Computes the element-wise loss |error|^p without reduction.
§Arguments
predictions- The model’s predicted values.targets- The ground truth target values.
§Returns
A tensor of the same shape as the inputs, containing |prediction - target|^p
for each element.
§Shapes
- predictions:
[...dims]- Any shape - targets:
[...dims]- Must match predictions shape - output:
[...dims]- Same shape as inputs
pub fn forward_reduce_dims<const D: usize, B>(
&self,
predictions: Tensor<B, D>,
targets: Tensor<B, D>,
dims: &[usize],
) -> Tensor<B, D>where
B: Backend,
pub fn forward_reduce_dims<const D: usize, B>(
&self,
predictions: Tensor<B, D>,
targets: Tensor<B, D>,
dims: &[usize],
) -> Tensor<B, D>where
B: Backend,
Computes the element-wise loss |error|^p with reduction over specified dimensions.
Calculates element-wise |predictions - targets|^p, then takes the mean
over the specified dimensions. Useful for per-sample or per-channel losses (e.g., when
working with images).
Dimensions can be provided in any order. They are sorted internally and reduced from highest to lowest to ensure indices remain valid.
§Arguments
predictions- The model’s predicted values.targets- The ground truth target values.dims- Dimensions to reduce over.
§Returns
A tensor with the specified dimensions reduced to size 1.
§Example
// Image tensor: [batch, C, H, W]
let l2_loss = LpLossConfig::l2();
// Per-image MSE for PSNR: reduce over C, H, W → [batch, 1, 1, 1]
let mse_per_image = l2_loss.forward_reduce_dims(predictions, targets, &[1, 2, 3]);Trait Implementations§
§impl<B> AutodiffModule<B> for LpLosswhere
B: AutodiffBackend,
impl<B> AutodiffModule<B> for LpLosswhere
B: AutodiffBackend,
§type InnerModule = LpLoss
type InnerModule = LpLoss
§fn valid(&self) -> <LpLoss as AutodiffModule<B>>::InnerModule
fn valid(&self) -> <LpLoss as AutodiffModule<B>>::InnerModule
§fn from_inner(module: <LpLoss as AutodiffModule<B>>::InnerModule) -> LpLoss
fn from_inner(module: <LpLoss as AutodiffModule<B>>::InnerModule) -> LpLoss
§impl<B> Module<B> for LpLosswhere
B: Backend,
impl<B> Module<B> for LpLosswhere
B: Backend,
§type Record = EmptyRecord
type Record = EmptyRecord
§fn visit<V>(&self, _visitor: &mut V)where
V: ModuleVisitor<B>,
fn visit<V>(&self, _visitor: &mut V)where
V: ModuleVisitor<B>,
§fn map<M>(self, _mapper: &mut M) -> LpLosswhere
M: ModuleMapper<B>,
fn map<M>(self, _mapper: &mut M) -> LpLosswhere
M: ModuleMapper<B>,
§fn load_record(self, _record: <LpLoss as Module<B>>::Record) -> LpLoss
fn load_record(self, _record: <LpLoss as Module<B>>::Record) -> LpLoss
§fn into_record(self) -> <LpLoss as Module<B>>::Record
fn into_record(self) -> <LpLoss as Module<B>>::Record
§fn to_device(self, _: &<B as BackendTypes>::Device) -> LpLoss
fn to_device(self, _: &<B as BackendTypes>::Device) -> LpLoss
§fn fork(self, _: &<B as BackendTypes>::Device) -> LpLoss
fn fork(self, _: &<B as BackendTypes>::Device) -> LpLoss
§fn collect_devices(
&self,
devices: Vec<<B as BackendTypes>::Device>,
) -> Vec<<B as BackendTypes>::Device>
fn collect_devices( &self, devices: Vec<<B as BackendTypes>::Device>, ) -> Vec<<B as BackendTypes>::Device>
§fn devices(&self) -> Vec<<B as BackendTypes>::Device>
fn devices(&self) -> Vec<<B as BackendTypes>::Device>
§fn train<AB>(self) -> Self::TrainModulewhere
AB: AutodiffBackend<InnerBackend = B>,
Self: HasAutodiffModule<AB>,
fn train<AB>(self) -> Self::TrainModulewhere
AB: AutodiffBackend<InnerBackend = B>,
Self: HasAutodiffModule<AB>,
§fn num_params(&self) -> usize
fn num_params(&self) -> usize
§fn save_file<FR, PB>(
self,
file_path: PB,
recorder: &FR,
) -> Result<(), RecorderError>
fn save_file<FR, PB>( self, file_path: PB, recorder: &FR, ) -> Result<(), RecorderError>
§fn load_file<FR, PB>(
self,
file_path: PB,
recorder: &FR,
device: &<B as BackendTypes>::Device,
) -> Result<Self, RecorderError>
fn load_file<FR, PB>( self, file_path: PB, recorder: &FR, device: &<B as BackendTypes>::Device, ) -> Result<Self, RecorderError>
§fn quantize_weights(self, quantizer: &mut Quantizer) -> Self
fn quantize_weights(self, quantizer: &mut Quantizer) -> Self
§impl ModuleDisplay for LpLoss
impl ModuleDisplay for LpLoss
§fn format(&self, passed_settings: DisplaySettings) -> String
fn format(&self, passed_settings: DisplaySettings) -> String
§fn custom_settings(&self) -> Option<DisplaySettings>
fn custom_settings(&self) -> Option<DisplaySettings>
Auto Trait Implementations§
impl Freeze for LpLoss
impl RefUnwindSafe for LpLoss
impl Send for LpLoss
impl Sync for LpLoss
impl Unpin for LpLoss
impl UnwindSafe for LpLoss
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
§impl<C> CloneExpand for Cwhere
C: Clone,
impl<C> CloneExpand for Cwhere
C: Clone,
fn __expand_clone_method(&self, _scope: &mut Scope) -> C
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> Pointable for T
impl<T> Pointable for T
§impl<T> ToCompactString for Twhere
T: Display,
impl<T> ToCompactString for Twhere
T: Display,
§fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>
fn try_to_compact_string(&self) -> Result<CompactString, ToCompactStringError>
ToCompactString::to_compact_string()] Read more§fn to_compact_string(&self) -> CompactString
fn to_compact_string(&self) -> CompactString
CompactString]. Read more