rm(list=ls(all=TRUE)) setwd("C:/Users/luigi/Dropbox/TOPIC MODEL") getwd() library(quanteda) library(readtext) library(caTools) library(e1071) library(randomForest) library(caret) library(naivebayes) library(car) library(cvTools) library(reshape2) library(dplyr) ##################################################### # let's prepare the training-set with 3 categories (this script works fine for any number of categories>2) ##################################################### uk_train <- read.csv("uk_train.csv") str(uk_train) myCorpusTwitterTrain <- corpus(uk_train) tok2 <- tokens(myCorpusTwitterTrain, remove_punct = TRUE, remove_numbers=TRUE, remove_symbols = TRUE, split_hyphens = TRUE, remove_separators = TRUE) tok2 <- tokens_remove(tok2, stopwords("en")) tok2 <- tokens_wordstem (tok2) Dfm_train <- dfm(tok2) # Let's trim the dfm in order to keep only tokens that appear in 2 or more tweets (tweets are very short texts...) Dfm_train <- dfm_trim(Dfm_train , min_docfreq = 2, verbose=TRUE) topfeatures(Dfm_train , 20) # 20 top words train <- as.matrix(Dfm_train) # our classes table(Dfm_train@docvars$Sentiment) # our benchmark: accuracy .53 prop.table(table(Dfm_train@docvars$Sentiment)) ###################################################### ###################################################### # which main changes? Compared to the script "Lab 8 part 2" # consider the case of a SVM - but that applies to all the other scripts ###################################################### ###################################################### # STEP 1: create the 2 folds. Why only 2? Cause you have very few positive tweets in the training-set, # and if you increase the number of folds, you risk to have some folds without any observations for the positive class ttrain <- train set.seed(1234) # set the see for replicability k <- 2 folds <- cvFolds(NROW(ttrain ), K=k) str(folds) # STEP 2: the LOOP system.time(for(i in 1:k){ train <- ttrain [folds$subsets[folds$which != i], ] # Set the training set validation <- ttrain [folds$subsets[folds$which == i], ] # Set the validation set newrf <- svm(y= as.factor(Dfm_train[folds$subsets[folds$which != i], ]@docvars$Sentiment) ,x=train, kernel='linear', cost = 1) # Get your new model # (just fit on the train data) and ADD the name of the output (in this case "Sentiment") newpred <- predict(newrf,newdata=validation) # Get the predicitons for the validation set (from the model just fit on the train data) class_table <- table("Predictions"= newpred, "Actual"=Dfm_train[folds$subsets[folds$which == i], ]@docvars$Sentiment) print(class_table) df<-confusionMatrix( class_table, mode = "everything") df.name<-paste0("conf.mat.sv",i) # create the name for the object that will save the confusion matrix for each loop (=5) assign(df.name,df) }) # STEP 3: the metrics SVMPredict <- data.frame(col1=vector(), col2=vector(), col3=vector(), col4=vector()) ##### FIRST CHANGE # Why 4 columns NOW? 1 for accuracy; and 3 for the K1 value of the classes in the Sentiment: negative, neutral, positive. # According to the number of classes in your output variable, changes the number of columns to fill!!! for(i in mget(ls(pattern = "conf.mat.sv")) ) { Accuracy <-(i)$overall[1] # save in the matrix the accuracy value ##### SECOND CHANGE: the following 4 lines: p <- as.data.frame((i)$byClass) F1_negative <- p$F1[1] # save in the matrix the F1 value for negative F1_neutral <- p$F1[2] # save in the matrix the F1 value for neutral F1_positive <- p$F1[3] # save in the matrix the F1 value for positive SVMPredict <- rbind(SVMPredict , cbind(Accuracy , F1_negative , F1_neutral, F1_positive )) } str(SVMPredict ) # you see that we are not doing that well with the class "negative" # Let's compare the average value for accuracy and f1 acc_sv_avg <- mean(SVMPredict[, 1] ) f1_sv_avg <- mean(colMeans(SVMPredict[-1] )) acc_sv_avg f1_sv_avg # you see here that we do not improve that much compared to our benchmark model. # Moreover there is a wide gap between accuracy and the avg. value of F1: why? cause we are doing good with some class (neutral) # and bad with the others. Why? The presence of an imbalanced dataset could be a reason for that. So here it does not matter # the type of fancy ML algorithm (and connceted hyper-parameters mix) you are employing. # The only way for you to improve the performance of a ML algorithm in the CV stage (before predicting the test-set) is going back # to the training-set and improving it (for example by adding more texts displaying the classes in which you are doing bad). # Any ML algorithm on a poorly built training-set, is going always to be a bad ML algorithm in terms of performance