我是R的新手,试图用线性核创建一个SVM模型。
下面是代码。
library(e1071)
svm.narrow.margin <- svm(Diagnosis~.,
data = biomed,
type = "C-classification",
cost = 1.0,
kernel = "linear")
然而它却返回了这个错误信息。
Error in if (any(as.integer(y) != y)) stop("因变量必须是分类模式的因子或整数类型。") : 缺少了需要TRUEFALSE的值此外。警告信息:在svm.default(x,y,scale = scale,...,na.action = na.action)中:由强制引入的NAs。
我在R Studio Cloud上运行了同样的一套代码,却能正常工作,这让人很困惑。
请Halp!
让我们尝试着把问题重现出来,并走一遍解决方法。
这样就可以了。
svm_works <- svm(Species~., data = iris, type = "C-classification", cost = 1.0,
kernel = "linear")
> svm_works
Call:
svm(formula = Species ~ ., data = iris, type = "C-classification", cost = 1,
kernel = "linear")
Parameters:
SVM-Type: C-classification
SVM-Kernel: linear
cost: 1
Number of Support Vectors: 29
SVM的结果必须是一个分类器, 或者用R术语来说是一个因子,比如Species。
> str(iris)
'data.frame': 150 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
让我们看看当我们将预测器改为非因子变量时会发生什么。这将产生你的错误。
#Change predictor to non-factor, like Sepal.Length
> svm_not_work <- svm(Sepal.Length~., data = iris, type = "C-classification",
cost = 1.0, kernel = "linear")
Error in svm.default(x, y, scale = scale, ..., na.action = na.action) :
dependent variable has to be of factor or integer type for classification mode.
所以很可能你的分类器,或者预测器,或者你的公式中的y (y~., data=data)
这些都是同义词)有问题。