Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 1 | library(caret) |
| 2 | library(tidyverse) |
| 3 | library(DMwR) |
| 4 | library(randomForest) |
| 5 | library(FSelector) |
| 6 | # library(randomForestExplainer) |
| 7 | # may need to: options(expressions = 5e5) to avoid stackoverflow for installing package |
| 8 | |
Marc Kupietz | 358a296 | 2021-02-22 07:55:49 +0100 | [diff] [blame] | 9 | set.seed(42) |
| 10 | |
PeterFankhauserIDS | ed93d2e | 2021-02-20 14:51:13 +0100 | [diff] [blame] | 11 | # Test |
| 12 | |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 13 | ngramfile<-"gold03_anno_ml_synfeat_nstopw" |
| 14 | |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 15 | setwd(dirname(rstudioapi::getSourceEditorContext()$path)) |
| 16 | stopwords <- readLines(con = "../data/stopwords.txt",encoding="UTF-8") |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 17 | oringramme <- read.csv(paste("../data/",ngramfile,".csv",sep=""), header = TRUE, sep = "\t", dec=".", quote="", encoding="UTF-8",stringsAsFactors=FALSE) |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 18 | syfeaturenames <- read.csv("../data/syfeatures.tsv", header = TRUE, sep = "\t", dec=".", quote="", encoding="UTF-8",stringsAsFactors=FALSE) |
| 19 | # syfeaturenames$navalue<-sapply(syfeaturenames$navalue,as.numeric) |
| 20 | |
| 21 | deleteStopwords = function(wl, stopwords = NULL) { |
| 22 | wl[!(wl %in% stopwords)] |
| 23 | } |
| 24 | |
Marc Kupietz | 631800f | 2021-02-19 17:27:26 +0100 | [diff] [blame] | 25 | oringramme <- oringramme %>% |
| 26 | filter(CO_IDIOM < 2) # just two classes: 0 no idiom, 1 idiom |
| 27 | |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 28 | # Reduce number of classes, treat null values, add NSTOPW, change names for SY features |
| 29 | |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 30 | ngramme <- oringramme %>% |
| 31 | add_column(NSTOPW = sapply(oringramme$tokens,function(x) length(deleteStopwords(tolower(unlist(strsplit(x," "))),stopwords)))) %>% |
| 32 | # select(-matches("CO_TOKEN.*"), -tokens) %>% |
| 33 | select(-matches("CO_TOKEN.*")) %>% # keep tokens for interpretability |
| 34 | mutate(across(matches(".rank.*"), ~ replace_na(.x, 1000))) %>% |
| 35 | mutate(across(c("dice", "lfmd", "llr", "ld", "pmi"), ~ replace_na(.x, min(.x) - 1))) %>% |
Marc Kupietz | aced270 | 2021-02-19 19:09:29 +0100 | [diff] [blame] | 36 | rename_at(syfeaturenames$innames, ~ syfeaturenames[syfeaturenames$innames==.x,]$synames ) %>% |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 37 | mutate(across(everything(), ~ replace_na(.x, 0))) %>% |
Marc Kupietz | 201e6f3 | 2021-02-22 12:34:13 +0100 | [diff] [blame] | 38 | mutate(CO_IDIOM = as.factor(if_else(CO_IDIOM == 1, "idiom", "no_idiom"))) # just two classes: 0 no idiom, 1 idiom |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 39 | |
| 40 | # Optional |
| 41 | write.table(ngramme,file=paste("../data/",ngramfile,"_cosy.csv",sep=""), sep = "\t", quote=F) |
| 42 | |
| 43 | # featuresets |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 44 | |
| 45 | covars <- c("CO_LL", "CO_Z", "CO_G", "CO_T", "CO_LOGDICE", "CO_PMI", "CO_MI3", "CO_DEREKO", "CO_SGT", "CO_WIN5_VEC","CO_WIN5_VEC_AUTOSEM") |
| 46 | syvars <- c(syfeaturenames$synames,"NSTOPW") |
| 47 | vars <- c(covars,syvars) |
| 48 | |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 49 | # formulae for training and testing rf |
| 50 | |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 51 | fmla <- as.formula(paste("CO_IDIOM ~ ", paste(vars, collapse= "+"))) |
| 52 | fmlaco <- as.formula(paste("CO_IDIOM ~ ", paste(covars, collapse= "+"))) |
| 53 | fmlasy <- as.formula(paste("CO_IDIOM ~ ", paste(syvars, collapse= "+"))) |
| 54 | |
| 55 | # Simple train/test split |
| 56 | |
| 57 | trainRows <- sample(nrow(ngramme), nrow(ngramme)*0.8, replace = FALSE) |
| 58 | train <- ngramme[trainRows,] |
| 59 | test <- ngramme[setdiff(1:nrow(ngramme),trainRows),] |
| 60 | |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 61 | cat("Random Forest\n") |
Marc Kupietz | 65733b2 | 2021-02-22 08:09:08 +0100 | [diff] [blame] | 62 | |
Marc Kupietz | 13f67ed | 2021-02-22 07:55:03 +0100 | [diff] [blame] | 63 | rf_classifier = randomForest(fmla, train, importance=TRUE) |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 64 | |
| 65 | # only SY features |
| 66 | # rf_classifier = randomForest(fmlasy, train, ntree=100, mtry=10, importance=TRUE) |
| 67 | |
| 68 | prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM)) |
| 69 | |
Marc Kupietz | 201e6f3 | 2021-02-22 12:34:13 +0100 | [diff] [blame] | 70 | res <- confusionMatrix(prediction_for_table, test$CO_IDIOM, positive= "idiom") |
Marc Kupietz | 13f67ed | 2021-02-22 07:55:03 +0100 | [diff] [blame] | 71 | print(res) |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 72 | collected_results <- bind_cols("rf" = res$byClass) |
PeterFankhauserIDS | c262278 | 2021-02-21 18:10:01 +0100 | [diff] [blame] | 73 | |
| 74 | # Sensitivity is recall of class 1 |
| 75 | # Pos Pred Value is precision |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 76 | varImpPlot(rf_classifier) |
| 77 | |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 78 | cat("Random Forest with cutoff\n") |
| 79 | prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM), cutoff = c(0.2, 0.8)) |
| 80 | res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "idiom") |
| 81 | collected_results <- bind_cols(collected_results, "rf with cutoff" = res$byClass) |
| 82 | print(res) |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 83 | |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 84 | cat("With SMOTE resampled training data\n") |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 85 | smoted.data <- SMOTE(fmla, subset(train, select = c("CO_IDIOM", vars)), perc.over = 1200, perc.under = 100) |
Marc Kupietz | 13f67ed | 2021-02-22 07:55:03 +0100 | [diff] [blame] | 86 | rf_classifier = randomForest(fmla, smoted.data, importance=TRUE) |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 87 | prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM)) |
Marc Kupietz | 201e6f3 | 2021-02-22 12:34:13 +0100 | [diff] [blame] | 88 | res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "idiom") |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 89 | collected_results <- bind_cols(collected_results, "rf with SMOTE" = res$byClass) |
Marc Kupietz | 13f67ed | 2021-02-22 07:55:03 +0100 | [diff] [blame] | 90 | print(res) |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 91 | |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 92 | cat("With SMOTE and cutoff\n") |
Marc Kupietz | 201e6f3 | 2021-02-22 12:34:13 +0100 | [diff] [blame] | 93 | prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM), cutoff = c(0.2, 0.8)) |
| 94 | res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "idiom") |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 95 | collected_results <- bind_cols(collected_results, "rf with SMOTE and cutoff" = res$byClass) |
Marc Kupietz | 1be40eb | 2021-02-22 08:10:29 +0100 | [diff] [blame] | 96 | print(res) |
| 97 | |
Marc Kupietz | 355d548 | 2021-02-22 17:13:56 +0100 | [diff] [blame] | 98 | collected_results <- collected_results %>% |
| 99 | round(3) %>% |
| 100 | add_column(measure = names(res$byClass)) %>% |
| 101 | column_to_rownames("measure") |
| 102 | |
| 103 | View(collected_results) |
Marc Kupietz | 1be40eb | 2021-02-22 08:10:29 +0100 | [diff] [blame] | 104 | |
PeterFankhauserIDS | 03d4ece | 2021-02-22 20:58:28 +0100 | [diff] [blame^] | 105 | # Analysing tradeoff between Fscore, Recall, Precision for various cutoffs |
| 106 | rf_classifier = randomForest(fmla, train, importance=TRUE) |
| 107 | cvalues<-c() |
| 108 | for (c in seq(from=0.05, to=0.5, by=0.025)) { |
| 109 | prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM), cutoff = c(c, 1-c)) |
| 110 | conf<-confusionMatrix(prediction_for_table, test$CO_IDIOM, positive = "idiom") |
| 111 | cvalues<-rbind(cvalues,c(c,conf$byClass)) |
| 112 | } |
| 113 | |
| 114 | plot(cvalues[,1],cvalues[,"F1"],type = "o",col = "green", xlab = "Cutoff", ylab = "F1",ylim=c(0,1), |
| 115 | main = "FScore, Recall, Precision") |
| 116 | lines(cvalues[,1],cvalues[,"Recall"], type = "o", col = "blue") |
| 117 | lines(cvalues[,1],cvalues[,"Precision"],type="o", col="red") |
| 118 | legend("bottomleft",legend=c("FScore","Recall","Precision"),col=c("green","blue","red"),pch=c(1,1,1),lty=c(1,1,1)) |
| 119 | |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 120 | # Using estimates by random forest on entire dataset |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 121 | |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 122 | library(randomForest) |
Marc Kupietz | 13f67ed | 2021-02-22 07:55:03 +0100 | [diff] [blame] | 123 | rf_classifier_full = randomForest(fmla, data=ngramme, importance=TRUE) |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 124 | rf_classifier_full |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 125 | # class.error is 1 - recall |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 126 | varImpPlot(rf_classifier_full) |
| 127 | |
| 128 | # Feature ranking |
| 129 | |
| 130 | # rf features as table |
| 131 | |
| 132 | # correlated features seem to split their rankings |
| 133 | |
| 134 | rfranks<-importance(rf_classifier_full)[,3:4] |
| 135 | |
| 136 | # ttest |
| 137 | |
Marc Kupietz | 201e6f3 | 2021-02-22 12:34:13 +0100 | [diff] [blame] | 138 | idioms<-ngramme %>% filter(CO_IDIOM == "idiom") |
| 139 | nonidioms<-ngramme %>% filter(CO_IDIOM != "idiom") |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 140 | |
| 141 | ttestPvalues<-sapply(vars, |
| 142 | function(sel) t.test(idioms[sel],nonidioms[sel])$p.value) |
| 143 | |
| 144 | # information gain |
| 145 | # multiply by 1000 to avoid undersized bins |
| 146 | # features are ranked individually not matter their correlation |
| 147 | igain<-information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2") |
| 148 | |
| 149 | featureRanks<-cbind(rfranks,igain,ttestPvalues) |
| 150 | |
| 151 | #randomForestExplainer::explain_forest(rf_classifier ) |
| 152 | |
| 153 | # averate estimates and feature ranks over 10 runs |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 154 | |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 155 | errrate<-0 |
| 156 | conf<-matrix(0,2,3) |
| 157 | featureRanks<-matrix(0,4,length(vars)) |
| 158 | for (i in 1:10) { |
Marc Kupietz | 13f67ed | 2021-02-22 07:55:03 +0100 | [diff] [blame] | 159 | rfc =randomForest(fmla, data=ngramme, importance=TRUE) |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 160 | #rfc =randomForest(fmla, data=ngramme, ntree=100, importance=TRUE, cutoff=c(0.8,0.2)) |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 161 | errrate<-errrate+rfc$err.rate[100,1] |
| 162 | conf<-conf+rfc$confusion |
| 163 | featureRanks<-featureRanks+ |
| 164 | cbind(importance(rfc)[,3:4], |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 165 | information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2"), |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 166 | sapply(vars, |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 167 | function(sel) t.test(idioms[sel],nonidioms[sel])$p.value)) |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 168 | print(errrate/i) |
| 169 | conf1<-round( |
| 170 | rbind( |
| 171 | cbind(conf[,1:2]/i,(1-conf[,3]/i)*100), |
| 172 | c(100*diag(conf[,1:2])/colSums(conf[,1:2]),NA), |
| 173 | c(rowSums(conf[,1:2]/i),NA)),digits=2) |
Marc Kupietz | 201e6f3 | 2021-02-22 12:34:13 +0100 | [diff] [blame] | 174 | colnames(conf1)<-c("1","0","rec") |
| 175 | rownames(conf1)<-c("1","0","prec","sum") |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 176 | print(conf1) |
| 177 | } |
| 178 | featureRanks<-featureRanks/10 |
PeterFankhauserIDS | d1f3df8 | 2021-02-20 14:44:01 +0100 | [diff] [blame] | 179 | colnames(featureRanks)<-c("MeanDecreaseAccuracy","MeanDecreaseGini","InformationGain","Ttest") |
Marc Kupietz | c3bf350 | 2021-02-19 17:18:57 +0100 | [diff] [blame] | 180 | |
| 181 | |
| 182 | |
| 183 | |