如何解决R:ksvm函数-错误:对象不是矩阵
我似乎在使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。