gpt4 book ai didi

algorithm - 你会如何在 Haskell 中表达它?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:44:21 25 4
gpt4 key购买 nike

你会使用 if/else 在 Haskell 中编写这个算法吗?没有他们,有没有办法表达它?很难从中间提取出有意义的函数。这只是机器学习系统的输出。

我正在实现用于将 html 内容段分类为内容或样板的算法 here .这具有已经硬编码的权重。

curr_linkDensity <= 0.333333
| prev_linkDensity <= 0.555556
| | curr_numWords <= 16
| | | next_numWords <= 15
| | | | prev_numWords <= 4: BOILERPLATE
| | | | prev_numWords > 4: CONTENT
| | | next_numWords > 15: CONTENT
| | curr_numWords > 16: CONTENT
| prev_linkDensity > 0.555556
| | curr_numWords <= 40
| | | next_numWords <= 17: BOILERPLATE
| | | next_numWords > 17: CONTENT
| | curr_numWords > 40: CONTENT
curr_linkDensity > 0.333333: BOILERPLATE

最佳答案

不是手动简化逻辑(假设您可能会自动生成此代码),我认为使用 MultiWayIf非常干净直接。

{-# LANGUAGE MultiWayIf #-}

data Stats = Stats {
curr_linkDensity :: Double,
prev_linkDensity :: Double,
...
}

data Classification = Content | Boilerplate

classify :: Stats -> Classification
classify s = if
| curr_linkDensity s <= 0.333333 -> if
| prev_linkDensity s <= 0.555556 -> if
| curr_numWords s <= 16 -> if
| next_numWords s <= 15 -> if
| prev_numWords s <= 4 -> Boilerplate
| prev_numWords s > 4 -> Content
| next_numWords s > 16 -> Content
...

等等。

但是,由于这是结构化的——只是一个带有比较的 if/else 树,还可以考虑创建一个决策树数据结构并为其编写一个解释器。这将允许您进行转换、操作和检查。也许它会给你买东西;为您的规范定义微型语言可能非常有益。

data DecisionTree i o 
= Comparison (i -> Double) Double (DecisionTree i o) (DecisionTree i o)
| Leaf o

runDecisionTree :: DecisionTree i o -> i -> o
runDecisionTree (Comparison f v ifLess ifGreater) i
| f i <= v = runDecisionTree ifLess i
| otherwise = runDecisionTree ifGreater i
runDecisionTree (Leaf o) = o

-- DecisionTree is an encoding of a function, and you can write
-- Functor, Applicative, and Monad instances!

然后

 classifier :: DecisionTree Stats Classification
classifier =
Comparison curr_linkDensity 0.333333
(Comparison prev_linkDensity 0.555556
(Comparison curr_numWords 16
(Comparison next_numWords 15
(Comparison prev_numWords 4
(Leaf Boilerplate)
(Leaf Content))
(Leaf Content)
...

关于algorithm - 你会如何在 Haskell 中表达它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31414337/

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