blob: 4880c9f78fb66e585efaddf17c97328a97a90bad [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
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +01009ngramfile<-"gold03_anno_ml_synfeat_nstopw"
10
Marc Kupietzc3bf3502021-02-19 17:18:57 +010011setwd(dirname(rstudioapi::getSourceEditorContext()$path))
12stopwords <- readLines(con = "../data/stopwords.txt",encoding="UTF-8")
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010013oringramme <- 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 +010014syfeaturenames <- read.csv("../data/syfeatures.tsv", header = TRUE, sep = "\t", dec=".", quote="", encoding="UTF-8",stringsAsFactors=FALSE)
15# syfeaturenames$navalue<-sapply(syfeaturenames$navalue,as.numeric)
16
17deleteStopwords = function(wl, stopwords = NULL) {
18 wl[!(wl %in% stopwords)]
19}
20
Marc Kupietz631800f2021-02-19 17:27:26 +010021oringramme <- oringramme %>%
22 filter(CO_IDIOM < 2) # just two classes: 0 no idiom, 1 idiom
23
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010024# Reduce number of classes, treat null values, add NSTOPW, change names for SY features
25
Marc Kupietzc3bf3502021-02-19 17:18:57 +010026ngramme <- oringramme %>%
27 add_column(NSTOPW = sapply(oringramme$tokens,function(x) length(deleteStopwords(tolower(unlist(strsplit(x," "))),stopwords)))) %>%
28 # select(-matches("CO_TOKEN.*"), -tokens) %>%
29 select(-matches("CO_TOKEN.*")) %>% # keep tokens for interpretability
30 mutate(across(matches(".rank.*"), ~ replace_na(.x, 1000))) %>%
31 mutate(across(c("dice", "lfmd", "llr", "ld", "pmi"), ~ replace_na(.x, min(.x) - 1))) %>%
Marc Kupietzaced2702021-02-19 19:09:29 +010032 rename_at(syfeaturenames$innames, ~ syfeaturenames[syfeaturenames$innames==.x,]$synames ) %>%
Marc Kupietzc3bf3502021-02-19 17:18:57 +010033 mutate(across(everything(), ~ replace_na(.x, 0))) %>%
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010034 mutate(CO_IDIOM = as.factor(if_else(CO_IDIOM !=1, "0", "1"))) # just two classes: 0 no idiom, 1 idiom
35
36# Optional
37write.table(ngramme,file=paste("../data/",ngramfile,"_cosy.csv",sep=""), sep = "\t", quote=F)
38
39# featuresets
Marc Kupietzc3bf3502021-02-19 17:18:57 +010040
41covars <- 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")
42syvars <- c(syfeaturenames$synames,"NSTOPW")
43vars <- c(covars,syvars)
44
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010045# formulae for training and testing rf
46
Marc Kupietzc3bf3502021-02-19 17:18:57 +010047fmla <- as.formula(paste("CO_IDIOM ~ ", paste(vars, collapse= "+")))
48fmlaco <- as.formula(paste("CO_IDIOM ~ ", paste(covars, collapse= "+")))
49fmlasy <- as.formula(paste("CO_IDIOM ~ ", paste(syvars, collapse= "+")))
50
51# Simple train/test split
52
53trainRows <- sample(nrow(ngramme), nrow(ngramme)*0.8, replace = FALSE)
54train <- ngramme[trainRows,]
55test <- ngramme[setdiff(1:nrow(ngramme),trainRows),]
56
57rf_classifier = randomForest(fmla, train, ntree=100, mtry=10, importance=TRUE)
58
59# only SY features
60# rf_classifier = randomForest(fmlasy, train, ntree=100, mtry=10, importance=TRUE)
61
62prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM))
63
64# different cutoff for prediction
65# prediction_for_table <- predict(rf_classifier, test %>% select(-CO_IDIOM), cutoff = c(0.8, 0.2))
66
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010067confusion <- table(observed=test$CO_IDIOM,predicted=prediction_for_table)
68conf <- confusionMatrix(confusion, positive= "1")
Marc Kupietzc3bf3502021-02-19 17:18:57 +010069print(conf)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010070# Sensitivity is precision of class 1
71# Pos Pred Value is recall
Marc Kupietzc3bf3502021-02-19 17:18:57 +010072varImpPlot(rf_classifier)
73
74# optional resampling with smote
75
76smoted.data <- SMOTE(fmla, subset(train, select = c("CO_IDIOM", vars)), perc.over = 1200, perc.under = 100)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010077rf_classifier = randomForest(fmla, smoted.data, ntree=100, mtry=10, importance=TRUE)
78prediction_for_table <- predict(rf_classifier,test %>% select(-CO_IDIOM))
79confusion <- table(observed=test$CO_IDIOM,predicted=prediction_for_table)
Marc Kupietz0932a782021-02-19 17:39:47 +010080conf <- confusionMatrix(confusion, positive = "1")
81print(conf)
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010082
Marc Kupietzc3bf3502021-02-19 17:18:57 +010083# Using estimates by random forest on entire dataset
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010084
Marc Kupietzc3bf3502021-02-19 17:18:57 +010085library(randomForest)
86rf_classifier_full = randomForest(fmla, data=ngramme, ntree=100, mtry=2, importance=TRUE, cutoff=c(0.8,0.2))
87rf_classifier_full
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +010088# class.error is 1 - recall
Marc Kupietzc3bf3502021-02-19 17:18:57 +010089varImpPlot(rf_classifier_full)
90
91# Feature ranking
92
93# rf features as table
94
95# correlated features seem to split their rankings
96
97rfranks<-importance(rf_classifier_full)[,3:4]
98
99# ttest
100
101idioms<-ngramme %>% filter(CO_IDIOM==1)
102nonidioms<-ngramme %>% filter(CO_IDIOM!=1)
103
104ttestPvalues<-sapply(vars,
105 function(sel) t.test(idioms[sel],nonidioms[sel])$p.value)
106
107# information gain
108# multiply by 1000 to avoid undersized bins
109# features are ranked individually not matter their correlation
110igain<-information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2")
111
112featureRanks<-cbind(rfranks,igain,ttestPvalues)
113
114#randomForestExplainer::explain_forest(rf_classifier )
115
116# averate estimates and feature ranks over 10 runs
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100117
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100118errrate<-0
119conf<-matrix(0,2,3)
120featureRanks<-matrix(0,4,length(vars))
121for (i in 1:10) {
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100122 rfc =randomForest(fmla, data=ngramme, ntree=100, importance=TRUE)
123 #rfc =randomForest(fmla, data=ngramme, ntree=100, importance=TRUE, cutoff=c(0.8,0.2))
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100124 errrate<-errrate+rfc$err.rate[100,1]
125 conf<-conf+rfc$confusion
126 featureRanks<-featureRanks+
127 cbind(importance(rfc)[,3:4],
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100128 information.gain(fmla, data=ngramme%>%mutate_at(vars, ~ . * 1000),unit="log2"),
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100129 sapply(vars,
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100130 function(sel) t.test(idioms[sel],nonidioms[sel])$p.value))
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100131 print(errrate/i)
132 conf1<-round(
133 rbind(
134 cbind(conf[,1:2]/i,(1-conf[,3]/i)*100),
135 c(100*diag(conf[,1:2])/colSums(conf[,1:2]),NA),
136 c(rowSums(conf[,1:2]/i),NA)),digits=2)
137 colnames(conf1)<-c("0","1","rec")
138 rownames(conf1)<-c("0","1","prec","sum")
139 print(conf1)
140}
141featureRanks<-featureRanks/10
PeterFankhauserIDSd1f3df82021-02-20 14:44:01 +0100142colnames(featureRanks)<-c("MeanDecreaseAccuracy","MeanDecreaseGini","InformationGain","Ttest")
Marc Kupietzc3bf3502021-02-19 17:18:57 +0100143
144
145
146