Skip to content

Instantly share code, notes, and snippets.

@hoxo-m
Created September 13, 2019 13:03
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 hoxo-m/445b23bcc0e98b472cc35fda04e8836d to your computer and use it in GitHub Desktop.
Save hoxo-m/445b23bcc0e98b472cc35fda04e8836d to your computer and use it in GitHub Desktop.
機械学習やってるGIFつくるやつ
library(dplyr)
library(ggplot2)
data <- iris %>% filter(Species != "setosa") %>%
select(Petal.Width, Sepal.Length, Species) %>%
sample_frac(1)
ggplot(data, aes(Petal.Width, Sepal.Length)) +
geom_point(aes(color = Species), size=4) + xlab("") + ylab("") +
scale_x_continuous(label=NULL) +
scale_y_continuous(label=NULL) +
scale_color_discrete(guide = FALSE) +
theme_bw()
library(animation)
x <- data %>% select(-Species) %>% mutate(c=1) %>% as.matrix
y <- (as.integer(data$Species) - 2.5) * 2
w <- matrix(0, nrow = 3, ncol = 1)
plot_contour <- function(data, w, iter) {
new_x <- expand.grid(Petal.Width = seq(1.0, 2.5, length.out = 100),
Sepal.Length = seq(4.9, 7.9, length.out = 100), c = 1)
score <- (as.matrix(new_x) %*% w) %>% scale
df <- new_x %>% mutate(score = score)
ggplot(data, aes(Petal.Width, Sepal.Length)) +
geom_point(aes(color = Species), size=5) +
geom_contour(data = df, aes(Petal.Width, Sepal.Length, z=score), bins = 1, size=2) +
xlab(NULL) + ylab(NULL) +
ggtitle(sprintf("iteration: %d", iter)) +
scale_x_continuous(label=NULL) +
scale_y_continuous(label=NULL) +
scale_color_discrete(guide = FALSE) +
theme_bw()
}
eta <- 0.001
C <- 0.2
pb <- txtProgressBar(max = 25, style = 3L)
animation::saveGIF({
w <- matrix(0, nrow = 3, ncol = 1)
for (j in 1:25) {
setTxtProgressBar(pb, j)
for (i in seq_len(nrow(x))) {
if (y[i] * x[i, , drop=FALSE] %*% w <= 1) {
w2 <- w + eta * y[i] * t(x[i, , drop=FALSE])
}
w <- w2 - 2 * eta * C * w
if (i %% 10 == 0) {
plot_contour(data, w, (j-1) * 100 + i) %>% print
}
}
}
for (k in 1:50) {
plot_contour(data, w, (j-1) * 100 + i) %>% print
}
}, interval = 0.1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment