首页 > 解决方案 > 如何修复 SVM 中的“不一致数组”错误?

问题描述

目前使用示例数据集练习 SVM,我正在尝试将 abline 添加到绘图中,但说 w[1,2] 不是正确的维度,导致我回到创建的变量“w”,其中“coefs”和“SV”不想在代码中工作

我试过小写 SV,它有效,但结果是 w | 数字(空)而不是 num [1, 1:2] -0.035 -0.0188。

structure(list(Height = c(44, 52.1, 57.1, 33, 27.8, 27.2, 32, 
45.1, 56.7, 56.9, 122.1, 123.9, 122.9, 101.1, 128.9, 137.1, 127, 
103, 141.6, 102.4), Weight = c(126.3, 136.9, 109.2, 148.3, 110.4, 
107.8, 128.4, 120.2, 140.2, 139.2, 154.1, 170.8, 183.1, 164, 
193.6, 181.7, 164.8, 174.6, 185.8, 176.9)), class = "data.frame", row.names = c(NA, 
-20L))
#create an is horse indicator variable
ishorse <- c(rep(-1,10),rep(+1,10))

library(e1071)

#create data frame for performing svm
data <- data.frame(Height= animal_data['Height'],
                   Weight= animal_data['Weight'],
                   animal=as.factor(ishorse))
#plot data
plot(data[,-3],col=(3)/2, pch=19); abline(h=0,v=0,lty=3)
#perform svm
svm.model <- svm(animal ~ .,
                 data=data,
                 type='C-classification',
                 kernel='linear',
                 scale=FALSE)
#show support vectors
points(data[svm.model$index, c(1,2)], col="orange", cex = 2)
#get parameters of hyperplane
w <- t(svm.model$coefs) %% svm.model$SV
b <- -svm.model$rho
#in this 2D case the hyperplane is the line w[1,1]*x1 + w[1,2]*2 +b = 0
abline(a=-b/w[2,2], b=-w[,]/w[,], col = "blue", lty = 3)

标签: r

解决方案


矩阵乘法的正确语法是%*%. 试试这个:

svm.model <- svm(animal ~ .,
                 data=data,
                 type='C-classification',
                 kernel='linear',
                 scale=FALSE)
#show support vectors
points(data[svm.model$index, c(1,2)], col="orange", cex = 2)
#get parameters of hyperplane
w <- t(svm.model$coefs) %*% svm.model$SV
b <- -1*svm.model$rho
#in this 2D case the hyperplane is the line w[1,1]*x1 + w[1,2]*2 +b = 0
abline(a=-b/w[1,2], b=-w[1]/w[2], col = "blue", lty = 3)

推荐阅读