Skip to content

Instantly share code, notes, and snippets.

@smrmkt
Last active December 28, 2015 13:49
Show Gist options
  • Save smrmkt/7510158 to your computer and use it in GitHub Desktop.
Save smrmkt/7510158 to your computer and use it in GitHub Desktop.
simple perceptron and graph sample using R
#パラメタ
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)
}
#判別もとデータのプロット
plot(cbind(x[c(2, 4, 5), 2], rep(0, 3)), col="red", xlim=c(-10, 10), ylim=c(-10,10), xlab="x", ylab="y")
par(new=T)
plot(cbind(x[c(1, 3, 6), 2], rep(0, 3)), col="blue", xlim=c(-10, 10), ylim=c(-10,10), xlab="x", ylab="y")
#全データで重みベクトルが更新されなくなるまで繰り返す
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
curve(w[2]*x+w[1], -10, 10, add=T, col="lightgray")
Sys.sleep(1)
}
print(w)
}
}
curve(w[2]*x+w[1], -10, 10, add=T, col="black")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment