How to save trained model in R

In [1]:
# Snippet_249
# --------------------------------------
# How to save trained model in R 
# --------------------------------------
# load libraries
library(caret)
library(mlbench)
library(randomForest)

# load dataset
data(Sonar)

# create 80%/20% for training and validation datasets
validation_index <- createDataPartition(Sonar$Class, p=0.67, list=FALSE)
validation <- Sonar[-validation_index,]
training <- Sonar[validation_index,]

# create final standalone model using all training data
final_model <- randomForest(Class~., training, mtry=2, ntree=2000)

# save the model to disk
getwd()
saveRDS(final_model, "./final_model.rds")

# later ... ... ... ... ...

# load the model
getwd()
saved_model <- readRDS("./final_model.rds")
print(saved_model)
plot(saved_model)

# make a predictions on "new data" using the final model
final_predictions <- predict(saved_model, validation[,1:60])
confusionMatrix(final_predictions, validation$Class)
Loading required package: lattice
Loading required package: ggplot2
randomForest 4.6-14
Type rfNews() to see new features/changes/bug fixes.

Attaching package: ‘randomForest’

The following object is masked from ‘package:ggplot2’:

    margin

'/Users/nilimesh/Desktop/Data Science Recipes/Kickstarter-Examples-1000/KE-249'
'/Users/nilimesh/Desktop/Data Science Recipes/Kickstarter-Examples-1000/KE-249'
Call:
 randomForest(formula = Class ~ ., data = training, mtry = 2,      ntree = 2000) 
               Type of random forest: classification
                     Number of trees: 2000
No. of variables tried at each split: 2

        OOB estimate of  error rate: 18.57%
Confusion matrix:
   M  R class.error
M 68  7  0.09333333
R 19 46  0.29230769
Confusion Matrix and Statistics

          Reference
Prediction  M  R
         M 33 12
         R  3 20
                                         
               Accuracy : 0.7794         
                 95% CI : (0.6624, 0.871)
    No Information Rate : 0.5294         
    P-Value [Acc > NIR] : 1.794e-05      
                                         
                  Kappa : 0.5503         
                                         
 Mcnemar's Test P-Value : 0.03887        
                                         
            Sensitivity : 0.9167         
            Specificity : 0.6250         
         Pos Pred Value : 0.7333         
         Neg Pred Value : 0.8696         
             Prevalence : 0.5294         
         Detection Rate : 0.4853         
   Detection Prevalence : 0.6618         
      Balanced Accuracy : 0.7708         
                                         
       'Positive' Class : M