0 | module NN.Architectures.LossFunctions
8 | import Data.Tensor.Utils
9 | import Data.Container.Additive
10 | import Data.Autodiff.Ops
11 | import Control.Monad.Distribution
13 | import Data.Container.Additive.Quantifiers
20 | Loss : (y, l : AddCont) -> Type
21 | Loss y l = y =\\=> l
26 | Label : Loss y l -> Type
27 | Label loss = (Param loss).Shp
29 | namespace Combinators
32 | pairLossFunctions : {y, z : AddCont} -> {l : Type} -> Num l =>
33 | Loss y (Const l) -> Loss z (Const l) -> Loss (y >*< z) (Const l)
34 | pairLossFunctions f g = postcomposeLens (composeParallel f g) sum
39 | chosenBranchLoss : {c : Cont} -> {branches : c.filledWith AddCont} ->
41 | (losses : (i : c.Pos (shapeExt branches)) -> Loss (index branches i) l) ->
42 | Loss (Section (index branches)) l
43 | chosenBranchLoss losses = MkPara (AddContDPair (\i => Param (losses i)))
44 | (evalSection {a = index branches} {p = \i => Param (losses i)}
45 | %+>> copair (\i => Run (losses i)))
50 | matchedBranchLoss : {c : Cont} -> (dec : IsDecidable c) =>
51 | {branches : c.filledWith AddCont} -> {0 l : AddCont} ->
52 | (losses : (i : c.Pos (shapeExt branches)) -> Loss (index branches i) l) ->
53 | Loss (Coproduct branches) (Maybe l)
54 | matchedBranchLoss losses = MkPara (AddContDPair (\i => Param (losses i)))
55 | (matchIndex @{GetInterface dec (shapeExt branches)}
56 | {b = index branches} {l = \i => Param (losses i)}
57 | %+>> Maybe (copair (\i => Run (losses i))))
62 | madeChoice : {ax : Axis} -> IsNaperian ax => DecEq (Log ax) =>
63 | {f : Log ax -> AddCont} ->
64 | AddContDPair f =%+> Simplex ax >*< AddContDPair f
65 | madeChoice = !%+ \ix => (
(diracDelta (fst ix), ix) ** snd)
69 | SquaredError : {a : Type} -> Num a => Neg a => Loss (Const a) (Const a)
70 | SquaredError = MkPara (Const a) SquaredDifference
73 | MeanSquaredError : {n : Axis} -> IsCubical n => TensorMonoid n.cont =>
74 | {a : Type} -> Num a => Neg a => Fractional a => Cast Nat a =>
75 | Loss (Const (Tensor [n] a)) (Const (Tensor [] a))
76 | MeanSquaredError = MkPara (Const (Tensor [n] a)) meanSquaredDifference
82 | softargmaxCrossEntropyLogits : {a : Axis} ->
83 | (nap : IsNaperian a) => IsFoldable a.cont =>
84 | Simplex a >*< Simplex a =%+> Const (Tensor [] Double)
85 | softargmaxCrossEntropyLogits @{MkIsNaperian _ pos} = !%+ \(predicted, labels) =>
86 | let logSoftargmaxLogits = logSoftargmax predicted.logits
87 | targetProbs = softargmaxImpl labels.logits
88 | out = - dot logSoftargmaxLogits targetProbs
90 | ((extract l' *) <$> (Prelude.exp <$> logSoftargmaxLogits) - targetProbs,
92 | (extract l' *) <$> negate (targetProbs * ((+ extract out) <$> logSoftargmaxLogits))))
95 | SoftargmaxCrossEntropyLogits : {a : Axis} ->
96 | IsNaperian a => IsFoldable a.cont =>
97 | Loss (Simplex a) (Const (Tensor [] Double))
98 | SoftargmaxCrossEntropyLogits
99 | = MkPara (Simplex a) softargmaxCrossEntropyLogits