【发布时间】:2013-12-29 14:02:23
【问题描述】:
我在 [-1,1]^2 区间内生成了一个包含 100 个随机 x-y 坐标的矩阵:
n <- 100
datam <- matrix(c(rep(1,n), 2*runif(n)-1, 2*runif(n)-1), n)
# leading 1 column needed for computation
# second column has x coordinates, third column has y coordinates
并通过给定的目标函数 f(向量)将它们分为 2 类 -1 和 1。 我计算了一个假设函数 g,现在想可视化它与 目标函数 f.
f <- c(1.0, 0.5320523, 0.6918301) # the given target function
ylist <- sign(datam %*% f) # classify into -1 and 1
# perceptron algorithm to find g:
perceptron = function(datam, ylist) {
w <- c(1,0,0) # starting vector
made.mistake = TRUE
while (made.mistake) {
made.mistake=FALSE
for (i in 1:n) {
if (ylist[i] != sign(t(w) %*% datam[i,])) {
w <- w + ylist[i]*datam[i,]
made.mistake=TRUE
}
}
}
return(w=w)
}
g <- perceptron(datam, ylist)
我现在想在情节中比较 f 和 g。
我可以在数学中很容易地做到这一点。此处显示的是具有目标函数 f 的数据集,该函数将 +1 和 -1 部分中的数据分开:
这个数学图显示了 f 和 g 的比较(不同的数据集和 f)
这是对应的mathematica代码
ContourPlot[g.{1, x1, x2} == 0, {x1, -1, 1}, {x2, -1, 1}]
如何在 R 中做类似的事情(ggplot 会很好)?
【问题讨论】:
-
是的,这是可能的。但是您的示例不可重现,因此我无法用代码回答您。
-
抱歉,我为一个工作示例添加了代码
-
@James 我不确定这是否是重复的。在我看来,OP 要求一种方法来从数据中获取区分边界,而不是如何在绘图上产生阴影。