blob: 47d4ef96006394718a87169eae1b1ad5677a132a [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))) %>%
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010038 mutate(CO_IDIOM = as.factor(if_else(CO_IDIOM !=1, "0", "1"))) # just two classes: 0 no idiom, 1 idiom
39
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 Kupietz13f67ed2021-02-22 07:55:03 +010061rf_classifier = randomForest(fmla, train, importance=TRUE)
Marc Kupietzc3bf3502021-02-19 17:18:57 +010062
63# only SY features
64# rf_classifier = randomForest(fmlasy, train, ntree=100, mtry=10, importance=TRUE)
65
66prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM))
67
68# different cutoff for prediction
69# prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM), cutoff = c(0.8, 0.2))
70
Marc Kupietz13f67ed2021-02-22 07:55:03 +010071res <- confusionMatrix(prediction_for_table, test$CO_IDIOM,positive= "1")
72cat("Without SMOTE")
73print(res)
PeterFankhauserIDSc2622782021-02-21 18:10:01 +010074
75# Sensitivity is recall of class 1
76# Pos Pred Value is precision
Marc Kupietzc3bf3502021-02-19 17:18:57 +010077varImpPlot(rf_classifier)
78
79# optional resampling with smote
80
81smoted.data <- SMOTE(fmla, subset(train, select = c("CO_IDIOM", vars)), perc.over = 1200, perc.under = 100)
Marc Kupietz13f67ed2021-02-22 07:55:03 +010082rf_classifier = randomForest(fmla, smoted.data, importance=TRUE)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010083prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM))
Marc Kupietz13f67ed2021-02-22 07:55:03 +010084res <- confusionMatrix(prediction_for_table,test$CO_IDIOM, positive = "1")
85cat("With SMOTE")
86print(res)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010087
Marc Kupietzc3bf3502021-02-19 17:18:57 +010088# Using estimates by random forest on entire dataset
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010089
Marc Kupietzc3bf3502021-02-19 17:18:57 +010090library(randomForest)
Marc Kupietz13f67ed2021-02-22 07:55:03 +010091rf_classifier_full = randomForest(fmla, data=ngramme, importance=TRUE)
Marc Kupietzc3bf3502021-02-19 17:18:57 +010092rf_classifier_full
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010093# class.error is 1 - recall
Marc Kupietzc3bf3502021-02-19 17:18:57 +010094varImpPlot(rf_classifier_full)
95
96# Feature ranking
97
98# rf features as table
99
100# correlated features seem to split their rankings
101
102rfranks<-importance(rf_classifier_full)[,3:4]
103
104# ttest
105
106idioms<-ngramme %>% filter(CO_IDIOM==1)
107nonidioms<-ngramme %>% filter(CO_IDIOM!=1)
108
109ttestPvalues<-sapply(vars,
110 function(sel) t.test(idioms[sel],nonidioms[sel])$p.value)
111
112# information gain
113# multiply by 1000 to avoid undersized bins
114# features are ranked individually not matter their correlation
115igain<-information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2")
116
117featureRanks<-cbind(rfranks,igain,ttestPvalues)
118
119#randomForestExplainer::explain_forest(rf_classifier )
120
121# averate estimates and feature ranks over 10 runs
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100122
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100123errrate<-0
124conf<-matrix(0,2,3)
125featureRanks<-matrix(0,4,length(vars))
126for (i in 1:10) {
Marc Kupietz13f67ed2021-02-22 07:55:03 +0100127 rfc =randomForest(fmla, data=ngramme, importance=TRUE)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100128 #rfc =randomForest(fmla, data=ngramme, ntree=100, importance=TRUE, cutoff=c(0.8,0.2))
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100129 errrate<-errrate+rfc$err.rate[100,1]
130 conf<-conf+rfc$confusion
131 featureRanks<-featureRanks+
132 cbind(importance(rfc)[,3:4],
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100133 information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2"),
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100134 sapply(vars,
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100135 function(sel) t.test(idioms[sel],nonidioms[sel])$p.value))
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100136 print(errrate/i)
137 conf1<-round(
138 rbind(
139 cbind(conf[,1:2]/i,(1-conf[,3]/i)*100),
140 c(100*diag(conf[,1:2])/colSums(conf[,1:2]),NA),
141 c(rowSums(conf[,1:2]/i),NA)),digits=2)
142 colnames(conf1)<-c("0","1","rec")
143 rownames(conf1)<-c("0","1","prec","sum")
144 print(conf1)
145}
146featureRanks<-featureRanks/10
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100147colnames(featureRanks)<-c("MeanDecreaseAccuracy","MeanDecreaseGini","InformationGain","Ttest")
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100148
149
150
151