loss

package
v0.28.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2026 License: Apache-2.0 Imports: 9 Imported by: 8 modules, 20 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package losses have several standard losses that implement train.LossFn interface. They can also be called separately by custom losses.

They all have the same signature that can be used by train.Trainer.

Index

Constants

View Source
const (
	Epsilon16 = 1e-4
	Epsilon32 = 1e-7
	Epsilon64 = 1e-8
)

Variables

View Source
var (
	// ParamAdaptivePowerLossNear is the name of the hyperparameter that defines the AdaptivePowerLoss.
	// It defaults to 2.0
	//
	// See MakeAdaptivePowerLoss and MakeAdaptivePowerLossFromScope.
	ParamAdaptivePowerLossNear = "adaptive_loss_near"

	// ParamAdaptivePowerLossFar is the name of one of the hyperparameter that defines the AdaptivePowerLoss
	// It defaults to 1.0
	//
	// See MakeAdaptivePowerLoss and MakeAdaptivePowerLossFromScope.
	ParamAdaptivePowerLossFar = "adaptive_loss_far"

	// ParamAdaptivePowerLossMiddleDelta is the name of one of the hyperparameter that defines the AdaptivePowerLoss.
	// It defaults to 1.0
	//
	// See MakeAdaptivePowerLoss and MakeAdaptivePowerLossFromScope.
	ParamAdaptivePowerLossMiddleDelta = "adaptive_loss_middle"

	// ParamAdaptivePowerLossSharpness is the name of one of the hyperparameter that defines the AdaptivePowerLoss.
	// It defaults to 1.0
	//
	// See MakeAdaptivePowerLoss and MakeAdaptivePowerLossFromScope.
	ParamAdaptivePowerLossSharpness = "adaptive_loss_sharpness"
)
View Source
var (
	// ParamTripletLossPairwiseDistanceMetric is the name of the hyperparameter that defines the TripletLoss.
	// It defaults to 0
	//
	// See MakeTripletLossFromScope.
	ParamTripletLossPairwiseDistanceMetric = "triplet_loss_pairwise_distance_metric"

	// ParamTripletLossMiningStrategy is the name of the hyperparameter that defines the TripletLoss.
	// It defaults to 2
	//
	// See MakeTripletLossFromScope.
	ParamTripletLossMiningStrategy = "triplet_loss_mining_strategy"

	// ParamTripletLossMargin is the name of the hyperparameter that defines the TripletLoss.
	// It defaults to 1.0
	//
	// See MakeTripletLossFromScope.
	ParamTripletLossMargin = "triplet_loss_margin"
)
View Source
var (
	// ParamHuberLossDelta is the name of the hyperparameter that defines the Huber loss delta.
	// See HuberLossBuilder.
	// It defaults to 1.0
	ParamHuberLossDelta = "huber_loss_delta"
)
View Source
var (
	// ParamLoss defines the loss to use (the value of the hyperparameter is a string),
	// when using LossFromScope.
	//
	// See enumeration Type for accepted loss types.
	//
	// Some losses may have extra parameters, also read from the scope hyperparameters -- e.g.:
	// MakeHuberLossFromScope and MakeAdaptivePowerLossFromScope.
	ParamLoss = "loss"
)

Functions

func BinaryCrossentropy

func BinaryCrossentropy(labels, predictions []*Node) *Node

BinaryCrossentropy returns the cross-entropy loss between labels and predictions, for binary classification tasks.

labels and predictions must have the same dimensions.

labels is converted to predictions dtype, and it's expected to convert to 1.0 (for true) or 0.0 for false. So labels as booleans should work, as well as labels as int type that is 0 or 1.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func BinaryCrossentropyLogits

func BinaryCrossentropyLogits(labels, logits []*Node) *Node

BinaryCrossentropyLogits returns the cross-entropy loss between labels and `sigmoid(logits)`, for binary classification tasks. It assumes the predictions are given by `sigmoid(logits)`. This is a more numerically stable and faster implementation than actually taking the sigmoid of the logits and using the equivalent BinaryCrossentropy. labels and logits must have the same shape.

labels is converted to predictions dtype, and it's expected to convert to 1.0 (for true) or 0.0 for false. So booleans should work, as an int type that is 0 or 1.

See mathematical derivation of the stable solution in https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func CategoricalCrossEntropy

func CategoricalCrossEntropy(labels, predictions []*Node) *Node

CategoricalCrossEntropy returns the cross-entropy loss of the predictions (as probabilities), given the labels. The labels are provided in "dense" format, they should have the exact same shape as predictions, and be set 1 for the true (labeled) category, and 0 for the others (one-hot encoding) -- or any other distribution that sums to 1. predictions should hold probabilities that must sum to 1.0.

