R: ksvm function - error: object is not a matrix

R: ksvm function - error: object is not a matrix

我似乎在使用 ksvm 函数时遇到错误。每次我尝试 运行 下面的代码时,我都会收到一条错误消息

Error in model.frame.default(data = ..1, formula = x) : 
object is not a matrix

我问过同事,但似乎没有人能够复制这一点(无论出于何种原因)。任何援助将不胜感激。请看下面的代码:

注意:我已经尝试使用 as.matrix。我得到同样的错误

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)

变量 type 不在数据框中。如果您有一个名为 type 的变量,它就可以正常工作:

## 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