hnn 0.1 → 0.2.0.0
raw patch · 9 files changed
+538/−303 lines, 9 filesdep +binarydep +bytestringdep +hmatrixdep −uvectordep ~basesetup-changed
Dependencies added: binary, bytestring, hmatrix, mwc-random, random, vector, vector-binary-instances, zlib
Dependencies removed: uvector
Dependency ranges changed: base
Files
- AI/HNN/FF/Network.hs +350/−0
- AI/HNN/Layer.hs +0/−68
- AI/HNN/Net.hs +0/−71
- AI/HNN/Neuron.hs +0/−89
- AI/HNN/Recurrent/Network.hs +121/−0
- LICENSE +24/−59
- Setup.hs +2/−0
- Setup.lhs +0/−3
- hnn.cabal +41/−13
+ AI/HNN/FF/Network.hs view
@@ -0,0 +1,350 @@+{-# LANGUAGE BangPatterns, + ScopedTypeVariables,+ RecordWildCards,+ FlexibleContexts,+ TypeFamilies,+ GeneralizedNewtypeDeriving #-}++-- |+-- Module : AI.HNN.FF.Network+-- Copyright : (c) 2012 Alp Mestanogullari+-- License : BSD3+-- Maintainer : alpmestan@gmail.com+-- Stability : experimental+-- Portability : GHC+-- +-- An implementation of feed-forward neural networks in pure Haskell.+-- +-- It uses weight matrices between each layer to represent the connections between neurons from+-- a layer to the next and exports only the useful bits for a user of the library.+-- +-- Here is an example of using this module to create a feed-forward neural network with 2 inputs,+-- 2 neurons in a hidden layer and one neuron in the output layer, with random weights, and compute+-- its output for [1,2] using the sigmoid function for activation for all the neurons.+-- +-- > import AI.HNN.FF.Network+-- > import Numeric.LinearAlgebra+-- >+-- > main = do+-- > n <- createNetwork 2 [2] 1 :: IO (Network Double)+-- > print $ output n sigmoid (fromList [1, 1])+-- +-- /Note/: Here, I create a @Network Double@, but you can replace 'Double' with any number type+-- that implements the appropriate typeclasses you can see in the signatures of this module.+-- Having your number type implement the @Floating@ typeclass too is a good idea, since that's what most of the+-- common activation functions require.+--+-- /Note 2/: You can also give some precise weights to initialize the neural network with, with+-- 'fromWeightMatrices'. You can also restore a neural network you had saved using 'loadNetwork'.+-- +-- Here is an example of how to train a neural network to learn the XOR function.+-- ( for reference: XOR(0, 0) = 0, XOR(0, 1) = 1, XOR(1, 0) = 1, XOR(1, 1) = 0 )+-- +-- First, let's import hnn's feedforward neural net module, and hmatrix's vector types.+-- +-- > import AI.HNN.FF.Network+-- > import Numeric.LinearAlgebra+-- +-- Now, we will specify our training set (what the net should try to learn).+-- +-- > samples :: Samples Double+-- > samples = [ fromList [0, 0] --> fromList [0]+-- > , fromList [0, 1] --> fromList [1]+-- > , fromList [1, 0] --> fromList [1]+-- > , fromList [1, 1] --> fromList [0] +-- > ]+-- +-- You can see that this is basically a list of pairs of vectors, the first vector being+-- the input given to the network, the second one being the expected output. Of course,+-- this imply working on a neural network with 2 inputs, and a single neuron on the output layer. Then,+-- let's create one!+-- +-- > main = do+-- > net <- createNetwork 2 [2] 1+-- +-- You may have noticed we haven't specified a signature this time, unlike in the earlier snippet.+-- Since we gave a signature to samples, specifying we're working with 'Double' numbers, and since+-- we are going to tie 'net' and 'samples' by a call to a learning function, GHC will gladly figure out+-- that 'net' is working with 'Double'. +-- +-- Now, it's time to train our champion. But first, let's see how bad he is now. The weights are most likely+-- not close to those that will give a good result for simulating XOR. Let's compute the output of the net on+-- the input vectors of our samples, using 'tanh' as the activation function.+-- +-- > mapM_ (print . output net tanh . fst) samples+-- +-- Ok, you've tested this, and it gives terrible results. Let's fix this by letting 'trainNTimes' teach our neural net+-- how to behave. Since we're using 'tanh' as our activation function, we will tell it to the training function,+-- and also specify its derivative.+-- +-- > let smartNet = trainNTimes 1000 0.8 tanh tanh' net samples+-- +-- So, this tiny piece of code will run the backpropagation algorithm on the samples 1000 times, with a learning rate+-- of 0.8. The learning rate is basically how strongly we should modify the weights when we try to correct the error the net makes+-- on our samples. The bigger it is, the more the weights are going to change significantly. Depending on the cases, it is good,+-- but sometimes it can also make the backprop algorithm oscillate around good weight values without actually getting to them.+-- You usually want to test several values and see which ones gets you the nicest neural net, which generalizes well to samples+-- that are not in the training set while giving decent results on the training set.+-- +-- Now, let's see how that worked out for us:+-- +-- > mapM_ (print . output smartNet tanh . fst) samples+-- +-- You could even save that neural network's weights to a file, so that you don't need to train it again in the future, using 'saveNetwork':+--+-- > saveNetwork "smartNet.nn" smartNet+--+-- Please note that 'saveNetwork' is just a wrapper around zlib compression + serialization using the binary package.+-- AI.HNN.FF.Network also provides a 'Data.Binary.Binary' instance for 'Network', which means you can also simply use+-- 'Data.Binary.encode' and 'Data.Binary.decode' to have your own saving/restoring routines, or to simply get a bytestring +-- we can send over the network, for example.+-- +-- Here's a run of the program we described on my machine (with the timing): first set of+-- fromList's is the output of the initial neural network, the second one is the output of+-- 'smartNet' :-)+-- +-- > fromList [0.574915179613429]+-- > fromList [0.767589097192215]+-- > fromList [0.7277396607146663]+-- > fromList [0.8227114080561128]+-- > ------------------+-- > fromList [6.763498312099933e-2]+-- > fromList [0.9775186355284375]+-- > fromList [0.9350823296850516]+-- > fromList [-4.400205702560454e-2]+-- > +-- > real 0m0.365s+-- > user 0m0.072s+-- > sys 0m0.016s+-- +-- Rejoyce! Feel free to play around with the library and report any bug, feature request and whatnot to us on+-- our github repository <https://github.com/alpmestan/hnn/issues> using the appropriate tags. Also, you can+-- see the simple program we studied here with pretty colors at <https://github.com/alpmestan/hnn/blob/master/examples/ff/xor.hs>+-- and other ones at <https://github.com/alpmestan/hnn/tree/master/examples/ff>.++module AI.HNN.FF.Network+ (+ -- * Types+ Network(..)+ , ActivationFunction+ , ActivationFunctionDerivative+ , Sample+ , Samples+ , (-->)++ -- * Creating a neural network+ , createNetwork+ , fromWeightMatrices++ -- * Computing a neural network's output+ , output+ , tanh+ , tanh'+ , sigmoid+ , sigmoid'++ -- * Training a neural network+ , trainUntil+ , trainNTimes+ , trainUntilErrorBelow+ , quadError+ + -- * Loading and saving a neural network+ , loadNetwork+ , saveNetwork+ ) where++import Codec.Compression.Zlib (compress, decompress)+import Data.Binary (Binary(..), encode, decode)+import Data.List (foldl')+import Foreign.Storable (Storable)+import qualified Data.ByteString.Lazy as B+import qualified Data.Vector as V++import System.Random.MWC+import Numeric.LinearAlgebra++-- | Our feed-forward neural network type. Note the 'Binary' instance, which means you can use +-- 'encode' and 'decode' in case you need to serialize your neural nets somewhere else than+-- in a file (e.g over the network)+newtype Network a = Network+ { matrices :: V.Vector (Matrix a) -- ^ the weight matrices+ } deriving Show++instance (Element a, Binary a) => Binary (Network a) where+ put (Network ms) = put . V.toList $ ms+ get = (Network . V.fromList) `fmap` get ++-- | The type of an activation function, mostly used for clarity in signatures+type ActivationFunction a = a -> a++-- | The type of an activation function's derivative, mostly used for clarity in signatures+type ActivationFunctionDerivative a = a -> a++-- | The following creates a neural network with 'n' inputs and if 'l' is [n1, n2, ...]+-- the net will have n1 neurons on the first layer, n2 neurons on the second, and so on+-- ending with k neurons on the output layer, with random weight matrices as a courtesy of+-- 'System.Random.MWC.uniformVector'.+-- +-- > createNetwork n l k+createNetwork :: (Variate a, Storable a) => Int -> [Int] -> Int -> IO (Network a)+createNetwork nInputs hiddens nOutputs =+ fmap Network $ withSystemRandom . asGenST $ \gen -> go gen dimensions V.empty+ where+ go _ [] !ms = return ms+ go gen ((!n,!m):ds) ms = do+ !mat <- randomMat n m gen+ go gen ds (ms `V.snoc` mat)+ randomMat n m g = reshape m `fmap` uniformVector g (n*m)+ dimensions = zip (hiddens ++ [nOutputs]) $+ (nInputs+1 : hiddens)+{-# INLINE createNetwork #-}+++-- | Creates a neural network with exactly the weight matrices given as input here.+-- We don't check that the numbers of rows/columns are compatible, etc. +fromWeightMatrices :: Storable a => V.Vector (Matrix a) -> Network a+fromWeightMatrices ws = Network ws+{-# INLINE fromWeightMatrices #-}++-- The `join [input, 1]' trick below is a courtesy of Alberto Ruiz+-- <http://dis.um.es/~alberto/>. Per his words:+--+-- "The idea is that the constant input in the first layer can be automatically transferred to the following layers+-- by the learning algorithm (by setting the weights of a neuron to 1,0,0,0,...). This allows for a simpler+-- implementation and in my experiments those networks are able to easily solve non linearly separable problems."++-- | Computes the output of the network on the given input vector with the given activation function+output :: (Floating (Vector a), Product a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> Vector a+output (Network{..}) act input = V.foldl' f (join [input, 1]) matrices+ where f !inp m = mapVector act $ m <> inp+{-# INLINE output #-}++-- | Computes and keeps the output of all the layers of the neural network with the given activation function+outputs :: (Floating (Vector a), Product a, Storable a, Num (Vector a)) => Network a -> ActivationFunction a -> Vector a -> V.Vector (Vector a)+outputs (Network{..}) act input = V.scanl f (join [input, 1]) matrices+ where f !inp m = mapVector act $ m <> inp+{-# INLINE outputs #-}++deltas :: (Floating (Vector a), Floating a, Product a, Storable a, Num (Vector a)) => Network a -> ActivationFunctionDerivative a -> V.Vector (Vector a) -> Vector a -> V.Vector (Matrix a)+deltas (Network{..}) act' os expected = V.zipWith outer (V.tail ds) (V.init os)+ where !dl = (V.last os - expected) * (deriv $ V.last os)+ !ds = V.scanr f dl (V.zip os matrices)+ f (!o, m) !del = deriv o * (trans m <> del)+ deriv = mapVector act'+{-# INLINE deltas #-}++updateNetwork :: (Floating (Vector a), Floating a, Product a, Storable a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Sample a -> Network a+updateNetwork alpha act act' n@(Network{..}) (input, expectedOutput) = Network $ V.zipWith (+) matrices corr+ where !xs = outputs n act input+ !ds = deltas n act' xs expectedOutput+ !corr = V.map (scale (-alpha)) ds+{-# INLINE updateNetwork #-}+ +-- | Input vector and expected output vector+type Sample a = (Vector a, Vector a)++-- | List of 'Sample's+type Samples a = [Sample a]++-- | Handy operator to describe your learning set, avoiding unnecessary parentheses. It's just a synonym for '(,)'. +-- Generally you'll load your learning set from a file, a database or something like that, but it can be nice for +-- quickly playing with hnn or for simple problems where you manually specify your learning set.+-- That is, instead of writing:+-- +-- > samples :: Samples Double+-- > samples = [ (fromList [0, 0], fromList [0])+-- > , (fromList [0, 1], fromList [1])+-- > , (fromList [1, 0], fromList [1])+-- > , (fromList [1, 1], fromList [0]) +-- > ]+-- +-- You can write:+-- +-- > samples :: Samples Double+-- > samples = [ fromList [0, 0] --> fromList [0]+-- > , fromList [0, 1] --> fromList [1]+-- > , fromList [1, 0] --> fromList [1]+-- > , fromList [1, 1] --> fromList [0] +-- > ]+(-->) :: Vector a -> Vector a -> Sample a+(-->) = (,)++backpropOnce :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Container Vector a) => a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a+backpropOnce rate act act' n samples = foldl' (updateNetwork rate act act') n samples+{-# INLINE backpropOnce #-}++-- | Generic training function.+-- +-- The first argument is a predicate that will tell the backpropagation algorithm when to stop.+-- The first argument to the predicate is the epoch, i.e the number of times the backprop has been+-- executed on the samples. The second argument is /the current network/, and the third is the list of samples.+-- You can thus combine these arguments to create your own criterion.+-- +-- For example, if you want to stop learning either when the network's quadratic error on the samples,+-- using the tanh function, is below 0.01, or after 1000 epochs, whichever comes first, you could+-- use the following predicate:+-- +-- > pred epochs net samples = if epochs == 1000 then True else quadError tanh net samples < 0.01+-- +-- You could even use 'Debug.Trace.trace' to print the error, to see how the error evolves while it's learning,+-- or redirect this to a file from your shell in order to generate a pretty graphics and what not.+-- +-- The second argument (after the predicate) is the learning rate. Then come the activation function you want,+-- its derivative, the initial neural network, and your training set.+-- Note that we provide 'trainNTimes' and 'trainUntilErrorBelow' for common use cases.+trainUntil :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Container Vector a) => (Int -> Network a -> Samples a -> Bool) -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a+trainUntil pr learningRate act act' net samples = go net 0+ where go n !k | pr k n samples = n+ | otherwise = case backpropOnce learningRate act act' n samples of+ n' -> go n' (k+1)+{-# INLINE trainUntil #-}++-- | Trains the neural network with backpropagation the number of times specified by the 'Int' argument,+-- using the given learning rate (second argument). +trainNTimes :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Container Vector a) => Int -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a+trainNTimes n = trainUntil (\k _ _ -> k > n)+{-# INLINE trainNTimes #-}++-- | Quadratic error on the given training set using the given activation function. Useful to create+-- your own predicates for 'trainUntil'.+quadError :: (Floating (Vector a), Floating a, Num (Vector a), Num (RealOf a), Product a) => ActivationFunction a -> Network a -> Samples a -> RealOf a+quadError act net samples = foldl' (\err (inp, out) -> err + (norm2 $ output net act inp - out)) 0 samples+{-# INLINE quadError #-}++-- | Trains the neural network until the quadratic error ('quadError') comes below the given value (first argument),+-- using the given learning rate (second argument).+-- +-- /Note/: this can loop pretty much forever when you're using a bad architecture for the problem, or unappropriate activation+-- functions.+trainUntilErrorBelow :: (Floating (Vector a), Floating a, Product a, Num (Vector a), Ord a, Container Vector a, Num (RealOf a), a ~ RealOf a, Show a) => a -> a -> ActivationFunction a -> ActivationFunctionDerivative a -> Network a -> Samples a -> Network a+trainUntilErrorBelow x rate act = trainUntil (\_ n s -> quadError act n s < x) rate act+{-# INLINE trainUntilErrorBelow #-}++-- | The sigmoid function: 1 / (1 + exp (-x))+sigmoid :: Floating a => a -> a+sigmoid !x = 1 / (1 + exp (-x))+{-# INLINE sigmoid #-}++-- | Derivative of the sigmoid function: sigmoid x * (1 - sigmoid x)+sigmoid' :: Floating a => a -> a+sigmoid' !x = case sigmoid x of+ s -> s * (1 - s)+{-# INLINE sigmoid' #-}++-- | Derivative of the 'tanh' function from the Prelude.+tanh' :: Floating a => a -> a+tanh' !x = case tanh x of+ s -> 1 - s**2+{-# INLINE tanh' #-}++-- | Loading a neural network from a file (uses zlib compression on top of serialization using the binary package).+-- Will throw an exception if the file isn't there.+loadNetwork :: (Storable a, Element a, Binary a) => FilePath -> IO (Network a)+loadNetwork fp = return . decode . decompress =<< B.readFile fp+{-# INLINE loadNetwork #-}++-- | Saving a neural network to a file (uses zlib compression on top of serialization using the binary package).+saveNetwork :: (Storable a, Element a, Binary a) => FilePath -> Network a -> IO ()+saveNetwork fp net = B.writeFile fp . compress $ encode net+{-# INLINE saveNetwork #-}
− AI/HNN/Layer.hs
@@ -1,68 +0,0 @@--- | Layer module, defining functions to work on a neural network layer, which is a list of neurons-module AI.HNN.Layer where--import AI.HNN.Neuron-import Control.Arrow-import Data.Array.Vector-import Data.List---- * Layer creation---- | Creates a layer compound of n neurons with the Sigmoid transfer function, all having the given threshold and weights.-createSigmoidLayerU :: Int -> Double -> UArr Double -> [Neuron]-createSigmoidLayerU n threshold weights = - let neuron = createNeuronSigmoidU threshold weights in- take n . repeat $ neuron---- | Creates a layer compound of n neurons with the Heavyside transfer function, all having the given threshold and weights.-createHeavysideLayerU :: Int -> Double -> UArr Double -> [Neuron]-createHeavysideLayerU n threshold weights =- let neuron = createNeuronSigmoidU threshold weights in - take n . repeat $ neuron---- | Creates a layer compound of n neurons with the sigmoid transfer function, all having the given threshold and weights.-createSigmoidLayer :: Int -> Double -> [Double] -> [Neuron]-createSigmoidLayer n threshold = createSigmoidLayerU n threshold . toU---- | Creates a layer compound of n neurons with the sigmoid transfer function, all having the given threshold and weights.-createHeavysideLayer :: Int -> Double -> [Double] -> [Neuron]-createHeavysideLayer n threshold = createHeavysideLayerU n threshold . toU---- * Computation---- | Computes the outputs of each Neuron of the layer-computeLayerU :: [Neuron] -> UArr Double -> UArr Double-computeLayerU ns inputs = toU $ map (\n -> computeU n inputs) ns---- | Computes the outputs of each Neuron of the layer-computeLayer :: [Neuron] -> [Double] -> [Double]-computeLayer ns = fromU . computeLayerU ns . toU---- * Learning---- | Trains each neuron with the given sample and the given learning ratio-learnSampleLayerU :: Double -> [Neuron] -> (UArr Double, UArr Double) -> [Neuron]-learnSampleLayerU alpha ns (xs, ys) = zipWith (\n y -> learnSampleU alpha n (xs, y)) ns (fromU ys)---- | Trains each neuron with the given sample and the given learning ratio-learnSampleLayer :: Double -> [Neuron] -> ([Double], [Double]) -> [Neuron]-learnSampleLayer alpha ns = learnSampleLayerU alpha ns . (toU *** toU)---- | Trains each neuron with the given samples and the given learning ratio-learnSamplesLayerU :: Double -> [Neuron] -> [(UArr Double, UArr Double)] -> [Neuron]-learnSamplesLayerU alpha = foldl' (learnSampleLayerU alpha)---- | Trains each neuron with the given samples and the given learning ratio-learnSamplesLayer :: Double -> [Neuron] -> [([Double], [Double])] -> [Neuron]-learnSamplesLayer alpha ns = learnSamplesLayerU alpha ns . map (toU *** toU)---- * Quadratic Error---- | Returns the quadratic error of a layer for a given sample-quadErrorU :: [Neuron] -> (UArr Double, UArr Double) -> Double-quadErrorU ns (xs, ys) = let os = computeLayerU ns xs- in (/2) $ sumU $ zipWithU (\o y -> (y - o)**2) os ys---- | Returns the quadratic error of a layer for a given sample-quadError :: [Neuron] -> ([Double], [Double]) -> Double-quadError ns = quadErrorU ns . (toU *** toU)
− AI/HNN/Net.hs
@@ -1,71 +0,0 @@--- | Net module, defining functions to work on a neural network, which is a list of list of neurons -module AI.HNN.Net where--import AI.HNN.Layer-import AI.HNN.Neuron-import Control.Arrow-import Data.List-import Data.Array.Vector--check :: [[Neuron]] -> Bool-check nss = let l = length nss in l > 1 && l < 3--nn :: [[Neuron]] -> [[Neuron]]-nn nss | check nss = nss- | otherwise = error "Invalid nn"---- * Computation---- | Computes the output of the given neural net on the given inputs-computeNetU :: [[Neuron]] -> UArr Double -> UArr Double-computeNetU neuralss xs = let nss = nn neuralss in computeLayerU (nss !! 1) $ computeLayerU (head nss) xs- --- | Computes the output of the given neural net on the given inputs-computeNet :: [[Neuron]] -> [Double] -> [Double]-computeNet neuralss = fromU . computeNetU neuralss . toU---- * Quadratic Error---- | Returns the quadratic error of the neural network on the given sample-quadErrorNetU :: [[Neuron]] -> (UArr Double, UArr Double) -> Double-quadErrorNetU nss (xs,ys) = (sumU . zipWithU (\y s -> (y - s)**2) ys $ computeNetU nss xs)/2.0---- | Returns the quadratic error of the neural network on the given sample-quadErrorNet :: [[Neuron]] -> ([Double], [Double]) -> Double-quadErrorNet nss = quadErrorNetU nss . (toU *** toU)---- | Returns the quadratic error of the neural network on the given samples-globalQuadErrorNetU :: [[Neuron]] -> [(UArr Double, UArr Double)] -> Double-globalQuadErrorNetU nss = sum . map (quadErrorNetU nss)---- | Returns the quadratic error of the neural network on the given samples-globalQuadErrorNet :: [[Neuron]] -> [([Double], [Double])] -> Double-globalQuadErrorNet nss = globalQuadErrorNetU nss . map (toU *** toU)---- * Learning---- | Train the given neural network using the backpropagation algorithm on the given sample with the given learning ratio (alpha)-backPropU :: Double -> [[Neuron]] -> (UArr Double, UArr Double) -> [[Neuron]]-backPropU alpha nss (xs, ys) = [aux (head nss) ds_hidden xs- ,aux (nss !! 1) ds_out output_hidden]- where - output_hidden = computeLayerU (head nss) xs- output_out = computeLayerU (nss !! 1) output_hidden- ds_out = zipWithU (\s y -> s * (1 - s) * (y - s)) output_out ys- ds_hidden = zipWithU (\x s -> x * (1-x) * s) output_hidden . toU $ map (sumU . zipWithU (*) ds_out) . map toU . transpose . map (fromU . weights) $ (nss !! 1)- aux ns ds xs = zipWith (\n d -> n { weights = zipWithU (\w x -> w + alpha * d * x) (weights n) xs }) ns (fromU ds)---- | Train the given neural network using the backpropagation algorithm on the given sample with the given learning ratio (alpha)-backProp :: Double -> [[Neuron]] -> ([Double], [Double]) -> [[Neuron]]-backProp alpha nss = backPropU alpha nss . (toU *** toU)--trainAux :: Double -> [[Neuron]] -> [(UArr Double, UArr Double)] -> [[Neuron]]-trainAux alpha = foldl' (backPropU alpha)---- | Train the given neural network on the given samples using the backpropagation algorithm using the given learning ratio (alpha) and the given desired maximal bound for the global quadratic error on the samples (epsilon)-trainU :: Double -> Double -> [[Neuron]] -> [(UArr Double, UArr Double)] -> [[Neuron]]-trainU alpha epsilon nss samples = until (\nss' -> globalQuadErrorNetU nss' samples < epsilon) (\nss' -> trainAux alpha nss' samples) nss---- | Train the given neural network on the given samples using the backpropagation algorithm using the given learning ratio (alpha) and the given desired maximal bound for the global quadratic error on the samples (epsilon)-train :: Double -> Double -> [[Neuron]] -> [([Double], [Double])] -> [[Neuron]]-train alpha epsilon nss = trainU alpha epsilon nss . map (toU *** toU)
− AI/HNN/Neuron.hs
@@ -1,89 +0,0 @@--- | Neuron module, defining an artificial neuron type and the basical operations we can do on it-module AI.HNN.Neuron where--import Data.Array.Vector-import Data.List---- * Type Definitions, type class instances---- | Our Artificial Neuron type-data Neuron = Neuron {- threshold :: Double- , weights :: UArr Double- , func :: Double -> Double- }--instance Show Neuron where- show n = "Threshold : " ++ show (threshold n) ++ "\nWeights : " ++ show (weights n)---- * Neuron creation---- | Creates a Neuron with the given threshold, weights and transfer function-createNeuronU :: Double -> UArr Double -> (Double -> Double) -> Neuron-createNeuronU t ws f = Neuron { threshold = t, weights = ws, func = f }---- | Equivalent to `createNeuronU t ws heavyside'-createNeuronHeavysideU :: Double -> UArr Double -> Neuron-createNeuronHeavysideU t ws = createNeuronU t ws heavyside---- | Equivalent to `createNeuronU t ws sigmoid'-createNeuronSigmoidU :: Double -> UArr Double -> Neuron-createNeuronSigmoidU t ws = createNeuronU t ws sigmoid---- | Same as createNeuronU, with a list instead of an UArr for the weights (converted to UArr anyway)-createNeuron :: Double -> [Double] -> (Double -> Double) -> Neuron-createNeuron t ws f = createNeuronU t (toU ws) f---- | Same as createNeuronHeavysideU, with a list instead of an UArr for the weights (converted to UArr anyway)-createNeuronHeavyside :: Double -> [Double] -> Neuron-createNeuronHeavyside t ws = createNeuronU t (toU ws) heavyside---- | Same as createNeuronSigmoidU, with a list instead of an UArr for the weights (converted to UArr anyway)-createNeuronSigmoid :: Double -> [Double] -> Neuron-createNeuronSigmoid t ws = createNeuronU t (toU ws) sigmoid---- * Transfer functions---- | The Heavyside function-heavyside :: Double -> Double-heavyside x | x >= 0 = 1.0-heavyside _ = 0.0---- | The Sigmoid function-sigmoid :: Double -> Double-sigmoid x = 1.0 / (1 + exp (-x))---- * Neuron output computation---- | Computes the output of a given Neuron for given inputs-computeU :: Neuron -> UArr Double -> Double-computeU n inputs | lengthU inputs == lengthU (weights n) - = func n $ sumU (zipWithU (*) (weights n) inputs) - threshold n-computeU n inputs = error $ "Number of inputs != Number of weights\n" ++ show n ++ "\nInput : " ++ show inputs---- | Computes the output of a given Neuron for given inputs-compute :: Neuron -> [Double] -> Double-compute n = computeU n . toU---- * Neuron learning with Widrow-Hoff (Delta rule)---- | Trains a neuron with the given sample, of the form (inputs, wanted_result) and the given learning ratio (alpha)-learnSampleU :: Double -> Neuron -> (UArr Double, Double) -> Neuron-learnSampleU alpha n (xs, y) = Neuron { - threshold = threshold n- , weights = map_weights (weights n) (xs, y) - , func = func n- }- where map_weights ws (xs, y) = let s = computeU n xs in- zipWithU (\w_i x_i -> w_i + alpha*(y-s)*x_i) ws xs--learnSample :: Double -> Neuron -> ([Double], Double) -> Neuron-learnSample alpha n (xs, y) = learnSampleU alpha n (toU xs, y)---- | Trains a neuron with the given samples and the given learning ratio (alpha)-learnSamplesU :: Double -> Neuron -> [(UArr Double, Double)] -> Neuron-learnSamplesU alpha = foldl' (learnSampleU alpha)---- | Trains a neuron with the given samples and the given learning ratio (alpha)-learnSamples :: Double -> Neuron -> [([Double], Double)] -> Neuron-learnSamples alpha n samples = learnSamplesU alpha n $ map (\(xs, y) -> (toU xs, y)) samples
+ AI/HNN/Recurrent/Network.hs view
@@ -0,0 +1,121 @@+{-# LANGUAGE BangPatterns, ScopedTypeVariables, RecordWildCards #-}++-- |+-- Module : AI.HNN.Recurrent.Network+-- Copyright : (c) 2012 Gatlin Johnson+-- License : LGPL+-- Maintainer : rokenrol@gmail.com+-- Stability : experimental+-- Portability : GHC+--+-- An implementation of recurrent neural networks in pure Haskell.+--+-- A network is an adjacency matrix of connection weights, the number of+-- neurons, the number of inputs, and the threshold values for each neuron.+--+-- E.g.,+--+-- > module Main where+-- >+-- > import AI.HNN.Recurrent.Network+-- >+-- > main = do+-- > let numNeurons = 3+-- > numInputs = 1+-- > thresholds = replicate numNeurons 0.5+-- > inputs = [[0.38], [0.75]]+-- > adj = [ 0.0, 0.0, 0.0,+-- > 0.9, 0.8, 0.0,+-- > 0.0, 0.1, 0.0 ]+-- > n <- createNetwork numNeurons numInputs adj thresholds :: IO (Network Double)+-- > output <- evalNet n inputs sigmoid+-- > putStrLn $ "Output: " ++ (show output)+--+-- This creates a network with three neurons (one of which is an input), an+-- arbitrary connection / weight matrix, and arbitrary thresholds for each neuron.+-- Then, we evaluate the network with an arbitrary input.+--+-- For the purposes of this library, the outputs returned are the values of all+-- the neurons except the inputs. Conceptually, in a recurrent net *any*+-- non-input neuron can be treated as an output, so we let you decide which+-- ones matter.++module AI.HNN.Recurrent.Network (++ -- * Network type+ Network, createNetwork,+ weights, size, nInputs, thresh,++ -- * Evaluation functions+ computeStep, evalNet,++ -- * Misc+ sigmoid++) where++import System.Random.MWC+import Control.Monad+import Numeric.LinearAlgebra+import Foreign.Storable as F++-- | Our recurrent neural network+data Network a = Network+ { weights :: !(Matrix a)+ , size :: {-# UNPACK #-} !Int+ , nInputs :: {-# UNPACK #-} !Int+ , thresh :: !(Vector a)+ } deriving Show++-- | Creates a network with an adjacency matrix of your choosing, specified as+-- an unboxed vector. You also must supply a vector of threshold values.+createNetwork :: (Variate a, Fractional a, Storable a) =>+ Int -> -- ^ number of total neurons neurons (input and otherwise)+ Int -> -- ^ number of inputs+ [a] -> -- ^ flat weight matrix+ [a] -> -- ^ threshold (bias) values for each neuron+ IO (Network a) -- ^ a new network++createNetwork n m matrix thresh = return $!+ Network ( (n><n) matrix ) n m (n |> thresh)++-- | Evaluates a network with the specified function and list of inputs+-- precisely one time step. This is used by `evalNet` which is probably a+-- more convenient interface for client applications.+computeStep :: (Variate a, Num a, F.Storable a, Product a) =>+ Network a -> -- ^ Network to evaluate input+ Vector a -> -- ^ vector of pre-existing state+ (a -> a) -> -- ^ activation function+ Vector a -> -- ^ list of inputs+ Vector a -- ^ new state vector++computeStep (Network{..}) state activation input =+ mapVector activation $! zipVectorWith (-) (weights <> prefixed) thresh+ where+ prefixed = Numeric.LinearAlgebra.join+ [ input, (subVector nInputs (size-nInputs) state) ]+ {-# INLINE prefixed #-}++-- | Iterates over a list of input vectors in sequence and computes one time+-- step for each.+evalNet :: (Num a, Variate a, Fractional a, Product a) =>+ Network a -> -- ^ Network to evaluate inputs+ [[a]] -> -- ^ list of input lists+ (a -> a) -> -- ^ activation function+ IO (Vector a) -- ^ output state vector++evalNet n@(Network{..}) inputs activation = do+ s <- foldM (\x -> computeStepM n x activation) state inputsV+ return $! subVector nInputs (size-nInputs) s+ where+ state = fromList $ replicate size 0.0+ {-# INLINE state #-}+ computeStepM n s a i = return $ computeStep n s a i+ {-# INLINE computeStepM #-}+ inputsV = map (fromList) inputs+ {-# INLINE inputsV #-}++-- | It's a simple, differentiable sigmoid function.+sigmoid :: Floating a => a -> a+sigmoid !x = 1 / (1 + exp (-x))+{-# INLINE sigmoid #-}
LICENSE view
@@ -1,65 +1,30 @@-GNU LESSER GENERAL PUBLIC LICENSE--Version 3, 29 June 2007--Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>--Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.--This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.-0. Additional Definitions.--As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.--“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.--An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.--A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.--The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.--The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.-1. Exception to Section 3 of the GNU GPL.--You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.-2. Conveying Modified Versions.--If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:-- * a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or- * b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.--3. Object Code Incorporating Material from Library Header Files.--The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:-- * a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.- * b) Accompany the object code with a copy of the GNU GPL and this license document.--4. Combined Works.--You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:-- * a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.- * b) Accompany the Combined Work with a copy of the GNU GPL and this license document.- * c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.- * d) Do one of the following:- o 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.- o 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.- * e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)--5. Combined Libraries.+Copyright (c) 2012, Alp Mestanogullari <alpmestan@gmail.com> -You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:+All rights reserved. - * a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.- * b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.+Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met: -6. Revised Versions of the GNU Lesser General Public License.+ * Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer. -The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.+ * Redistributions in binary form must reproduce the above+ copyright notice, this list of conditions and the following+ disclaimer in the documentation and/or other materials provided+ with the distribution. -Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.+ * Neither the name of Alp Mestanogullari <alpmestan@gmail.com> nor the names of other+ contributors may be used to endorse or promote products derived+ from this software without specific prior written permission. -If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
− Setup.lhs
@@ -1,3 +0,0 @@-#!/usr/bin/env runhaskell-> import Distribution.Simple-> main = defaultMain
hnn.cabal view
@@ -1,15 +1,43 @@ name: hnn-version: 0.1-synopsis: A minimal Haskell Neural Network Library-description: hnn provides minimal types and functions to create, train and use feed forward neural networks <http://www.haskell.org/haskellwiki/HNN>-category: AI-license: LGPL+version: 0.2.0.0+synopsis: A reasonably fast and simple neural network library+description: + .+ A neural network library implemented purely in Haskell, relying on the+ hmatrix library.+ .+ This library provides a straight and simple feed-forward neural networks implementation which+ is way better than the one in hnn-0.1, in all aspects. It also provides a simple and little tested+ implementation of recurrent neural networks.+ .+ If you're interested in the feed-forward neural networks, please read the mini-tutorial on+ @AI.HNN.FF.Network@.+homepage: http://github.com/alpmestan/hnn+bug-reports: http://github.com/alpmestan/hnn/issues+license: BSD3 license-file: LICENSE-author: Alp Mestanogullari-maintainer: alpmestan@gmail.com-build-depends: base >= 3 && <= 5-build-type: Simple -cabal-version: >= 1.2-Library- Build-Depends: uvector, base >= 3 && <= 5- Exposed-modules: AI.HNN.Neuron, AI.HNN.Layer, AI.HNN.Net+author: Alp Mestanogullari <alpmestan@gmail.com>, Gatlin Johnson <rokenrol@gmail.com>+maintainer: Alp Mestanogullari <alpmestan@gmail.com>+copyright: 2009-2014 Alp Mestanogullari, Gatlin Johnson+category: AI+build-type: Simple+cabal-version: >=1.8++library+ exposed-modules: AI.HNN.FF.Network, AI.HNN.Recurrent.Network+ build-depends:+ base >=4 && <5,+ vector,+ mwc-random,+ hmatrix >= 0.16,+ random,+ vector-binary-instances >= 0.2,+ binary,+ zlib,+ bytestring+ ghc-options: -O2 -funbox-strict-fields -Wall+ ghc-prof-options: -O2 -funbox-strict-fields -Wall -prof -auto-all -rtsopts++source-repository head+ type: git+ location: http://github.com/alpmestan/hnn.git