Numeric.AD和打字问题 [英] Numeric.AD and typing problem
本文介绍了Numeric.AD和打字问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Numeric.AD和一个自定义Expr类型。我希望计算
用户输入表达式的符号梯度。具有恒定
表达式的第一次试验效果很好:
calcGrad0 :: [Expr Double]
calcGrad0 = grad df vars
其中
df [x,y] = eval(env [x,y])(EVarx* EVary)
env vs = zip varNames vs
varNames = [x,y]
vars =地图EVar varNames
> calcGrad0
[Const 0.0:+(Const 0.0:+(EVar (const 1.0):const Const 0.0:+(const 0.0:+(EVarx:* Const 1.0))]
但是,如果我将表达式作为参数提取:
calcGrad1 :: [Expr Double]
calcGrad1 = calcGrad1'(EVarx* EVary)
calcGrad1'e = grad df vars
其中
df [x,y] = eval( env [x,y])e
env vs = zip varNames vs
varNames = [x,y]
vars =地图EVar varNames
$ c
$ b pre $ code $无法推断(a〜AD s(Expr a1))
上下文(Num a1,Floating a)
被
calcGrad1'的推断类型约束:: ::(Num a1,Floating a)=> Expr a - > Symbolics.hs中的[Expr a1]
:(60,1) - (65,29)
或from(Mode s)
由上下文期望的类型限制:
模式s => [AD s(Expr a1)] - > AD s(Expr a1)
在Symbolics.hs:60:16-27
`a'是一个刚性类型变量,由
绑定
calcGrad1'的推断类型:: (数字a1,浮动a)=> Expr a - > [Expr a1]
在Symbolics.hs:60:1
预期类型:[AD s(Expr a1)] - > AD s(Expr a1)
实际类型:[a] - > a
在`grad'的第一个参数中,即`df'
在表达式中:grad df vars
我如何得到ghc接受这个?
解决方案
我的猜测是你忘记申请 lift 将 Expr
转换为 AD s Expr
。
如果您有兴趣使用广告包进行符号区分。 Lennart Augustsson的追踪套餐运作良好。
I'm trying to work with Numeric.AD and a custom Expr type. I wish to calculate the symbolic gradient of user inputted expression. The first trial with a constant expression works nicely:
calcGrad0 :: [Expr Double]
calcGrad0 = grad df vars
where
df [x,y] = eval (env [x,y]) (EVar "x"*EVar "y")
env vs = zip varNames vs
varNames = ["x","y"]
vars = map EVar varNames
This works:
>calcGrad0
[Const 0.0 :+ (Const 0.0 :+ (EVar "y" :* Const 1.0)),Const 0.0 :+ (Const 0.0 :+ (EVar "x" :* Const 1.0))]
However, if I pull the expression out as a parameter:
calcGrad1 :: [Expr Double]
calcGrad1 = calcGrad1' (EVar "x"*EVar "y")
calcGrad1' e = grad df vars
where
df [x,y] = eval (env [x,y]) e
env vs = zip varNames vs
varNames = ["x","y"]
vars = map EVar varNames
I get
Could not deduce (a ~ AD s (Expr a1))
from the context (Num a1, Floating a)
bound by the inferred type of
calcGrad1' :: (Num a1, Floating a) => Expr a -> [Expr a1]
at Symbolics.hs:(60,1)-(65,29)
or from (Mode s)
bound by a type expected by the context:
Mode s => [AD s (Expr a1)] -> AD s (Expr a1)
at Symbolics.hs:60:16-27
`a' is a rigid type variable bound by
the inferred type of
calcGrad1' :: (Num a1, Floating a) => Expr a -> [Expr a1]
at Symbolics.hs:60:1
Expected type: [AD s (Expr a1)] -> AD s (Expr a1)
Actual type: [a] -> a
In the first argument of `grad', namely `df'
In the expression: grad df vars
How do I get ghc to accept this?
解决方案
My guess is you are forgetting to apply lift to convert an Expr
to an AD s Expr
.
If you are interested in using the ad package for symbolic differentiation. Lennart Augustsson's traced package works well.
这篇关于Numeric.AD和打字问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文