Predicting and Evaluating Models

Welcome back! In the previous lesson, we learned how to train a simple machine learning model using the Linear SVM method with the caret package in R. Now that you have a trained model, it's time to make predictions and evaluate how well your model performs.

What You'll Learn

In this lesson, you will learn how to:

  • Make predictions using your trained model.
  • Evaluate the performance of your model using a confusion matrix.

Making predictions and evaluating your model are crucial steps in the machine learning workflow. They help you assess whether your model performs well on unseen data and identify areas for improvement.

Data Splitting and Model Training

In this lesson, we continue from where we left off in the last lesson. Before making predictions, remember that the initial steps include loading the dataset, splitting the data into training and testing sets, and training your model. Here’s a brief reminder of those steps:

# Load iris dataset
data(iris)

# For reproducibility
set.seed(123)

# Splitting data into train and test sets
trainIndex <- createDataPartition(iris$Species, p = 0.7, list = FALSE, times = 1)
irisTrain <- iris[trainIndex,]
irisTest  <- iris[-trainIndex,]

# Training a Linear SVM model
model <- train(Species ~ ., data = irisTrain, method = "svmLinear")
Making Predictions

Once you have your trained model, the next step is to make predictions on your test data. In R, you can use the predict function from the caret package to generate these predictions. Here's how you can do it:

# Making predictions
predictions <- predict(model, irisTest)

In this code snippet:

  • model is your trained machine learning model.
  • irisTest is your test dataset, which contains the same features as your training data, including the target labels. The predict function will ignore the labels and use only the features for making predictions.
Evaluating the Model: Confusion Matrix

After making predictions, you need to evaluate how well your model performed. One of the common ways to do this is by using a confusion matrix. But what exactly is a confusion matrix?

A confusion matrix is a table used to evaluate the performance of a classification model. It compares the actual target values with the predicted values and provides a detailed breakdown of your model's performance. The matrix includes the following terms:

  • True Positives (TP): The number of correct positive predictions.
  • True Negatives (TN): The number of correct negative predictions.
  • False Positives (FP): The number of incorrect positive predictions.
  • False Negatives (FN): The number of incorrect negative predictions.

The rows in a confusion matrix represent the actual classes, and the columns represent the predicted classes. This makes it easy to see where your model is making correct and incorrect classifications.

Here's how you can create and print a confusion matrix in R:

confusion <- confusionMatrix(predictions, irisTest$Species)
print(confusion)

In this code snippet:

  • confusionMatrix is a function from the caret package that takes the predictions and the actual target values as arguments and returns a confusion matrix.
  • irisTest$Species is the actual target values from your test dataset.

Here’s a rough idea of what you might see:

Confusion Matrix and Statistics

            Reference
Prediction   setosa versicolor virginica
  setosa         15          0         0
  versicolor      0         15         1
  virginica       0          0        14

Overall Statistics
                                          
               Accuracy : 0.9778          
                 95% CI : (0.8823, 0.9994)
    No Information Rate : 0.3333          
    P-Value [Acc > NIR] : < 2.2e-16       
                                          
                  Kappa : 0.9667          
                                          
 Mcnemar's Test P-Value : NA              

Statistics by Class:

                     Class: setosa Class: versicolor Class: virginica
Sensitivity                 1.0000            1.0000           0.9333
Specificity                 1.0000            0.9667           1.0000
Pos Pred Value              1.0000            0.9375           1.0000
Neg Pred Value              1.0000            1.0000           0.9677
Prevalence                  0.3333            0.3333           0.3333
Detection Rate              0.3333            0.3333           0.3111
Detection Prevalence        0.3333            0.3556           0.3111
Balanced Accuracy           1.0000            0.9833           0.9667
Evaluating the Model: Calculating Accuracy
Why It Matters

Evaluating your model is essential because it tells you how good your predictions are. A model that performs well on training data but poorly on test data is not useful. By utilizing tools like the confusion matrix, you can quantify your model's performance and gain insights into its accuracy and errors.

Precision
Recall (Sensitivity)
Example Calculations in R

Using the caret package, you can calculate these metrics from the confusion matrix object. Here's how you can do it:

# Evaluating the model
confusion <- confusionMatrix(predictions, irisTest$Species)
print(confusion)

# Extracting the relevant metrics
accuracy <- confusion$overall['Accuracy']
# Extracting metrics for Setosa (class 1)
precision_setosa <- confusion$byClass[1, 'Pos Pred Value']
recall_setosa <- confusion$byClass[1, 'Sensitivity']
# Extracting metrics for Versicolor (class 2)
precision_versicolor <- confusion$byClass[2, 'Pos Pred Value']
recall_versicolor <- confusion$byClass[2, 'Sensitivity']
# Extracting metrics for Virginica (class 3)
precision_virginica <- confusion$byClass[3, 'Pos Pred Value']
recall_virginica <- confusion$byClass[3, 'Sensitivity']

# Printing the extracted metrics
print(paste("Accuracy:", accuracy))
print(paste("Precision for Setosa:", precision_setosa))
print(paste("Recall for Setosa:", recall_setosa))
print(paste("Precision for Versicolor:", precision_versicolor))
print(paste("Recall for Versicolor:", recall_versicolor))
print(paste("Precision for Virginica:", precision_virginica))
print(paste("Recall for Virginica:", recall_virginica))

In this code:

  • confusion$overall['Accuracy'] gives you the accuracy of the model.
  • confusion$byClass[i, 'Pos Pred Value'] gives you the precision for class (i).
  • confusion$byClass[i, 'Sensitivity'] gives you the recall for class (i).

Note: The paste function in R concatenates strings together, allowing you to create a single string from multiple elements. In this example, paste is used to combine the metric names (e.g., "Accuracy:") with their respective values for easier readability when printing.

Here’s a rough idea of what you might see:

[1] "Accuracy: 0.977777777777778"
[1] "Precision for Setosa: 1"
[1] "Recall for Setosa: 1"
[1] "Precision for Versicolor: 0.9375"
[1] "Recall for Versicolor: 1"
[1] "Precision for Virginica: 1"
[1] "Recall for Virginica: 0.933333333333333"

These metrics provide a comprehensive view of your model's performance:

  • Accuracy tells you the overall effectiveness of the model.
  • Precision and Recall provide insights into the model's performance in terms of false positives and false negatives, which is crucial for imbalanced datasets.

Excited to see how your hard work pays off? Let's dive into the practice section and put your model to the test.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal