Skip to content

Instantly share code, notes, and snippets.

@nh2
Created October 16, 2012 05:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nh2/3897375 to your computer and use it in GitHub Desktop.
Save nh2/3897375 to your computer and use it in GitHub Desktop.
Hopfield networks - minimal Haskell implementation
import Data.Vector ((!))
import qualified Data.Vector as V
import Data.Vector.Generic.Mutable (write)
step ws state = case updatable of [] -> state
(i,_):_ -> V.modify (\v -> write v i (o i)) state
where
n = V.length state
w i j = ws ! i ! j
x i = state ! i
h i = sum [ w i j *. x j | j <- [0..n-1] ]
o i | h i >= 0 = 1
| otherwise = -1
updatable = [ (i, s) | (i, s) <- zip [0..n-1] (V.toList state), o i /= s ]
converge ws s = if new == s then s else converge ws new where new = step ws s
train patterns n = generateVector2d w
where
w i j | i == j = 0
| otherwise = sum (map (\p -> (p ! i) .*. (p ! j)) patterns) /. n
generateVector2d f = V.generate n (V.generate n . f)
query patterns n queryState = converge (train patterns n) queryState
x *. y = x * fromIntegral y
x .*. y = fromIntegral x * fromIntegral y
x /. y = x / fromIntegral y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment