Skip to content

Instantly share code, notes, and snippets.

@neizod
Last active December 19, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neizod/5927048 to your computer and use it in GitHub Desktop.
Save neizod/5927048 to your computer and use it in GitHub Desktop.
Simple perceptron train in Haskell.
type Vector = (Double, Double)
dotV :: Vector -> Vector -> Double
dotV (x, y) (u, v) = x * u + y * v
addV :: Vector -> Vector -> Vector
addV (x, y) (u, v) = (x + u, y + v)
negV :: Vector -> Vector
negV (x, y) = (-x, -y)
predict :: Vector -> Vector -> Int
predict xy uv | dotV xy uv > 0 = 1
| otherwise = -1
predictAll :: Vector -> [Vector] -> [Int]
predictAll xy = map $ predict xy
trainOnce :: Vector -> Vector -> Int -> Vector
trainOnce xy uv z | z == predict xy uv = xy
| z == 1 = addV xy uv
| otherwise = addV xy (negV uv)
train :: Vector -> [(Vector,Int)] -> Vector
train = foldl $ \xy (uv,z) -> trainOnce xy uv z
getPerceptron :: IO (Vector, Int)
getPerceptron = do
raw <- getLine
let [u,v] = take 2 $ map read $ words raw
z = read $ last $ words raw
return ((u,v),z)
main :: IO ()
main = do
rn <- getLine
ls <- sequence $ replicate (read rn) getPerceptron
print $ train (0,0) ls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment