Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ff4bb89

Browse files
author
Francesco Gadaleta
committed
example of kernel methods in R
1 parent 0808ef9 commit ff4bb89

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

kernels.R

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#############################################
2+
# (c) 2014 Francesco Gadaleta #
3+
#############################################
4+
5+
library(kernlab)
6+
7+
data(spam)
8+
dt <- as.matrix(spam[c(10:20, 3000:3010), -58])
9+
10+
rbf <- rbfdot(sigma = 0.5)
11+
12+
#rbf(o1,o2)
13+
#exp(0.5 * (2 * crossprod(o1, o2) - crossprod(o1) - crossprod(o2)))
14+
#exp(0.5 * (2 * t(o1)%*%o2 - t(o1)%*%o1 - t(o2)%*%o2))
15+
16+
K = kernelMatrix(kernel = rbf, x = dt)
17+
yt <- as.matrix(as.integer(spam[c(10:20, 3000:3010), 58]))
18+
yt[yt==2] = -1
19+
20+
# compute kernel expansion
21+
kernelMult(rbf, dt, , yt)
22+
23+
24+
25+
# 1. example of ksvm
26+
data(promotergene)
27+
tindex <- sample(1:dim(promotergene)[1], 5)
28+
genetrain <- promotergene[-tindex, ]
29+
genetest <- promotergene[tindex, ]
30+
31+
gene <- ksvm(Class ~ ., data = genetrain, kernel = "rbfdot",
32+
kpar = "automatic", C = 60, cross = 3, prob.model = TRUE)
33+
predict(gene, genetest, type="probabilities")
34+
tmp <- genetest[1, -1]
35+
#tmp["V2"] = 'a'
36+
predict(gene, tmp)
37+
38+
# 2. example of ksvm
39+
x <- rbind(matrix(rnorm(120), , 2), matrix(rnorm(120, mean = 3), , 2))
40+
y <- matrix(c(rep(1, 60), rep(-1, 60)))
41+
vp <- ksvm(x, y, type = "C-svc")
42+
plot(vp, data=x)
43+
newdata = matrix(c(2,0.1, 3,3), ncol = 2)
44+
predict(vp, newdata)
45+
46+
# relevance vector machine
47+
rvmm <- rvm(x,y, kernel="rbfdot", kpar=list(sigma=0.1))
48+
yhat <- predict(rvmm, x)
49+
plot(yhat)
50+
51+
52+
# ranking algorithm
53+
data(spirals)
54+
ran <- spirals[rowSums(abs(spirals) < 0.55) == 2, ]
55+
ranked <- ranking(ran, 54, kernel = "rbfdot",
56+
kpar = list(sigma = 100), edgegraph = TRUE)
57+
ranked[54,2] <- max(ranked[-54,2])
58+
c <- 1:86
59+
op <- par(mfrow = c(1, 2), pty = "s")
60+
plot(ran)
61+
plot(ran, cex = c[ranked[, 3]]/40)
62+
63+
64+
# online learning
65+
x <- rbind(matrix(rnorm(90), , 2), matrix(rnorm(90) + 3, , 2))
66+
y <- matrix(c(rep(1, 45), rep(-1, 45)), , 1)
67+
on <- inlearn(2, kernel = "rbfdot", kpar = list(sigma = 0.2), type = "classification")
68+
ind <- sample(1:90, 90)
69+
70+
for (i in ind)
71+
on <- onlearn(on, x[i, ], y[i], nu = 0.03, lambda = 0.1)
72+
sign(predict(on, x))
73+
74+
spc <- specc(x, centers=4)
75+
plot(spc@centers)
76+
plot(x)
77+
78+
79+
80+

0 commit comments

Comments
 (0)