【问题标题】:fmap with two functions具有两个功能的 fmap
【发布时间】:2018-07-15 16:48:06
【问题描述】:

我正在使用 haskell 编写神经网络。我的代码基于此 http://www-cs-students.stanford.edu/~blynn/haskell/brain.html 。 我通过以下方式调整了前馈方法:

feedForward :: [Float] -> [([Float], [[Float]])] -> [Float]
feedForward = foldl ((fmap tanh . ) . previousWeights)

previousWeights 是:

previousWeights :: [Float] -> ([Float], [[Float]]) -> [Float]
previousWeights actual_value (bias, weights) = zipWith (+) bias (map (sum.(zipWith (*) actual_value)) weights)

我真的不明白 fmap tanh . 从我读到的 fmap 应用于两个函数就像一个组合。如果我将fmap 更改为map,我会得到相同的结果。

【问题讨论】:

  • 对于列表fmap = mapfmapmap 的泛化。
  • fmap 等于map 用于列表,请参阅learnyouahaskell.com/…,查找fmap = map
  • (fmap tanh .) 给你(Floating b, Functor f) => (a -> f b) -> a -> f b 如果你使用地图将它限制在列表中,你会得到(map tanh .) :: Floating b => (a -> [b]) -> a -> [b]
  • 对于(.) . 看看this question
  • (fmap tanh . ) . previousWeights 是写\x y -> map tanh (previousWeights x y) 的复杂方式。因此,它会生成之前的权重,然后取每个权重的 tanh。

标签: haskell neural-network feed-forward


【解决方案1】:

如果我们给出参数名称并删除连续的.,则更容易阅读:

feedForward :: [Float] -> [([Float], [[Float]])] -> [Float]
feedForward actual_value bias_and_weights =
  foldl
  (\accumulator -- the accumulator, it is initialized as actual_value
    bias_and_weight -> -- a single value from bias_and_weights
     map tanh $ previousWeights accumulator bias_and_weight)
  actual_value -- initialization value
  bias_and_weights -- list we are folding over

在这种情况下,知道foldl 的类型签名将是([Float] -> ([Float], [[Float]])-> [Float]) -> [Float] -> [([Float], [[Float]])] -> [Float] 也可能会有所帮助。

注意:您发现的这种代码风格虽然写起来很有趣,但对其他人来说阅读起来可能是一个挑战,如果不是为了好玩,我通常不建议您这样写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 2023-03-24
    • 2017-09-10
    • 2021-09-20
    • 2022-07-01
    • 1970-01-01
    • 2012-05-08
    相关资源
    最近更新 更多