Assignment_Week2B_CodebaseClassification Metrics)

Author

Yalda Azamee

Published

September 13, 2026

Introduction

This assignment evaluates a binary classification model that predicts whether a penguin is female, using the penguin_predictions.csv file from the course GitHub repository (data link). The model gives each penguin a probability of being female, and a probability threshold turns that probability into a class prediction. I compare the model with a simple baseline (the null error rate) and examine how the thresholds 0.2, 0.5, and 0.8 change the confusion matrix and the performance metrics.

Approach

I will begin by exploring the penguin_predictions.csv dataset to understand the structure of the data and the distribution of the actual sex classes. I will first determine whether the classes are balanced and calculate the null error rate based on the majority class. This will provide a baseline for evaluating whether the classification model is performing better than a simple majority-class prediction.

Next, I will focus on the .pred_female variable, which contains the model’s predicted probability for the female class. Rather than relying on the existing .pred_class variable, I will use the predicted probabilities to generate class predictions at three different thresholds: 0.2, 0.5, and 0.8. This will allow me to examine how changing the threshold affects the number and type of classification errors.

For each threshold, I will compare the predicted class with the actual sex value and organize the results into a confusion matrix containing true positives, false positives, true negatives, and false negatives. I will then use these values to calculate accuracy, precision, recall, and F1 score and compare the results across the three thresholds.

One challenge I anticipate is making sure that the definition of the positive class is consistent throughout the analysis. Since the assignment focuses on predicting the female class, I will treat female as the positive class and make sure that the interpretation of TP, FP, TN, and FN follows this definition. I will also pay attention to the difference between predicted probabilities and predicted class labels so that changing the threshold produces the intended predictions.

Finally, I will use the results to explain the tradeoff between lower and higher probability thresholds. In particular, I will consider how a lower threshold may identify more positive cases while also producing more false positives, whereas a higher threshold may reduce false positives but increase false negatives. I will connect these tradeoffs to real-world situations where the consequences of different types of classification errors may influence the choice of threshold.

I will use R and ggplot2 for the analysis and visualization and structure the work so that the analysis is reproducible and can be tested using the provided data source.

For Data source; I will use the penguin_predictions.csv dataset provided through the course GitHub repository. The dataset contains model-predicted probabilities, predicted class labels, and the actual class labels.

Load the Data

The data is read directly from the course GitHub repository, so the code runs on any computer.

library(tidyverse)

url <- "https://raw.githubusercontent.com/acatlin/data/refs/heads/master/penguin_predictions.csv"
penguins <- read_csv(url, show_col_types = FALSE)

glimpse(penguins)
Rows: 93
Columns: 3
$ .pred_female <dbl> 0.99217462, 0.95423945, 0.98473504, 0.18702056, 0.9947012…
$ .pred_class  <chr> "female", "female", "female", "male", "female", "female",…
$ sex          <chr> "female", "female", "female", "female", "female", "female…

The assignment describes .pred_class and sex as 1/0 values, but in the file they are text labels ("female" and "male"). I convert sex to 1 (female, the positive class) and 0 (male), so it can be compared with my own predictions.

penguins <- penguins |>
  mutate(actual = if_else(sex == "female", 1, 0))

penguins |> count(sex, actual)
# A tibble: 2 × 3
  sex    actual     n
  <chr>   <dbl> <int>
1 female      1    39
2 male        0    54

Null Error Rate

The null model ignores the data and always predicts the most common class. Its error rate is the share of observations that are not in the majority class.

class_counts <- penguins |>
  count(sex) |>
  mutate(percent = round(100 * n / sum(n), 1))

class_counts
# A tibble: 2 × 3
  sex        n percent
  <chr>  <int>   <dbl>
1 female    39    41.9
2 male      54    58.1
majority_class  <- class_counts$sex[which.max(class_counts$n)]
null_error_rate <- 1 - max(class_counts$n) / sum(class_counts$n)

round(null_error_rate, 3)
[1] 0.419
ggplot(class_counts, aes(x = sex, y = n, fill = sex)) +
  geom_col(width = 0.6) +
  geom_text(aes(label = paste0(n, " (", percent, "%)")), vjust = -0.5, size = 4.5) +
  scale_fill_manual(values = c(female = "#D55E00", male = "#0072B2")) +
  scale_y_continuous(expand = expansion(mult = c(0, 0.15))) +
  labs(
    title    = "Distribution of the Actual Class (sex)",
    subtitle = paste0("Always predicting '", majority_class, "' gives a null error rate of ",
                      round(100 * null_error_rate, 1), "%"),
    x        = "Actual sex",
    y        = "Number of penguins"
  ) +
  theme_minimal(base_size = 12) +
  theme(legend.position = "none")

The majority class is male (54 of 93 penguins), so a model that always predicts “male” is wrong 41.9% of the time.

Why the null error rate matters: it is the baseline that any real model must beat. Accuracy alone can be misleading when the classes are unbalanced. For example, if 95% of emails are not spam, a “model” that never flags spam is 95% accurate but useless. Comparing a model’s error rate with the null error rate shows whether the model has actually learned something from the data.

Confusion Matrices at Three Thresholds

