ive train_data将使用感知器进行分类。 感知器分类错误
train_data =data.frame(x_1=c(0,1,4,5,6,8,2,3,5,9,12,14,15,16,17,20,19,16,18,19,0,2,3,4,5,6),
x_2=c(1,4,13,2,14,15,3,7,8,11,12,20,16,14,5,6,8,9,12,10,11,16,17,20,20,19),
y_d=c(1,1,0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0))
p=ggplot(train_data,aes(train_data$x_1,train_data$x_2))
p
train_data$b=1
head(train_data)
x=train_data[,c(1,2,4)]
head(x)
y= train_data[,3]
head(y)
perceptron = function(x,y,rate,epoch){
weight_vector= rep(0,ncol(x))
error=rep(0,epoch)
for (i in 1:epoch) {
for (j in 1:nrow(x)) {
output= sum(weight_vector*x[j,])
if(output<0){
ypred=-1
p+geom_point(aes(x[j,1],x[j,2],col="red"))
}else{
ypred=1
p+geom_point(aes(x[j,1],x[j,2],col="blue"))
}
weightdiff=rate*(y[j]-ypred)*as.numeric(x[j,])
weight_vector=weight_vector+weightdiff
if((y[j]-ypred)!=0.0){
error[i]= error[i]+1
}
return(error)
}
}
}
perceptron(x,y,0.01,100)
感知器函数将所有错误生成为零,除了第一个错误
[1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
[45] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
[89] 0 0 0 0 0 0 0 0 0 0 0 0
这样我就可以划出一条线来对两个类进行分类
答案 0 :(得分:1)
由于算法中存在一些错误(激活函数计算[我采用了Heaviside激活函数],维数),请参阅下面的更正算法。我在代码右侧的#m
中标记了它们。以及由于ggplot2
的内部机制,我在算法计算内部将base::plot
替换为ggplot2
函数。请查看以下结果:
train_data <- structure(list(x_1 = c(0, 1, 4, 5, 6, 8, 2, 3, 5, 9, 12, 14,
15, 16, 17, 20, 19, 16, 18, 19, 0, 2, 3, 4, 5, 6), x_2 = c(1,
4, 13, 2, 14, 15, 3, 7, 8, 11, 12, 20, 16, 14, 5, 6, 8, 9, 12,
10, 11, 16, 17, 20, 20, 19), y_d = c(1, 1, 0, 1, 0, 0, 1, 1,
1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)), class = "data.frame",
row.names = c(NA, -26L))
plot(train_data$x_1, train_data$x_2, type = "n")
perceptron <- function(x, y, rate, epoch){
weight_vector <- rep(0, ncol(x) + 1) #m
error <- rep(0, epoch)
for (i in 1:epoch) {
for (j in 1:length(y)) { #m
output <- sum(weight_vector[2:length(weight_vector)] *
as.numeric(x[j, ])) + weight_vector[1] #m
if (output < 0) {
ypred <- -1
points(x[j, 1], x[j, 2], col = "red", pch = 19, cex = 2)
} else {
ypred <- 1
points(x[j, 1], x[j, 2], col = "blue", pch = 19, cex = 2)
}
weightdiff <- rate * (y[j] - ypred) * c(1, as.numeric(x[j, ])) #m
weight_vector <- weight_vector + weightdiff
if((y[j] - ypred) != 0.0){
error[i] <- error[i] + 1
}
}
}
return(error)
}
x <- train_data[, c(1,2)]
y <- train_data[, 3]
perceptron(x, y, 0.01, 100)
输出:
[1] 13 13 13 15 10 11 11 11 14 14 11 11 10 12 10 11 11 12 13 11 12 10 11 11 12 13 11 12 13 11 11 12 10 12 10
[36] 12 10 12 10 10 10 11 12 11 12 11 12 11 12 11 12 11 12 11 12 12 11 11 12 12 11 11 12 12 11 11 10 11 12 11
[71] 10 12 12 11 11 10 11 12 11 12 10 12 12 10 12 11 10 11 10 12 10 12 10 10 11 10 12 10 12 10