How to fix 'non-conformable arrays' error in SVM?

时间:2019-04-16 23:56:30

标签: r

Currently practicing SVM with a sample dataset and I'm trying to add the abline to the plot but says that w[1,2] is not the correct dimensions, leading me back to the created variable 'w' in which 'coefs' and 'SV' are not wanting to work in the code

I've tried lowercasing SV, which works but results in w | numeric (empty) instead of 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)

1 个答案:

答案 0 :(得分:0)

The correct syntax for matrix multiplication is %*%. Try this:

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)