I ignore the existing .pred_class column and recompute the predicted class from .pred_female for each threshold: a penguin is predicted female (1) if .pred_female > threshold, otherwise male (0). With female as the positive class:

  • TP: predicted female, actually female
  • FP: predicted female, actually male
  • TN: predicted male, actually male
  • FN: predicted male, actually female
confusion_counts <- function(threshold) {
  penguins |>
    mutate(predicted = ifelse(.pred_female > threshold, 1, 0)) |>
    summarise(
      threshold = threshold,
      TP = sum(predicted == 1 & actual == 1),
      FP = sum(predicted == 1 & actual == 0),
      TN = sum(predicted == 0 & actual == 0),
      FN = sum(predicted == 0 & actual == 1)
    )
}

thresholds <- c(0.2, 0.5, 0.8)
counts     <- map_dfr(thresholds, confusion_counts)

counts
# A tibble: 3 × 5
  threshold    TP    FP    TN    FN
      <dbl> <int> <int> <int> <int>
1       0.2    37     6    48     2
2       0.5    36     3    51     3
3       0.8    36     2    52     3
# Show each threshold as a 2 x 2 confusion matrix
for (i in seq_len(nrow(counts))) {
  r <- counts[i, ]
  matrix_table <- tibble(
    ` `                 = c("Actual: female", "Actual: male"),
    `Predicted: female` = c(r$TP, r$FP),
    `Predicted: male`   = c(r$FN, r$TN)
  )
  print(knitr::kable(matrix_table, caption = paste("Confusion matrix, threshold =", r$threshold)))
  cat("\n")
}
Confusion matrix, threshold = 0.2
Predicted: female Predicted: male
Actual: female 37 2
Actual: male 6 48
Confusion matrix, threshold = 0.5
Predicted: female Predicted: male
Actual: female 36 3
Actual: male 3 51
Confusion matrix, threshold = 0.8
Predicted: female Predicted: male
Actual: female 36 3
Actual: male 2 52

As a check, the threshold of 0.5 should give the same predictions as the existing .pred_class column:

all((penguins$.pred_female > 0.5) == (penguins$.pred_class == "female"))
[1] TRUE

Performance Metrics

  • Accuracy = (TP + TN) / total: the share of all predictions that are correct.
  • Precision = TP / (TP + FP): of the penguins predicted female, the share that are actually female.
  • Recall = TP / (TP + FN): of the actual females, the share the model found.
  • F1 = 2 × Precision × Recall / (Precision + Recall): the harmonic mean of precision and recall.
metrics <- counts |>
  mutate(
    accuracy  = (TP + TN) / (TP + FP + TN + FN),
    precision = TP / (TP + FP),
    recall    = TP / (TP + FN),
    f1        = 2 * precision * recall / (precision + recall)
  )

metrics |>
  select(Threshold = threshold, Accuracy = accuracy, Precision = precision,
         Recall = recall, `F1 score` = f1) |>
  knitr::kable(digits = 3, caption = "Performance metrics by threshold (positive class = female)")
Performance metrics by threshold (positive class = female)
Threshold Accuracy Precision Recall F1 score
0.2 0.914 0.860 0.949 0.902
0.5 0.935 0.923 0.923 0.923
0.8 0.946 0.947 0.923 0.935

Interpretation:

  • At every threshold, accuracy (0.914 to 0.946) is far above the null model’s accuracy of 0.581, so the model is much better than always guessing “male”.
  • Lowering the threshold to 0.2 predicts female more often: recall is 0.949 (it finds more of the actual females), but precision falls to 0.86 because more males are wrongly predicted female (6 false positives).
  • Raising the threshold to 0.8 does the opposite: precision rises to 0.947 (only 2 false positives), while recall is 0.923, lower than at 0.2, because 3 females are missed (false negatives).
  • In this data, the 0.8 threshold has the highest F1 score (0.935). The differences between thresholds are small because most predicted probabilities are very close to 0 or 1, so changing the threshold changes only a few predictions.

Threshold Use Cases

When a 0.2 threshold is preferable (missing a positive is costly): medical screening, for example an early cancer screening test. A low threshold flags anyone with even a moderate probability of disease. This creates more false positives, but those people only need a follow-up test, while a false negative (a missed cancer) can be life-threatening. High recall matters more than high precision.

When a 0.8 threshold is preferable (a false positive is costly): automatic fraud blocking of credit card transactions. A high threshold only blocks transactions the model is very confident are fraudulent. Blocking a legitimate purchase frustrates customers and loses sales, so it is better to accept some missed fraud (which can be reviewed later) than to block many honest customers. High precision matters more than high recall.

Conclusions

  • The classes are somewhat unbalanced: 58.1% male and 41.9% female, giving a null error rate of 0.419.
  • The model clearly beats this baseline at all three thresholds. At 0.5, accuracy is 0.935 and F1 is 0.923.
  • The threshold controls the tradeoff between precision and recall. A lower threshold finds more females but makes more false-positive errors; a higher threshold makes fewer false-positive errors but misses more females.
  • There is no single best threshold. The right choice depends on which type of error is more costly in the real situation.

AI Use

Anthropic. (2026). Claude Opus 5.5 [Large language model]. https://claude.ai. Accessed November 30, 2026. Used to help understant the assignment and the requirments.