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