I am computing a random weighted classifier based on the rates at which 3 labels appear in a "train" set. I want to use this RWC as a baseline for other classifiers. I'm doing this over 1000 iterations and then computing the mean of F1, Precision and Recall of each class besides the overall kappa.
Can this code run faster/look nicer? Minimum example here:
library(caret)
random_weighted_classifier <- function(weightA, weightB, weightC){
random_number = sample(1:100,1) / 100
if(random_number <= weightA){
return("better")
}else if (random_number > weightA && random_number <= (weightA + weightB)){
return("worse")
}else if(random_number > (weightA + weightB) && random_number <= (weightA + weightB + weightC)){
return("no change")
}
}
test <- function(){
betters = rep(x = "better", 100)
worses = rep(x = "worse", 50)
no_changes = rep(x = "no_change", 10)
reference = sample(c(betters, worses, no_changes))
better = sum(reference == "better")
worse = sum(reference == "worse")
no_change = sum(reference == "no_change")
total = length(reference)
# rwc = random weighted classifer
prediction_rwc = vector("character", total)
iterations = 1000
f1_rwc = matrix(0., iterations, 3)
pres_rwc = matrix(0.,iterations, 3)
rec_rwc = matrix(0., iterations, 3)
kappa_rwc = vector("double", iterations)
for(i in seq(1:iterations)){
for(j in seq(1:total)){
prediction_rwc[[j]] = random_weighted_classifier(better/total, worse/total, no_change/total)
}
cm = (confusionMatrix(data = factor(prediction_rwc, levels = c("better","worse", "no_change")),
reference = factor(reference, levels = c("better","worse", "no_change")),
positive = c("better", "worse"),
mode = "everything"))
f1_rwc[i,1:3] <- cm$byClass[,"F1"]
pres_rwc[i,1:3] = cm$byClass[,"Precision"]
rec_rwc[i,1:3] = cm$byClass[,"Recall"]
kappa_rwc[[i]] = round(cm$overall["Kappa"],2)
}
print(list("f1" = c(mean(f1_rwc[,1], na.rm = T),mean(f1_rwc[,2], na.rm = T),mean(f1_rwc[,3], na.rm = T)),
"precision" = c(mean(pres_rwc[,1], na.rm = T),mean(pres_rwc[,2], na.rm = T),mean(pres_rwc[,3], na.rm = T)),
"recall" = c(mean(rec_rwc[,1], na.rm = T),mean(rec_rwc[,2], na.rm = T),mean(rec_rwc[,3], na.rm = T)),
"kappa" = mean(kappa_rwc, na.rm = T)))
}
test()