Wie mache ich eine automatische Differenzierung bei komplexen Datentypen?

Gegeben eine sehr einfache Matrixdefinition basierend auf Vector:

import Numeric.AD
import qualified Data.Vector as V

newtype Mat a = Mat { unMat :: V.Vector a }

scale' f = Mat . V.map (*f) . unMat
add' a b = Mat $ V.zipWith (+) (unMat a) (unMat b)
sub' a b = Mat $ V.zipWith (-) (unMat a) (unMat b)
mul' a b = Mat $ V.zipWith (*) (unMat a) (unMat b)
pow' a e = Mat $ V.map (^e) (unMat a)

sumElems' :: Num a => Mat a -> a
sumElems' = V.sum . unMat

(zu Demonstrationszwecken ... Ich benutze hmatrix, dachte aber, das Problem sei irgendwie da)

Und eine Fehlerfunktion eq3):

eq1' :: Num a => [a] -> [Mat a] -> Mat a
eq1' as φs = foldl1 add' $ zipWith scale' as φs

eq3' :: Num a => Mat a -> [a] -> [Mat a] -> a
eq3' img as φs = negate $ sumElems' (errImg `pow'` (2::Int))
  where errImg = img `sub'` (eq1' as φs)

Warum kann der Compiler hieraus nicht die richtigen Typen ableiten?

diffTest :: forall a . (Fractional a, Ord a) => Mat a -> [Mat a] -> [a] -> [[a]]
diffTest m φs as0 = gradientDescent go as0
  where go xs = eq3' m xs φs

Die genaue Fehlermeldung lautet:

src/Stuff.hs:59:37:
    Could not deduce (a ~ Numeric.AD.Internal.Reverse.Reverse s a)
    from the context (Fractional a, Ord a)
      bound by the type signature for
                 diffTest :: (Fractional a, Ord a) =>
                             Mat a -> [Mat a] -> [a] -> [[a]]
      at src/Stuff.hs:58:13-69
    or from (reflection-1.5.1.2:Data.Reflection.Reifies
               s Numeric.AD.Internal.Reverse.Tape)
      bound by a type expected by the context:
                 reflection-1.5.1.2:Data.Reflection.Reifies
                   s Numeric.AD.Internal.Reverse.Tape =>
                 [Numeric.AD.Internal.Reverse.Reverse s a]
                 -> Numeric.AD.Internal.Reverse.Reverse s a
      at src/Stuff.hs:59:21-42
      ‘a’ is a rigid type variable bound by
          the type signature for
            diffTest :: (Fractional a, Ord a) =>
                        Mat a -> [Mat a] -> [a] -> [[a]]
          at src//Stuff.hs:58:13
    Expected type: [Numeric.AD.Internal.Reverse.Reverse s a]
                   -> Numeric.AD.Internal.Reverse.Reverse s a
      Actual type: [a] -> a
    Relevant bindings include
      go :: [a] -> a (bound at src/Stuff.hs:60:9)
      as0 :: [a] (bound at src/Stuff.hs:59:15)
      φs :: [Mat a] (bound at src/Stuff.hs:59:12)
      m :: Mat a (bound at src/Stuff.hs:59:10)
      diffTest :: Mat a -> [Mat a] -> [a] -> [[a]]
        (bound at src/Stuff.hs:59:1)
    In the first argument of ‘gradientDescent’, namely ‘go’
    In the expression: gradientDescent go as0

Antworten auf die Frage(2)

Ihre Antwort auf die Frage