我有一个数据集,看起来像这样
ID 885038 885039 885040 885041 885042 885043 885044 Class
1267359 2 0 0 0 0 1 0 0
1295720 0 0 0 0 0 1 0 0
1295721 0 0 0 0 0 1 0 0
1295723 0 0 0 0 0 1 0 0
1295724 0 0 0 1 0 1 0 0
1295725 0 0 0 1 0 1 0 0
1295726 2 0 0 0 0 1 0 1
1295727 2 0 0 0 0 1 0 1
1295740 0 0 0 0 0 1 0 1
1295742 0 0 0 0 0 1 0 1
1295744 0 0 0 0 0 1 0 1
1295745 0 0 0 0 0 1 0 1
1295746 0 0 0 0 0 1 0 1
为了进行递归特征消除,我按照以下步骤进行:
- 训练SVM分类器
- 计算所有特征的排名标准
- 删除排名值最小的特征
- 回到第1步
以下是我编写的R代码,用于执行上述操作,但它没有显示任何错误并且循环持续着训练集���长度。
data <- read.csv("dummy - Copy.csv", header = TRUE)
rownames(data) <- data[,1]
data<-data[,-1]
for (k in 1:length(data)){
inTraining <- createDataPartition(data$Class, p = .70, list = FALSE)
training <- data[ inTraining,]
testing <- data[-inTraining,]
## Building the model ####
svm.model <- svm(Class ~ ., data = training, cross=10,metric="ROC",type="eps-regression",kernel="linear",na.action=na.omit,probability = TRUE)
###### auc measure #######
#prediction and ROC
svm.model$index
svm.pred <- predict(svm.model, testing, probability = TRUE)
#calculating auc
c <- as.numeric(svm.pred)
c = c - 1
pred <- prediction(c, testing$Class)
perf <- performance(pred,"tpr","fpr")
plot(perf,fpr.stop=0.1)
auc <- performance(pred, measure = "auc")
auc <- auc@y.values[[1]]
#compute the weight vector
w = t(svm.model$coefs)%*%svm.model$SV
#compute ranking criteria
weight_matrix = w * w
#rank the features
w_transpose <- t(weight_matrix)
w2 <- as.matrix(w_transpose[order(w_transpose[,1], decreasing = FALSE),])
a <- as.matrix(w2[which(w2 == min(w2)),]) #to get the rows with minimum values
row.names(a) -> remove
data<- data[,setdiff(colnames(data),remove)]
print(length(data))
length <- (length(data))
cols_names <- colnames(data)
print(auc)
output <- paste(length,auc,sep=";")
write(output, file = "output.txt",append = TRUE)
write(cols_names, file = paste(length,"cols_selected", ".txt", sep=""))
}
打印输出的结果如下:
[1] 3
[1] 0.5
[1] 2
[1] 0.5
[1] 2
[1] 0.5
[1] 2
[1] 0.75
[1] 2
[1] 1
[1] 2
[1] 0.75
[1] 2
[1] 0.5
[1] 2
[1] 0.75
但是当我选择任何一个特征子集,例如特征3,并使用上述代码(不使用循环)构建SVM模型时,我得到的AUC值并不是0.75。
data <- read.csv("3.csv", header = TRUE)
rownames(data) <- data[,1]
data<-data[,-1]
inTraining <- createDataPartition(data$Class, p = .70, list = FALSE)
training <- data[ inTraining,]
testing <- data[-inTraining,]
## Building the model ####
svm.model <- svm(Class ~ ., data = training, cross=10,metric="ROC",type="eps-regression",kernel="linear",na.action=na.omit,probability = TRUE)
###### auc measure #######
#prediction and ROC
svm.model$index
svm.pred <- predict(svm.model, testing, probability = TRUE)
#calculating auc
c <- as.numeric(svm.pred)
c = c - 1
pred <- prediction(c, testing$Class)
perf <- performance(pred,"tpr","fpr")
plot(perf,fpr.stop=0.1)
auc <- performance(pred, measure = "auc")
auc <- auc@y.values[[1]]
print(auc)
prints output
[1] 3
[1] 0.75 (instead of 0.5)
这两个代码都是一样的(一个带有递归循环,另一个没有任何递归循环),但对于相同的特征子集,AUC值却不同。
这两个代码所使用的三个特征(885041
,885043
和Class
)是一样的,但它们给出了不同的AUC值。