Skip to content

Instantly share code, notes, and snippets.

@einblicker
Created November 29, 2011 09:51
Show Gist options
  • Save einblicker/1404219 to your computer and use it in GitHub Desktop.
Save einblicker/1404219 to your computer and use it in GitHub Desktop.
perceptron
object Perceptron {
type Vec = Map[Symbol, Double]
def makeVec(R: Double, G: Double, B: Double, bias: Double): Vec =
Map('R -> R, 'G -> G, 'B -> B, 'bias -> bias)
def predict(w: Vec, x: Vec): Double =
w.keys.filter(w(_) != 0).map(k => w(k) * x(k)).sum
def train(w: Vec, x: Vec, t: Double): Vec =
if (predict(w, x) * t < 0)
x.map{case (k, v) => (k, w(k) + t * x(k))}
else
w
val xs: List[Vec] =
List(Map('R -> 255, 'G -> 0, 'B -> 0, 'bias -> 1),
Map('R -> 0, 'G -> 255, 'B -> 255, 'bias -> 1),
Map('R -> 0, 'G -> 255, 'B -> 0, 'bias -> 1),
Map('R -> 255, 'G -> 0, 'B -> 255, 'bias -> 1),
Map('R -> 0, 'G -> 0, 'B -> 255, 'bias -> 1),
Map('R -> 255, 'G -> 255, 'B -> 0, 'bias -> 1))
val ts: List[Double] = List(1, -1, -1, 1, -1, 1)
val w0: Vec = Map('R -> 0, 'G -> 0, 'B -> 0, 'bias -> 1)
val trainingSet = Iterator.continually(xs zip ts).take(10).flatten
val wn = trainingSet.foldLeft(w0){
case (w, (x, t)) => train(w, x, t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment