1

我有以下代码,无法编译:

  import Numeric.AD

  data Trainable a b = forall n . Floating n =>  Trainable ([n] -> a -> b) (a -> b -> [n] -> n) 

  trainSgdFull :: (Floating n, Ord n) => Trainable a b -> [n] -> a -> b -> [[n]]
  trainSgdFull (Trainable _ cost) init input target =  gradientDescent (cost input target) init

我想使用 Trainable 类型来表示可通过梯度下降训练的机器学习系统。第一个参数是传递函数,第二个参数是成本函数,a 是输入类型,b 是输出/目标类型,列表包含可学习的参数。编译器抱怨这个:

 src/MachineLearning/Training.hs:12:73:
Could not deduce (n1 ~ ad-3.3.1.1:Numeric.AD.Internal.Types.AD s n)
from the context (Floating n, Ord n)
  bound by the type signature for
             trainSgdFull :: (Floating n, Ord n) =>
                             Trainable a b -> [n] -> a -> b -> [[n]]
  at src/MachineLearning/Training.hs:12:3-95
or from (Floating n1)
  bound by a pattern with constructor
             Trainable :: forall a b n.
                          Floating n =>
                          ([n] -> a -> b) -> (a -> b -> [n] -> n) -> Trainable a b,
           in an equation for `trainSgdFull'
  at src/MachineLearning/Training.hs:12:17-32
or from (Numeric.AD.Internal.Classes.Mode s)
  bound by a type expected by the context:
             Numeric.AD.Internal.Classes.Mode s =>
             [ad-3.3.1.1:Numeric.AD.Internal.Types.AD s n]
             -> ad-3.3.1.1:Numeric.AD.Internal.Types.AD s n
  at src/MachineLearning/Training.hs:12:56-95
  `n1' is a rigid type variable bound by
       a pattern with constructor
         Trainable :: forall a b n.
                      Floating n =>
                      ([n] -> a -> b) -> (a -> b -> [n] -> n) -> Trainable a b,
       in an equation for `trainSgdFull'
       at src/MachineLearning/Training.hs:12:17
Expected type: [ad-3.3.1.1:Numeric.AD.Internal.Types.AD s n1]
               -> ad-3.3.1.1:Numeric.AD.Internal.Types.AD s n1
  Actual type: [n] -> n
In the return type of a call of `cost'
In the first argument of `gradientDescent', namely
  `(cost input target)'

基本概念对吗?如果是,我怎样才能使代码编译?

4

1 回答 1

7

问题是

data Trainable a b = forall n . Floating n =>  Trainable ([n] -> a -> b) (a -> b -> [n] -> n)

意味着在

Trainable transfer cost

使用的类型n丢失了。所知道的是,有某种类型GuessmeFloating实例使得

transfer :: [Guessme] -> a -> b
cost :: a -> b -> [Guessme] -> Guessme

您可以使用仅适用于或仅适用于或 ...的功能构建TrainablesComplex FloatDouble

但在

trainSgdFull :: (Floating n, Ord n) => Trainable a b -> [n] -> a -> b -> [[n]]
trainSgdFull (Trainable _ cost) init input target =  gradientDescent (cost input target) init

您正在尝试使用作为参数提供的cost任何类型。Floating

Trainable是为使用 type 而构建的,n0用户提供 type n1,这些可能相同也可能不同。因此编译器不能推断它们是相同的。

如果您不想制作n的类型参数Trainable,则需要使其包装适用于调用者提供的每种 Floating类型的多态函数

data Trainable a b
    = Trainable (forall n. Floating n => [n] -> a -> b)
                (forall n. Floating n => a -> b -> [n] -> n)

(需要Rank2Types,或者,因为它正在被弃用,RankNTypes)。

于 2013-02-06T19:01:28.187 回答