module Data.ANN.Hopfield where import Data.List -- Discrete Hopfield networks -- Hopfield networks are a form of error-correcting, auto-associative memory. -- That is, a hopfield network memorises a list of vectors and can often find the closest -- memorised vector for a given input. -- Quick and dirty version using lists. Would be nice to do this using a vector space library type Vector a = [a] type Matrix a = [Vector a] vecPlus = zipWith (+) matPlus = zipWith vecPlus matId i = (i : repeat 0) : (map (0:) $ matId i) matProd xs ys = [ [sum $ zipWith (*) x y | y<-transpose ys] | x<-xs] outerProd xs ys = [ [x*y | y<-ys] | x<-xs] boolToInt b = if b then 1 else -1 intToBool i | i >= 0 = True | otherwise = False -- A hopfield network can be represented as a matrix multiplication data Hopfield = Hopfield (Matrix Int) deriving (Eq,Ord,Show) makeHopfield :: [Vector Bool] -> Hopfield makeHopfield bs = Hopfield $ foldl matPlus (matId (- genericLength bs)) [ y `outerProd` y | y <- map (map boolToInt) bs] recall :: Hopfield -> Vector Bool -> Vector Bool recall (Hopfield ys) x = [intToBool $ sum $ zipWith (*) (map boolToInt x) y | y<-ys]