¿Cómo hacer la diferenciación automática en tipos de datos complejos?
Dada una definición de matriz muy simple basada en 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
(para fines de demostración ... Estoy usando hmatrix pero pensé que el problema estaba allí de alguna manera)
Y una función de error (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)
¿Por qué el compilador no puede deducir los tipos correctos en esto?
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
El mensaje de error exacto es este:
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