简体   繁体   English

我正在尝试在R中编写一个函数,该函数使用svm进行分类以找到混淆矩阵。

[英]I am trying to write a function in R that finds the confusion matrix using a svm for classification.

I am trying to write a program where the data and the place holder for the y (output) variable are given to the function. 我正在尝试编写一个程序,其中将y(输出)变量的数据和占位符赋予函数。 The function produces the confusion matrix for the data set and the test data. 该函数为数据集和测试数据生成混淆矩阵。 This is in fact my 5th attempt at this sort of function- which is why most of this function is from a manual using the iris data as the data set- but I seem to get stuck on the y.vec input for the function. 实际上,这是我对此类功能的第五次尝试-这就是为什么该功能大部分来自使用虹膜数据作为数据集的手册的原因,但是我似乎陷入了该功能的y.vec输入中。 Is my method for inserting the y variable into the function correct? 我将y变量插入函数的方法正确吗?

Any help would be appreciated and thank you in advance. 任何帮助将不胜感激,并提前感谢您。

Here is my function. 这是我的功能。

function(data,y.vec) 功能(数据,y.vec)

{ {
library(e1071) library(rpart) data=data 库(e1071)库(rpart)数据=数据

index <- 1:nrow(data)
testindex <- sample(index, trunc(length(index)/3))
testset <- data[testindex,]
trainset <- data[-testindex,]

svm.model <- svm(as.factor(data[y.vec]) ~ ., data = trainset, cost = 100, gamma = 1)
svm.pred <- predict(svm.model, testset[,-y.vec])

table(pred = svm.pred, true = testset[,y.vec])    

} }

Hope this helps! 希望这可以帮助!

myFunc <- function(df, y.vec)
  {
    library(e1071) 

    df[,y.vec] <- as.factor(df[,y.vec])

    set.seed(1)
    index <- 1:nrow(df)
    testindex <- sample(index, trunc(length(index)/3))
    testset <- df[testindex,]
    trainset <- df[-testindex,]

    svm.model <- svm(as.formula(paste(y.vec, "~ .")), data = trainset, cost = 100, gamma = 1)
    svm.pred <- predict(svm.model, testset[,!(names(testset) %in% y.vec)])

    return(table(pred = svm.pred, true = testset[,y.vec]))
  }

myFunc(iris, "Species")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM