```{r setup,include=F}
library(tidyverse)
library(quanteda)
library(quanteda.textmodels)
```

*File to follow along in class*

## Movie reviews corpus

```{r}
reviews_corp <- data_corpus_moviereviews
reviews_dfm <- dfm(reviews_corp,remove_punct=T)
```


## Sampling

```{r}
reviews_train <- dfm_sample(reviews_dfm,0.8*ndoc(reviews_corp))
reviews_test <- dfm_subset(reviews_dfm,
  !(docnames(reviews_dfm) %in% docnames(reviews_train)))


head(reviews_train,3)
head(reviews_test,3)
```

## Adjusting Feature Set

```{r,echo=T}
reviews_train <- reviews_train %>% dfm_trim(1)
reviews_test <- dfm_match(reviews_test, featnames(reviews_train))

head(reviews_test,3)
```

## Training the model

```{r}
start <- Sys.time()

# Model
nb_model<-textmodel_nb(reviews_train,docvars(reviews_train,
  "sentiment"))
nb_model

end <- Sys.time()
end-start
```

## Predicting test data


```{r}
test_predictions<-predict(nb_model,
  newdata=reviews_test)



head(test_predictions,5)
table(docvars(reviews_test,"sentiment"),test_predictions)
```

## Exercise: SVM

Try using the Support Vector Machine Classifier instead. For this, you will need to change the classification command to `textmodel_svm()`.
Measure time to assess if the classifier is faster than Naive Bayes.

```{r}
start <- Sys.time()

# Model
svm_model<-textmodel_svm(reviews_train,docvars(reviews_train,
  "sentiment"))
svm_model

end <- Sys.time()
end-start
```


Predict the test data and look at the cross-tabulation to see how well the model compares, compared to the Naive Bayes Classifier.
If you have still stored the results from your Naive Bayes Model, create a confusion Matrix for both.


```{r}
predictions_svm <- predict(svm_model,
  newdata=reviews_test)

head(predictions_svm,5)
table(docvars(reviews_test,"sentiment"),predictions_svm)
```


```{r}
caret::confusionMatrix(docvars(reviews_test,"sentiment"),test_predictions)
caret::confusionMatrix(docvars(reviews_test,"sentiment"),predictions_svm)
```

