Skip to content

Instantly share code, notes, and snippets.

@smrmkt
Last active December 27, 2015 13:39
Show Gist options
  • Save smrmkt/7334696 to your computer and use it in GitHub Desktop.
Save smrmkt/7334696 to your computer and use it in GitHub Desktop.
simple perceptron R sample
x <- matrix(c(1, 1, 1, 1, 1, 1, 3, 7, 1, 5, 4, 2), 6, 2) #素性ベクトル
l <- c(-1, 1, -1, 1, 1, -1) #ラベル
w <- c(0, 0) #重みベクトル
r <- 0.5 #学習係数
#重みベクトルの更新メソッド
update <- function(x, l, w) {
if (sign(x %*% w) == sign(l)) {
return(w)
}
return(w+r*x*l)
}
#全データで重みベクトルが更新されなくなるまで繰り返す
c <- 0
while (c < nrow(x)) {
for (i in 1:nrow(x)) {
tmp <- update(x[i,], l[i], w)
if (all(tmp == w)) {
c <- c+1
} else {
w <- tmp
c <- 0
}
print(w)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment