gpt4 book ai didi

haskell - 符号微分的递归方案

转载 作者:行者123 更新时间:2023-12-02 16:51:51 25 4
gpt4 key购买 nike

以下术语来自 this excellent series ,让我们用 Term Expr 表示一个表达式,例如 (1 + x^2 - 3x)^3,其中数据类型如下:

data Expr a =
Var
| Const Int
| Plus a a
| Mul a a
| Pow a Int
deriving (Functor, Show, Eq)

data Term f = In { out :: f (Term f) }

是否有适合执行符号微分的递归方案?我觉得它几乎是专门针对 Term Expr 的 Futumorphism,即 futuderiveFutu 用于适当的函数 deriveFutu:

data CoAttr f a  
= Automatic a
| Manual (f (CoAttr f a))

futu :: Functor f => (a -> f (CoAttr f a)) -> a -> Term f
futu f = In <<< fmap worker <<< f where
worker (Automatic a) = futu f a
worker (Manual g) = In (fmap worker g)

这看起来相当不错,除了下划线变量是 Term 而不是 CoAttr:

deriveFutu :: Term Expr -> Expr (CoAttr Expr (Term Expr))
deriveFutu (In (Var)) = (Const 1)
deriveFutu (In (Const _)) = (Const 0)
deriveFutu (In (Plus x y)) = (Plus (Automatic x) (Automatic y))
deriveFutu (In (Mul x y)) = (Plus (Manual (Mul (Automatic x) (Manual _y)))
(Manual (Mul (Manual _x) (Automatic y)))
)
deriveFutu (In (Pow x c)) = (Mul (Manual (Const c)) (Manual (Mul (Manual (Pow _x (c-1))) (Automatic x))))

没有递归方案的版本如下所示:

derive :: Term Expr -> Term Expr
derive (In (Var)) = In (Const 1)
derive (In (Const _)) = In (Const 0)
derive (In (Plus x y)) = In (Plus (derive x) (derive y))
derive (In (Mul x y)) = In (Plus (In (Mul (derive x) y)) (In (Mul x (derive y))))
derive (In (Pow x c)) = In (Mul (In (Const c)) (In (Mul (In (Pow x (c-1))) (derive x))))

作为这个问题的扩展,是否存在一种递归方案来区分和消除“空”Expr,例如作为 a 出现的 Plus (Const 0) x微分的结果——一次传递数据?

最佳答案

看产品的差异化规则:

(u v)' = u' v + v' u

要使产品脱颖而出,您需要了解什么?您需要知道子项的导数 (u', v') 及其值 (u, v )。

这正是拟态给你带来的。

para
:: Functor f
=> (f (b, Term f) -> b)
-> Term f -> b
para g (In a) = g $ (para g &&& id) <$> a

derivePara :: Term Expr -> Term Expr
derivePara = para $ In . \case
Var -> Const 1
Const _ -> Const 0
Plus x y -> Plus (fst x) (fst y)
Mul x y -> Plus
(In $ Mul (fst x) (snd y))
(In $ Mul (snd x) (fst y))
Pow x c -> Mul
(In (Const c))
(In (Mul
(In (Pow (snd x) (c-1)))
(fst x)))

在拟态中,fst 使您可以访问子术语的导数,而 snd 则为您提供术语本身。

As an extension to this question, is there a recursion scheme for differentiating and eliminating "empty" Exprs such as Plus (Const 0) x that arise as a result of differentiation -- in one pass over the data?

是的,它仍然是一个拟态。看到这一点的最简单方法是使用智能构造函数,例如

plus :: Term Expr -> Term Expr -> Expr (Term Expr)
plus (In (Const 0)) (In x) = x
plus (In x) (In (Const 0)) = x
plus x y = Plus x y

并在定义代数时使用它们。您也可以将其表达为某种 para-cata 融合。

关于haskell - 符号微分的递归方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com