Last active
December 19, 2015 08:39
-
-
Save neizod/5927048 to your computer and use it in GitHub Desktop.
Simple perceptron train in Haskell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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