Notice the CategoricalCrossEntropyLogits is more stable, given the choice choose that instead.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func CategoricalCrossEntropyLogits

func CategoricalCrossEntropyLogits(labels, logits []*Node) *Node

CategoricalCrossEntropyLogits returns the cross-entropy loss of the logits, given the labels. The labels are provided in "dense" format, they should have the exact same shape as logits, and be set 1 for the true (labeled) category, and 0 for the others -- or any other distribution that sum to 1.

It *does not* reduce-mean the losses, they are returned individually for each element of the batch and need to be ReduceAllMean (usually the mean, but it could be the sum also) before used for training.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

TODO: implement faster version with logits, see https://github.com/tensorflow/tensorflow/blob/359c3cdfc5fabac82b3c70b3b6de2b0a8c16874f/tensorflow/python/ops/nn_ops.py#L4051

func CheckExtraLabelsForWeightsAndMask

func CheckExtraLabelsForWeightsAndMask(weightsShape shapes.Shape, labels []*Node) (weights, mask *Node)

CheckExtraLabelsForWeightsAndMask takes the remainder labels tensor slice (so without the actual labels values) and separates a mask (bool) and weights (float), which can be provided in any order.

`weightsShape` is the expected shape for weights (if present) and the dimensions for a mask (if present), although a mask is assumed to be of dtype `Bool`.

If weights and masks are present, weights are converted to zero for masked out values (where mask is false).

It raises an exception (panic) if there are more or unknown shaped labels.

This function is used by the loss implementations to help handle mask and weights extra label tensors.

func EuclideanDistance

func EuclideanDistance(labels, predictions []*Node) (loss *Node)

EuclideanDistance returns the Euclidean distance between labels and predictions vectors (last axis).

labels and predictions must have the same shape.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes into consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func EuclideanDistanceSquare

func EuclideanDistanceSquare(labels, predictions []*Node) (loss *Node)

EuclideanDistanceSquare returns the square of the Euclidean distance between labels and predictions vectors (last axis).

labels and predictions must have the same shape.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes into consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func MakeShapeLike

func MakeShapeLike(dtype dtypes.DType, template shapes.Shape, dims ...int) shapes.Shape

MakeShapeLike constructs a shape similar to template but with a different dtype and dimensions. If any dimension in dims is dynamic (negative), or if template is dynamic, the returned shape is dynamic, and it will attempt to preserve the axis names from the template.

func MeanAbsoluteError

func MeanAbsoluteError(labels, predictions []*Node) (loss *Node)

MeanAbsoluteError returns the mean absolute error between labels and predictions. It uses only the first element of each. labels and predictions must have the same shape.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func MeanSquaredError

func MeanSquaredError(labels, predictions []*Node) (loss *Node)

MeanSquaredError returns the mean squared error between labels and predictions.

labels and predictions must have the same shape.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func PairwiseDistanceMetricStrings

func PairwiseDistanceMetricStrings() []string

PairwiseDistanceMetricStrings returns a slice of all String values of the enum

func SparseCategoricalCrossEntropyLogits

func SparseCategoricalCrossEntropyLogits(labels, logits []*Node) *Node

SparseCategoricalCrossEntropyLogits returns the cross-entropy loss of the logits, given the labels. The labels are provided in "sparse" format, that is, integer numbers from 0 to logits dimension-1. labels and logits must have the same rank, and labels last dimension must be 1.

Labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example.

func TripletLoss

func TripletLoss(labels, predictions []*Node,
	miningStrategy TripletMiningStrategy,
	margin float64,
	metric PairwiseDistanceMetric) *Node

TripletLoss Computes the triplet loss for valid triplet with different mining strategies for positives and negatives over a batch of embeddings.

Parameters:

  • labels *Node labels of the batch, of size (batch_size,)
  • embeddings *Node 2-D Tensor of shape (batch_size, embed_dim)
  • miningStrategy TripletMiningStrategy What mining strategy to use to select embedding from the different class. {'all', 'hard', 'semi-hard'}
  • margin float64 Defines the target margin between positive and negative pairs, e.g., a margin of 1.0 means that the positive and negative distances should be 1.0 apart if margin is negative, a soft margin will apply. It can be beneficial to pull together samples from the same class as much as possible. See the paper for more details https://arxiv.org/pdf/1703.07737.pdf
  • metric PairwiseDistanceMetric Which metric to use to compute the pairwise distances between embeddings.

References

