我在读感知器,并试图在哈斯克尔实现一个。这个算法似乎在我能测试的范围内运行我将在某个时候完全重写代码,但在重写之前,我考虑了在编写代码时问一些arosen的问题。
当返回完整的神经元时,可以训练神经元let neuron = train set [1,1]是有效的,但是如果我改变train函数,返回一个不完整的神经元而不输入,或者尝试模式匹配,只创建一个不完整的神经元,那么代码就陷入无休止循环。
当返回完整的神经元时,一切工作正常,但是当返回可流通的神经元时,代码进入一个循环。

module Main where
import System.Random
type Inputs = [Float]
type Weights = [Float]
type Threshold = Float
type Output = Float
type Trainingset = [(Inputs, Output)]

data Neuron = Neuron Threshold Weights Inputs deriving Show

output :: Neuron -> Output
output (Neuron threshold weights inputs) =
          if total >= threshold then 1 else 0
          where total = sum $ zipWith (*) weights inputs

rate :: Float -> Float -> Float
rate t o = 0.1 * (t - o)

newweight :: Float -> Float -> Weights -> Inputs -> Weights
newweight t o weight input = zipWith nw weight input
  where nw w x = w + (rate t o) * x

learn :: Neuron -> Float -> Neuron
learn on@(Neuron tr w i) t =
  let o = output on
  in Neuron tr (newweight t o w i) i

converged :: (Inputs -> Neuron) -> Trainingset -> Bool
converged n set = not $ any (\(i,o) -> output (n i) /= o) set

train :: Weights -> Trainingset -> Neuron
train w s = train' s (Neuron 1 w)

train' :: Trainingset -> (Inputs -> Neuron) -> Neuron
train' s n | not $ converged n set
              = let (Neuron t w i) = train'' s n
                in train' s (Neuron t w)
          | otherwise = n $ fst $ head s

train'' :: Trainingset -> (Inputs -> Neuron) -> Neuron
train'' ((a,b):[]) n = learn (n a) b
train'' ((a,b):xs) n = let
                        (Neuron t w i) = learn (n a) b
                      in
                        train'' xs (Neuron t w)

set :: Trainingset
set = [
        ([1,0], 0),
        ([1,1], 1),
        ([0,1], 0),
        ([0,0], 0)
      ]

randomWeights :: Int -> IO [Float]
randomWeights n =
  do
    g <- newStdGen
    return $ take n $ randomRs (-1, 1) g

main = do
  w <- randomWeights 2
  let (Neuron t w i) = train w set
  print $ output $ (Neuron t w [1,1])
  return ()

编辑:根据评论,再指定一点。
运行上面的代码,我得到:
perceptron: <<loop>>
但通过编辑主要方法:
main = do
  w <- randomWeights 2
  let neuron = train w set
  print $ neuron
  return ()

(注意let neuron和打印行),一切正常,输出为:
Neuron 1.0 [0.71345896,0.33792675] [1.0,0.0]

最佳答案

也许我遗漏了一些东西,但我将您的测试用例简化为这个程序:

module Main where
data Foo a = Foo a

main = do
  x ← getLine
  let (Foo x) = Foo x
  putStrLn x

这进一步简化为:
main = do
  x ← getLine
  let x = x
  putStrLn x

问题是将(Foo x)绑定到依赖于x的对象
是循环依赖项为了评估x,我们需要知道
好的,我们只需要计算x。要计算x,我们需要
知道x的值。没关系,我们只计算x,以此类推。
这不是C,记住:它是绑定,不是赋值,而且绑定
被懒洋洋地评价。
使用更好的变量名,一切正常:
module Main where
data Foo a = Foo a

main = do
  line ← getLine
  let (Foo x) = Foo line
  putStrLn x

(在您的例子中,所讨论的变量是w

关于algorithm - Haskell的行为不一致,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3313068/

10-12 21:36