blob: 7f6451c59431a45ade8284ee101b3d11d97cb4a7 [file] [log] [blame]
Marc Kupietzc3bf3502021-02-19 17:18:57 +01001library(caret)
2library(tidyverse)
3library(DMwR)
4library(randomForest)
5library(FSelector)
6# library(randomForestExplainer)
7# may need to: options(expressions = 5e5) to avoid stackoverflow for installing package
8
Marc Kupietz358a2962021-02-22 07:55:49 +01009set.seed(42)
10
PeterFankhauserIDSed93d2e2021-02-20 14:51:13 +010011# Test
12
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010013ngramfile<-"gold03_anno_ml_synfeat_nstopw"
14
Marc Kupietzc3bf3502021-02-19 17:18:57 +010015setwd(dirname(rstudioapi::getSourceEditorContext()$path))
16stopwords <- readLines(con = "../data/stopwords.txt",encoding="UTF-8")
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010017oringramme <- read.csv(paste("../data/",ngramfile,".csv",sep=""), header = TRUE, sep = "\t", dec=".", quote="", encoding="UTF-8",stringsAsFactors=FALSE)
Marc Kupietzc3bf3502021-02-19 17:18:57 +010018syfeaturenames <- 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
21deleteStopwords = function(wl, stopwords = NULL) {
22 wl[!(wl %in% stopwords)]
23}
24
Marc Kupietz631800f2021-02-19 17:27:26 +010025oringramme <- oringramme %>%
26 filter(CO_IDIOM < 2) # just two classes: 0 no idiom, 1 idiom
27
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010028# Reduce number of classes, treat null values, add NSTOPW, change names for SY features
29
Marc Kupietzc3bf3502021-02-19 17:18:57 +010030ngramme <- 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 Kupietzaced2702021-02-19 19:09:29 +010036 rename_at(syfeaturenames$innames, ~ syfeaturenames[syfeaturenames$innames==.x,]$synames ) %>%
Marc Kupietzc3bf3502021-02-19 17:18:57 +010037 mutate(across(everything(), ~ replace_na(.x, 0))) %>%
Marc Kupietz201e6f32021-02-22 12:34:13 +010038 mutate(CO_IDIOM = as.factor(if_else(CO_IDIOM == 1, "idiom", "no_idiom"))) # just two classes: 0 no idiom, 1 idiom
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010039
40# Optional
41write.table(ngramme,file=paste("../data/",ngramfile,"_cosy.csv",sep=""), sep = "\t", quote=F)
42
43# featuresets
Marc Kupietzc3bf3502021-02-19 17:18:57 +010044
45covars <- 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")
46syvars <- c(syfeaturenames$synames,"NSTOPW")
47vars <- c(covars,syvars)
48
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010049# formulae for training and testing rf
50
Marc Kupietzc3bf3502021-02-19 17:18:57 +010051fmla <- as.formula(paste("CO_IDIOM ~ ", paste(vars, collapse= "+")))
52fmlaco <- as.formula(paste("CO_IDIOM ~ ", paste(covars, collapse= "+")))
53fmlasy <- as.formula(paste("CO_IDIOM ~ ", paste(syvars, collapse= "+")))
54
55# Simple train/test split
56
57trainRows <- sample(nrow(ngramme), nrow(ngramme)*0.8, replace = FALSE)
58train <- ngramme[trainRows,]
59test <- ngramme[setdiff(1:nrow(ngramme),trainRows),]
60
Marc Kupietz355d5482021-02-22 17:13:56 +010061cat("Random Forest\n")
Marc Kupietz65733b22021-02-22 08:09:08 +010062
Marc Kupietz13f67ed2021-02-22 07:55:03 +010063rf_classifier = randomForest(fmla, train, importance=TRUE)
Marc Kupietzc3bf3502021-02-19 17:18:57 +010064
65# only SY features
66# rf_classifier = randomForest(fmlasy, train, ntree=100, mtry=10, importance=TRUE)
67
68prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM))
69
Marc Kupietz201e6f32021-02-22 12:34:13 +010070res <- confusionMatrix(prediction_for_table, test$CO_IDIOM, positive= "idiom")
Marc Kupietz13f67ed2021-02-22 07:55:03 +010071print(res)
Marc Kupietz355d5482021-02-22 17:13:56 +010072collected_results <- bind_cols("rf" = res$byClass)
PeterFankhauserIDSc2622782021-02-21 18:10:01 +010073
74# Sensitivity is recall of class 1
75# Pos Pred Value is precision
Marc Kupietzc3bf3502021-02-19 17:18:57 +010076varImpPlot(rf_classifier)
77
Marc Kupietz355d5482021-02-22 17:13:56 +010078cat("Random Forest with cutoff\n")
79prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM), cutoff = c(0.2, 0.8))
80res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "idiom")
81collected_results <- bind_cols(collected_results, "rf with cutoff" = res$byClass)
82print(res)
Marc Kupietzc3bf3502021-02-19 17:18:57 +010083
Marc Kupietz355d5482021-02-22 17:13:56 +010084cat("With SMOTE resampled training data\n")
Marc Kupietzc3bf3502021-02-19 17:18:57 +010085smoted.data <- SMOTE(fmla, subset(train, select = c("CO_IDIOM", vars)), perc.over = 1200, perc.under = 100)
Marc Kupietz13f67ed2021-02-22 07:55:03 +010086rf_classifier = randomForest(fmla, smoted.data, importance=TRUE)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010087prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM))
Marc Kupietz201e6f32021-02-22 12:34:13 +010088res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "idiom")
Marc Kupietz355d5482021-02-22 17:13:56 +010089collected_results <- bind_cols(collected_results, "rf with SMOTE" = res$byClass)
Marc Kupietz13f67ed2021-02-22 07:55:03 +010090print(res)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010091
Marc Kupietz355d5482021-02-22 17:13:56 +010092cat("With SMOTE and cutoff\n")
Marc Kupietz201e6f32021-02-22 12:34:13 +010093prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM), cutoff = c(0.2, 0.8))
94res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "idiom")
Marc Kupietz355d5482021-02-22 17:13:56 +010095collected_results <- bind_cols(collected_results, "rf with SMOTE and cutoff" = res$byClass)
Marc Kupietz1be40eb2021-02-22 08:10:29 +010096print(res)
97
Marc Kupietz355d5482021-02-22 17:13:56 +010098collected_results <- collected_results %>%
99 round(3) %>%
100 add_column(measure = names(res$byClass)) %>%
101 column_to_rownames("measure")
102
103View(collected_results)
Marc Kupietz1be40eb2021-02-22 08:10:29 +0100104
PeterFankhauserIDS03d4ece2021-02-22 20:58:28 +0100105# Analysing tradeoff between Fscore, Recall, Precision for various cutoffs
PeterFankhauserIDSd2c893a2021-02-22 21:16:06 +0100106# full range from precision almost 100% to recall almost 100%
PeterFankhauserIDS03d4ece2021-02-22 20:58:28 +0100107rf_classifier = randomForest(fmla, train, importance=TRUE)
Marc Kupietzb1b03362021-02-23 09:32:16 +0100108cvalues<-tibble()
Marc Kupietz347a0392021-02-23 09:56:05 +0100109for (c in c(seq(from=0.4,to=0.99,by=0.025),0.999)) {
110 prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM), cutoff = c(1-c, c))
PeterFankhauserIDS03d4ece2021-02-22 20:58:28 +0100111 conf<-confusionMatrix(prediction_for_table, test$CO_IDIOM, positive = "idiom")
Marc Kupietzb1b03362021-02-23 09:32:16 +0100112 cvalues <-bind_rows(cvalues, c(cutoff=c, conf$byClass))
PeterFankhauserIDS03d4ece2021-02-22 20:58:28 +0100113}
Marc Kupietzb1b03362021-02-23 09:32:16 +0100114cvalues %>%
115 select(c("cutoff", "Recall", "Precision", "F1", "Specificity", "Balanced Accuracy")) %>%
116 pivot_longer(!cutoff, names_to=c("measure")) %>%
117 ggplot(aes(cutoff, value, colour=measure)) + geom_line()
PeterFankhauserIDS03d4ece2021-02-22 20:58:28 +0100118
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100119# Using estimates by random forest on entire dataset
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100120
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100121library(randomForest)
Marc Kupietz13f67ed2021-02-22 07:55:03 +0100122rf_classifier_full = randomForest(fmla, data=ngramme, importance=TRUE)
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100123rf_classifier_full
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100124# class.error is 1 - recall
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100125varImpPlot(rf_classifier_full)
126
127# Feature ranking
128
129# rf features as table
130
131# correlated features seem to split their rankings
132
133rfranks<-importance(rf_classifier_full)[,3:4]
134
135# ttest
136
Marc Kupietz201e6f32021-02-22 12:34:13 +0100137idioms<-ngramme %>% filter(CO_IDIOM == "idiom")
138nonidioms<-ngramme %>% filter(CO_IDIOM != "idiom")
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100139
140ttestPvalues<-sapply(vars,
141 function(sel) t.test(idioms[sel],nonidioms[sel])$p.value)
142
143# information gain
144# multiply by 1000 to avoid undersized bins
145# features are ranked individually not matter their correlation
146igain<-information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2")
147
148featureRanks<-cbind(rfranks,igain,ttestPvalues)
149
150#randomForestExplainer::explain_forest(rf_classifier )
151
152# averate estimates and feature ranks over 10 runs
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100153
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100154errrate<-0
155conf<-matrix(0,2,3)
156featureRanks<-matrix(0,4,length(vars))
157for (i in 1:10) {
Marc Kupietz13f67ed2021-02-22 07:55:03 +0100158 rfc =randomForest(fmla, data=ngramme, importance=TRUE)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100159 #rfc =randomForest(fmla, data=ngramme, ntree=100, importance=TRUE, cutoff=c(0.8,0.2))
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100160 errrate<-errrate+rfc$err.rate[100,1]
161 conf<-conf+rfc$confusion
162 featureRanks<-featureRanks+
163 cbind(importance(rfc)[,3:4],
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100164 information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2"),
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100165 sapply(vars,
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100166 function(sel) t.test(idioms[sel],nonidioms[sel])$p.value))
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100167 print(errrate/i)
168 conf1<-round(
169 rbind(
170 cbind(conf[,1:2]/i,(1-conf[,3]/i)*100),
171 c(100*diag(conf[,1:2])/colSums(conf[,1:2]),NA),
172 c(rowSums(conf[,1:2]/i),NA)),digits=2)
Marc Kupietz201e6f32021-02-22 12:34:13 +0100173 colnames(conf1)<-c("1","0","rec")
174 rownames(conf1)<-c("1","0","prec","sum")
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100175 print(conf1)
176}
177featureRanks<-featureRanks/10
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100178colnames(featureRanks)<-c("MeanDecreaseAccuracy","MeanDecreaseGini","InformationGain","Ttest")
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100179
180
181
182