Skip to content

Instantly share code, notes, and snippets.

@novotnyr
Created January 8, 2014 23:45
Show Gist options
  • Save novotnyr/8326908 to your computer and use it in GitHub Desktop.
Save novotnyr/8326908 to your computer and use it in GitHub Desktop.
Haskell Perceptron
module Main where
import Debug.Trace
threshold = 0.5
learningRate = 0.1
weights = [0, 0, 0] :: [Double]
trainingSet = [
([1, 0, 0], 1),
([1, 0, 1], 1),
([1, 1, 0], 1),
([1, 1, 1], 0) ] :: [ ([Double], Int) ]
dotProduct vec1 vec2 = sum $ zipWith (*) vec1 vec2
add v1 v2 = zipWith (+) v1 v2
timesScalar vector n = map (* n) vector
timesVector n vector = map (* n) vector
cmp o1 o2
| o1 < o2 = 1
| otherwise = 0
train threshold learningRate (_, weights) (inputVector, desiredOutput) =
traceShow ("s=", s, "n=", n, "e=", error) $
(error /= 0, newWeights)
where error = fromIntegral (desiredOutput - result)
s = inputVector `dotProduct` weights
n = s `cmp` threshold
result = desiredOutput - n
newWeights = weights `add` ((learningRate * error) `timesVector` inputVector)
trainExampleSet threshold learningRate weights exampleSet =
(isError, newWeights)
where
newWeights = snd $ last singleExampleTrainingResults
isError = all (\_ -> True) $ map fst singleExampleTrainingResults
singleExampleTrainingResults = scanl (train threshold learningRate) (True, weights) trainingSet
classify example weights =
dotProduct example weights
main::IO()
main = do
-- print $ trainExampleSet threshold learningRate weights trainingSet
let learnedWeights = snd $ last $ take 10 $ scanl (\(isError, w) ts -> trainExampleSet threshold learningRate w ts) (True, weights) (cycle [trainingSet])
print $ classify [1,1,1] learnedWeights
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment