課題名
rm(list = ls())
library(MASS)
n <- 100
c <- vector('list', 7)
c[[1]] <- mvrnorm(n, mu = c( 0, 0), Sigma = rbind(c(2.0, 0.0), c( 0.0, 2.0)))
c[[2]] <- mvrnorm(n, mu = c( 0, 10), Sigma = rbind(c(2.0, -0.8), c(-0.8, 2.0)))
c[[3]] <- mvrnorm(n, mu = c(10, 0), Sigma = rbind(c(2.0, -0.8), c(-0.8, 2.0)))
c[[4]] <- mvrnorm(n, mu = c(-5, -5), Sigma = rbind(c(2.0, 0.8), c( 0.8, 2.0)))
c[[5]] <- mvrnorm(n, mu = c( 5, 5), Sigma = rbind(c(2.0, 0.8), c( 0.8, 2.0)))
c[[6]] <- mvrnorm(n, mu = c(-5, 5), Sigma = rbind(c(2.0, -0.8), c(-0.8, 2.0)))
c[[7]] <- mvrnorm(n, mu = c( 5, -5), Sigma = rbind(c(2.0, -0.8), c(-0.8, 2.0)))
for (i in seq_along(c))
{
c[[i]] <- as.data.frame(c[[i]])
colnames(c[[i]]) <- c('x', 'y')
}
# 単純な分類用データ
d <- data.frame(c(rep(1, n), rep(0, n)), rbind(c[[1]], c[[5]]))
colnames(d) <- c('blue', 'x', 'y')
# カラーパレット
COL <- c(rgb(255, 0, 0, 105, max = 255), # 赤
rgb( 0, 0, 255, 105, max = 255), # 青
rgb( 0, 155, 0, 105, max = 255), # 緑
rgb(100, 100, 100, 20, max = 255)) # 灰
#cairo_pdf('red_blue.pdf')
matplot (NA, type = 'n', xlim = c(-10, 10), ylim = c(-10, 10),
xlab = 'x', ylab = 'y')
grid()
matlines(x = c[[1]]$x, y = c[[1]]$y, type = 'p', pch = 1, col = COL[2])
matlines(x = c[[4]]$x, y = c[[4]]$y, type = 'p', pch = 1, col = COL[1])
matlines(x = c[[5]]$x, y = c[[5]]$y, type = 'p', pch = 1, col = COL[1])
matlines(x = c[[6]]$x, y = c[[6]]$y, type = 'p', pch = 1, col = COL[1])
matlines(x = c[[7]]$x, y = c[[7]]$y, type = 'p', pch = 1, col = COL[1])
legend('topright', col = COL[1:2], pch = c(1, 1), bg = 'white',
legend = c('赤', '青'))

library(e1071)
# カーネル
KERNEL <- c('linear', 'polynomial', 'sigmoid', 'radial')
k <- 1 # カーネル選択番号
# 交差検証法によるパラメータ選択
cv <- tune('svm', as.factor(blue) ~ ., data = d,
kernel = KERNEL[k], type = 'C-classification',
ranges = list(#gamma = 2^(-4:4),
#epsilon = seq(0, 1, 0.1),
#coef0 = 2^(-4:4),
cost = 2^(-4:4)))
# 結果表示
cv
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost
## 0.0625
##
## - best performance: 0
KERNEL # カーネル関数の種類
## [1] "linear" "polynomial" "sigmoid" "radial"
# 複雑な分類用データ
d <- data.frame(c(rep(1, n*3), rep(0, n*4)),
rbind(c[[1]], c[[2]], c[[3]], c[[4]], c[[5]], c[[6]], c[[7]]))
colnames(d) <- c('blue', 'x', 'y')
head(d)
## blue x y
## 1 1 -1.5990180 -2.9114466
## 2 1 -0.2637146 0.6781409
## 3 1 2.3267272 1.0932076
## 4 1 -1.4125658 1.3985736
## 5 1 0.8898399 -2.1935555
## 6 1 0.2930800 -4.8146943
# 図枠
matplot (NA, type = 'n',
xlim = c(-10, 15), ylim = c(-10, 20),
xlab = 'x', ylab = 'y')
grid() # 格子線
# データ抽出
d.red <- d[d$blue == 0, ] # 赤データ
d.blue <- d[d$blue == 1, ] # 青データ
# 描画
matlines(x = d.red$x, y = d.red$y, type = 'p', pch = 1, col = COL[1])
matlines(x = d.blue$x, y = d.blue$y, type = 'p', pch = 1, col = COL[2])
# 凡例
legend('topright', col = COL[1:2], pch = c(1, 1), bg = 'white',
legend = c('赤', '青'))

plot(1:9)
