I seem to be encountering an error using the ksvm function. Each time I try to run the below code I get an error message
Error in model.frame.default(data = ..1, formula = x) :
object is not a matrix
I have asked colleagues, but no one seems able to replicate this (for whatever reason). Any assistance would be appreciated. Please see the code below:
Note: I have already tried using as.matrix. I get the same error
library(kernlab)
#Import airquality df
aq_df<-airquality
#Function to replace NA's
replaceNAs<-function(df,df_col)
{
for (i in 1:dim(df)[1])
{
if(is.na(df_col[i]))
{
#print(df_col[i])
df_col[i]<-mean(na.omit(df_col))
}
}
return(df_col)
}
#Call the function to replace NA's with mean
aq_df$Ozone<-replaceNAs(aq_df,aq_df$Ozone)
aq_df$Solar.R<-replaceNAs(aq_df,aq_df$Solar.R)
aq_df$Wind<-replaceNAs(aq_df,aq_df$Wind)
aq_df$Temp<-replaceNAs(aq_df,aq_df$Temp)
#Setup ksvm
randIndex<-sample(1:dim(aq_df)[1])
cutPoint_23<-floor(2*dim(aq_df)[1]/3)
trainData<-aq_df[randIndex[1:cutPoint_23],]
testData<-aq_df[randIndex[(cutPoint_23+1):dim(aq_df)[1]],]
svmOutput<-ksvm(type ~.,data=trainData, kernel="rbfdot",kpar="automatic",C=5,cross=3,prob.model=TRUE)
The variable type
isn't in the data frame. If you had a variable called type
, it would work just fine:
## add a variable named type
aq_df$type <- sample(1:2, nrow(aq_df), replace=TRUE)
## proceed as above
#Setup ksvm
randIndex<-sample(1:dim(aq_df)[1])
cutPoint_23<-floor(2*dim(aq_df)[1]/3)
trainData<-aq_df[randIndex[1:cutPoint_23],]
testData<-aq_df[randIndex[(cutPoint_23+1):dim(aq_df)[1]],]
svmOutput<-ksvm(type ~.,data=trainData,
kernel="rbfdot",kpar="automatic",
C=5,cross=3,prob.model=TRUE)
svmOutput
# Support Vector Machine object of class "ksvm"
#
# SV type: eps-svr (regression)
# parameter : epsilon = 0.1 cost C = 5
#
# Gaussian Radial Basis kernel function.
# Hyperparameter : sigma = 0.161753619421595
#
# Number of Support Vectors : 93
#
# Objective Function Value : -225.2614
# Training error : 0.413681
# Cross validation error : 0.373122
# Laplace distr. width : 0.952921