【发布时间】:2016-06-10 11:33:06
【问题描述】:
我已经为我的向量创建了正确数量的索引,并且我正在尝试从 for 循环中输入第 i 个元素作为索引来保存分类错误值。但我得到了错误:
indeces.gen_error[[i]] 中的错误 尝试选择少于一个元素
我的代码:
library(e1071)
library(caret)
set.seed(733)
uspscldf = read.table('uspscl.txt', header=F, sep=',')
uspsdatadf = read.table('uspsdata.txt', header=F, sep='\t')
trainIndex <- createDataPartition(uspscldf$V1,list=FALSE, p = .80,times=1)
dataTrain <- uspsdatadf[ trainIndex,]
dataTest <- uspsdatadf[-trainIndex,]
classTrain <- uspscldf[ trainIndex,]
classTest <- uspscldf[-trainIndex,]
indeces = seq(0.00001, 1, by=0.001)
indeces.gen_error = NULL
indeces.softmargin = NULL
for (i in seq(0.00001, 1, by=0.001)){
# For svm(): soft margin is "cost"
# Gaussian kernel bandwidth (sigma) = is implicitly defined by "gamma"
# kernal=radial is non-linear while kernal=linear is linear
svm.model <- svm(classTrain ~ ., data = dataTrain, cost = i,type="C-classification",kernal = "linear")
svm.pred <- predict(svm.model, dataTrain)
# confusion matrix
tab <- table(pred = svm.pred, true = classTrain)
classification_error <- 1- sum(svm.pred == classTrain)/length(svm.pred)
indeces.gen_error[[i]] <- paste(classification_error)
indeces.softmargin[[i]]<-i
}
我在第一次迭代中打印了第一个 i,它给出了 1e-5,这是正确的,所以我不知道为什么它说我选择的元素少于一个。 任何帮助,将不胜感激。谢谢
回答::: 在我自己解决答案之前,我没有看到皮埃尔对此的回答,但他的解释更好,所以我接受他的回答。我现在的新代码是:
indeces = seq(0.00001, 1, by=0.001)
indeces.gen_error = NULL
indeces.softmargin = NULL
count=0
for (i in indeces){
count=count+1
# For svm(): soft margin is "cost"
# Gaussian kernel bandwidth (sigma) = is implicitly defined by "gamma"
# kernal=radial is non-linear while kernal=linear is linear
svm.model <- svm(classTrain ~ ., data = dataTrain, cost = i,type="C-classification",kernal = "linear")
svm.pred <- predict(svm.model, dataTrain)
# confusion matrix
tab <- table(pred = svm.pred, true = classTrain)
classification_error <- 1- sum(svm.pred == classTrain)/length(svm.pred)
indeces.gen_error[[count]] <- paste(classification_error)
indeces.softmargin[[count]]<-i
}
【问题讨论】:
-
你能解释一下 0.00001 的索引对数组意味着什么吗?索引应该是整数;如果不是,它们会以某种方式被强制(在这种情况下,这似乎会给您带来问题)。
-
在 Stack Overflow 上,任何调试问题(“为什么这段代码不起作用?”)都必须包含一个可重现的示例。在这种情况下,我们没有 uspscl.txt 或 uspsdata.txt,因此我们无法复制您的错误。您可以发布数据样本或使用内置数据集来使您的问题可重现。要阅读有关 R 中可重现示例的更多信息,请参阅stackoverflow.com/questions/5963269。
-
您正在使用
0.00001之类的值进行子集化。我确定这不是故意的。要查看重现的错误,请尝试x <- NULL; x[[0.001]] <- "a" -
@josliber 我添加了文本文件。
-
@PierreLafortune hm 我看到你复制了代码,但我还是不明白。