[Oliver Moindrot blog](https://omoindrot.github.io/triplet-loss)
[FaceNet](https://arxiv.org/abs/1503.03832)
[In Defense of the Triplet Loss for Person Re-Identification](https://arxiv.org/abs/1703.07737)
[Tensorflow similarity triplet loss](https://github.com/tensorflow/similarity/blob/master/tensorflow_similarity/losses/triplet_loss.py)

func TripletMiningStrategyStrings

func TripletMiningStrategyStrings() []string

TripletMiningStrategyStrings returns a slice of all String values of the enum

func TypeStrings

func TypeStrings() []string

TypeStrings returns a slice of all String values of the enum

Types

type LossFn

type LossFn func(labels, predictions []*Node) *Node

LossFn is the interface used bye train.Trainer to train models.

It takes as inputs the labels and predictions:

  • labels come from the dataset.
  • predictions come from the model.
  • the returned loss will be graph.ReduceAllMean by train.Trainer to a scalar, before being used for gradient descent. That means that the loss function is free to return a loss per example or an already reduced scalar loss.

Most of the predefined losses in the package `gomlx/ml/train/losses` assume labels and predictions are both of length one. For multi-head models, it's very easy to write a small custom LossFn that splits the slice and send each label/prediction pair to a predefined loss.

func LossFromScope

func LossFromScope(scope *model.Scope) (LossFn, error)

LossFromScope takes the value from the ParamLoss hyperparameter as a string and returns or creates the corresponding loss. It defaults to "mae".

Useful for projects where more than one loss matches the problem underlying optimization goal.

It returns an error if the configured loss is unknown.

func MakeAdaptivePowerLoss

func MakeAdaptivePowerLoss(powerNear, powerFar, middleDelta, sharpness float64) LossFn

MakeAdaptivePowerLoss creates an adaptive power loss function.

  • When the labels and predictions are close, it tends to |labels-predictions|^powerNear.
  • When the labels and predictions are far, it tends to |labels-predictions|^powerFar.
  • If labels-predictions == middleDelta, it's exactly mid-point loss between powerNear and powerFar, and the loss is |labels-predictions|^(powerFar+powerNear)/2.
  • sharpness defines how sharp ("sudden") is the transition.

For the returned loss function, labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example. Weights are automatically normalized to sum to one (preserving their ratio), preserving their ratio.

E.g.: setting powerNear to 2, powerFar to 1, this will behave similarly to a HuberLoss.

func MakeAdaptivePowerLossFromScope

func MakeAdaptivePowerLossFromScope(scope *model.Scope) LossFn

MakeAdaptivePowerLossFromScope calls MakeAdaptivePowerLoss using the delta configured by the hyperparameter in the model.

See ParamAdaptivePowerLossNear, ParamAdaptivePowerLossFar, ParamAdaptivePowerLoss

func MakeHuberLoss

func MakeHuberLoss(delta float64) LossFn

MakeHuberLoss returns a Huber loss function: it's similar to an L2 (MeanSquaredLoss) close to the target, and it becomes L1 (linear) away from the target.

The delta parameter configures the range where the loss behaves as L2: if the prediction is further than delta it becomes linear. It also defines the slope. A good default value is 1.0.

For the returned loss function, labels can have 2 optional extra values (in any order):

  • mask: a boolean mask of shape [batchSize] set to true for values to be used, and false for those to be ignored. Typically used for padding. The returned mean loss takes in consideration the mask.
  • weights: a float value of shape [batchSize] with the relative weights to be applied to each example. Weights are automatically normalized to sum to one (preserving their ratio), preserving their ratio.

See https://en.wikipedia.org/wiki/Huber_loss

func MakeHuberLossFromScope

func MakeHuberLossFromScope(scope *model.Scope) LossFn

MakeHuberLossFromScope calls MakeHuberLoss using the delta configured by the hyperparameter ParamHuberLossDelta in the model.

func MakeTripletLossFromScope

func MakeTripletLossFromScope(scope *model.Scope) LossFn

MakeTripletLossFromScope calls TripletLoss using the configured by the hyperparameter in the model.

type PairwiseDistanceMetric

type PairwiseDistanceMetric int
const (
	PairwiseDistanceMetricL2 PairwiseDistanceMetric = iota
	PairwiseDistanceMetricSquaredL2
	PairwiseDistanceMetricCosine
)

func PairwiseDistanceMetricString

func PairwiseDistanceMetricString(s string) (PairwiseDistanceMetric, error)

PairwiseDistanceMetricString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func PairwiseDistanceMetricValues

func PairwiseDistanceMetricValues() []PairwiseDistanceMetric

PairwiseDistanceMetricValues returns all values of the enum

func (PairwiseDistanceMetric) IsAPairwiseDistanceMetric

func (i PairwiseDistanceMetric) IsAPairwiseDistanceMetric() bool

IsAPairwiseDistanceMetric returns "true" if the value is listed in the enum definition. "false" otherwise

func (PairwiseDistanceMetric) MarshalJSON

func (i PairwiseDistanceMetric) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for PairwiseDistanceMetric

func (PairwiseDistanceMetric) MarshalText

func (i PairwiseDistanceMetric) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for PairwiseDistanceMetric

func (PairwiseDistanceMetric) MarshalYAML

func (i PairwiseDistanceMetric) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for PairwiseDistanceMetric

func (PairwiseDistanceMetric) String

func (i PairwiseDistanceMetric) String() string

func (*PairwiseDistanceMetric) UnmarshalJSON

func (i *PairwiseDistanceMetric) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for PairwiseDistanceMetric

func (*PairwiseDistanceMetric) UnmarshalText

func (i *PairwiseDistanceMetric) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for PairwiseDistanceMetric

func (*PairwiseDistanceMetric) UnmarshalYAML

func (i *PairwiseDistanceMetric) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for PairwiseDistanceMetric

func (PairwiseDistanceMetric) Values

func (PairwiseDistanceMetric) Values() []string

type TripletMiningStrategy

type TripletMiningStrategy int
const (
	TripletMiningStrategyAll TripletMiningStrategy = iota
	TripletMiningStrategyHard
	TripletMiningStrategySemiHard
)

func TripletMiningStrategyString

func TripletMiningStrategyString(s string) (TripletMiningStrategy, error)

TripletMiningStrategyString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func TripletMiningStrategyValues

func TripletMiningStrategyValues() []TripletMiningStrategy

TripletMiningStrategyValues returns all values of the enum

func (TripletMiningStrategy) IsATripletMiningStrategy

func (i TripletMiningStrategy) IsATripletMiningStrategy() bool

IsATripletMiningStrategy returns "true" if the value is listed in the enum definition. "false" otherwise

func (TripletMiningStrategy) MarshalJSON

func (i TripletMiningStrategy) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for TripletMiningStrategy

func (TripletMiningStrategy) MarshalText

func (i TripletMiningStrategy) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for TripletMiningStrategy

func (TripletMiningStrategy) MarshalYAML

func (i TripletMiningStrategy) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for TripletMiningStrategy

func (TripletMiningStrategy) String

func (i TripletMiningStrategy) String() string

func (*TripletMiningStrategy) UnmarshalJSON

func (i *TripletMiningStrategy) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for TripletMiningStrategy

func (*TripletMiningStrategy) UnmarshalText

func (i *TripletMiningStrategy) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for TripletMiningStrategy

func (*TripletMiningStrategy) UnmarshalYAML

func (i *TripletMiningStrategy) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for TripletMiningStrategy

func (TripletMiningStrategy) Values

func (TripletMiningStrategy) Values() []string

type Type

type Type int

Type of loss, an enumeration of losses supported by

const (
	// TypeMAE corresponds to MeanAbsoluteError.
	TypeMAE Type = iota

	// TypeMSE corresponds to MeanSquaredError.
	TypeMSE

	// TypeHuber corresponds to a Huber-loss, see MakeHuberLoss.
	TypeHuber

	// TypeAPL corresponds to an Adaptive-Power-Loss, see MakeAdaptivePowerLoss.
	TypeAPL

	// TypeBinCross corresponds to BinaryCrossentropy.
	TypeBinCross

	// TypeBinCrossLogits corresponds to BinaryCrossentropyLogits.
	TypeBinCrossLogits

	// TypeCategoricalCross corresponds to CategoricalCrossEntropy.
	TypeCategoricalCross

	// TypeCategoricalCrossLogits corresponds to CategoricalCrossEntropyLogits.
	TypeCategoricalCrossLogits

	// TypeSparseCrossLogits corresponds to SparseCategoricalCrossEntropyLogits.
	TypeSparseCrossLogits

	// TypeTriplet corresponds to TripletLoss.
	TypeTriplet

	// TypeEuclidean corresponds to EuclideanDistance.
	TypeEuclidean

	// TypeEuclideanSquare corresponds to EuclideanDistanceSquare.
	TypeEuclideanSquare
)

func TypeString

func TypeString(s string) (Type, error)

TypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func TypeValues

func TypeValues() []Type

TypeValues returns all values of the enum

func (Type) IsAType

func (i Type) IsAType() bool

IsAType returns "true" if the value is listed in the enum definition. "false" otherwise

func (Type) MarshalJSON

func (i Type) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Type

func (Type) MarshalText

func (i Type) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface for Type

func (Type) MarshalYAML

func (i Type) MarshalYAML() (interface{}, error)

MarshalYAML implements a YAML Marshaler for Type

func (Type) String

func (i Type) String() string

func (*Type) UnmarshalJSON

func (i *Type) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Type

func (*Type) UnmarshalText

func (i *Type) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for Type

func (*Type) UnmarshalYAML

func (i *Type) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements a YAML Unmarshaler for Type

func (Type) Values

func (Type) Values() []string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL