I am new to R and trying to save my svm model in R and have read the documentation but still do not understand what is wrong.
I am getting the error "object is not a matrix" which would seem to mean that my data is not a matrix, but it is... so something is missing.
My data is defined as:
data = read.table("data.csv") trainSet = as.data.frame(data[,1:(ncol(data)-1)]) Where the last line is my label
I am trying to define my model as:
svm.model <- svm(type ~ ., data=trainSet, type='C-classification', kernel='polynomial',scale=FALSE) This seems like it should be correct but I am having trouble finding other examples.
Here is my code so far:
# load libraries require(e1071) require(pracma) require(kernlab) options(warn=-1) # load dataset SVMtimes = 1 KERNEL="polynomial" DEGREE = 2 data = read.table("head.csv") results10foldAll=c() # Cross Fold for training and validation datasets for(timesRun in 1:SVMtimes) { cat("Running SVM = ",timesRun," result = ") trainSet = as.data.frame(data[,1:(ncol(data)-1)]) trainClasses = as.factor(data[,ncol(data)]) model = svm(trainSet, trainClasses, type="C-classification", kernel = KERNEL, degree = DEGREE, coef0=1, cost=1, cachesize = 10000, cross = 10) accAll = model$accuracies cat(mean(accAll), "/", sd(accAll),"\n") results10foldAll = rbind(results10foldAll, c(mean(accAll),sd(accAll))) } # create model svm.model <- svm(type ~ ., data = trainSet, type='C-classification', kernel='polynomial',scale=FALSE) An example of one of my samples would be:
10.135338 7.214543 5.758917 6.361316 0.000000 18.455875 14.082668 31 32 Answers
Here, trainSet is a data frame but in the svm.model function it expects data to be a matrix(where you are assigning trainSet to data). Hence, set data = as.matrix(trainSet). This should work fine.
1Indeed as pointed out by @user5196900 you need a matrix to run the svm(). However beware that matrix object means all columns have same datatypes, all numeric or all categorical/factors. If this is true for your data as.matrix() may be fine.
In practice more than often people want to model.matrix() or sparse.model.matrix() (from package Matrix) which gives dummy columns for categorical variables, while having single column for numerical variables. But a matrix indeed.