Conformal Prediction in R: Dry Bean Classification

Bar chart showing seven dry bean varieties, with Dermason tallest and Bombay shortest.

Dry bean identification with an honest calibration set and interpretable uncertainty

NoteThe distinction that matters

A 90% marginal coverage target does not mean each bean variety achieves 90% coverage. Prediction-set size and class-specific failures must be interpreted alongside average coverage.

The problem: accurate labels are not the whole story

Imagine a seed sorting system that labels a bean HOROZ. A point prediction is convenient, but it hides an important distinction: was that label obvious from the grain’s image-derived shape, or were several varieties nearly indistinguishable? A useful decision system should sometimes return several plausible varieties, rather than disguise ambiguity behind one label.

Split-conformal prediction wraps an ordinary classifier to create a prediction set. With a 90% nominal marginal coverage target, and under the method’s exchangeability assumptions, the true category is covered with at least 90% probability for a future exchangeable observation. That is a long-run marginal statement—not a 90% certainty for a particular seed or an every-class guarantee. The rule can produce empty sets, singletons or sets with multiple labels; their usefulness has to be checked on unseen data.

We will use a classification tree (rpart) because its terminal-node class proportions are straightforward to inspect and interpret. It is not presented as the highest-performing architecture for dry beans. The main lesson is how to calibrate and audit uncertainty around any probabilistic classifier.

Real dataset: seeds, not field trials

The UCI Dry Bean dataset was published in 2020 and contains images represented as 16 numerical measurements per grain, with one of seven varieties as the label. The sample unit is one pictured bean seed. Measures such as Area, Perimeter, MajorAxisLength and ShapeFactor1 describe segmented shapes; they are not soil, yield, fertilizer-treatment or weather variables. Therefore this tutorial supports prediction of the recorded labels, not causal conclusions about farming practices.

The observations were obtained from a pinned public mirror of the UCI data. The mirror has not been independently byte-matched to the archive distributed by UCI. The source spells two features AspectRation and roundness; their names are standardized in the analysis data without changing measurements. Exact repeated records are removed before creating independent data partitions, limiting a straightforward form of evaluation leakage.

1. Import, check and deduplicate

A model can return plausible-looking predictions with invalid inputs. Here we explicitly check the source schema, expected class names, numerical types, missing values and duplicate count before analysis. Rather than deleting unusual but potentially genuine beans, we remove only exact whole-row duplicates identified in the source audit.

if (!requireNamespace("rpart", quietly = TRUE)) {
  stop("The recommended R package 'rpart' is missing. Install it with install.packages('rpart').")
}

input_file <- "01_data/dry_bean_source.csv"
if (!file.exists(input_file)) {
  stop("Missing real data at ", input_file, ". Run the acquisition script first; do not substitute simulated records.")
}
dir.create("04_outputs", showWarnings = FALSE, recursive = TRUE)

source_beans <- read.csv(input_file, check.names = FALSE, stringsAsFactors = FALSE)
expected_names <- c(
  "Area", "Perimeter", "MajorAxisLength", "MinorAxisLength", "AspectRation",
  "Eccentricity", "ConvexArea", "EquivDiameter", "Extent", "Solidity",
  "roundness", "Compactness", "ShapeFactor1", "ShapeFactor2",
  "ShapeFactor3", "ShapeFactor4", "Class"
)
bean_levels <- c("BARBUNYA", "BOMBAY", "CALI", "DERMASON", "HOROZ", "SEKER", "SIRA")
if (!identical(names(source_beans), expected_names) || nrow(source_beans) != 13611L) {
  stop("The input does not match the Stage 2 audited mirror schema/count.")
}
if (anyNA(source_beans) || !all(vapply(source_beans[1:16], is.numeric, logical(1))) ||
    any(!is.finite(as.matrix(source_beans[1:16])))) {
  stop("Missing, nonnumeric or non-finite predictor values require investigation.")
}
if (!identical(sort(unique(source_beans$Class)), sort(bean_levels))) {
  stop("Unexpected seed-class names in the input.")
}
if (any(source_beans$Area <= 0) || any(source_beans$ConvexArea < source_beans$Area) ||
    any(source_beans$MinorAxisLength <= 0) || any(source_beans$MajorAxisLength <= 0)) {
  stop("Implausible seed-morphology measurements in the input.")
}

duplicates <- duplicated(source_beans)
if (sum(duplicates) != 68L || any(source_beans$Class[duplicates] != "HOROZ")) {
  stop("Duplicate counts differ from the Stage 2 full-mirror audit.")
}
beans <- source_beans[!duplicates, , drop = FALSE]
names(beans)[names(beans) == "AspectRation"] <- "AspectRatio"
names(beans)[names(beans) == "roundness"] <- "Roundness"
beans$Class <- factor(beans$Class, levels = bean_levels)
stopifnot(nrow(beans) == 13543L, !anyDuplicated(beans))
write.csv(beans, "01_data/dry_bean_analysis_unique.csv", row.names = FALSE)
cat("Source rows:", nrow(source_beans), "| exact duplicates:", sum(duplicates),
    "| unique analysis rows:", nrow(beans), "\n")
Source rows: 13611 | exact duplicates: 68 | unique analysis rows: 13543 

The analysis contains 13,543 distinct rows, down from 13,611 source records after removing 68 exact repetitions. All removed records belong to the HOROZ variety. Deduplication cannot identify biologically related seeds or batches captured under the same imaging conditions; that information is not available in these measurements.

2. Inspect imbalance before predicting

Some bean classes are more frequent than others. This matters because a classifier may appear strong on average while making worse predictions for rarer varieties. The distribution is a description of this dataset, not a claim about real-world variety prevalence.

class_counts <- data.frame(
  Class = bean_levels,
  N = as.integer(table(beans$Class)),
  Percent = round(100 * as.integer(table(beans$Class)) / nrow(beans), 2)
)
write.csv(class_counts, "04_outputs/01_class_counts.csv", row.names = FALSE)
print(class_counts)

png("04_outputs/01_class_balance.png", width = 1700, height = 950, res = 170)
par(mar = c(8, 5, 4, 2))
barplot(class_counts$N, names.arg = class_counts$Class, las = 2,
        col = "#30738C", border = NA, ylab = "Seeds in the analysis dataset",
        main = "Seven bean varieties: sample sizes are unequal")
dev.off()
Bean varieties remaining after exact deduplication
Class N Percent
BARBUNYA 1322 9.76
BOMBAY 522 3.85
CALI 1630 12.04
DERMASON 3546 26.18
HOROZ 1860 13.73
SEKER 2027 14.97
SIRA 2636 19.46

Bar chart showing seven dry bean varieties, with Dermason tallest and Bombay shortest.

DERMASON contributes the most analyzed seeds and BOMBAY the fewest. Because representation is unequal, aggregate classification accuracy may obscure errors within smaller groups.

3. Protect the calibration set and the test set

The data are shuffled once with a fixed seed, then divided into approximately 60% training, 20% calibration, and 20% testing. Training fits the tree; calibration is reserved only for learning an uncertainty threshold; testing is untouched until the final performance audit. These three roles are not interchangeable.

We intentionally use an unstratified random partition for the primary split-conformal demonstration, since splitting exchangeable rows at random preserves the simple exchangeability argument used for the nominal guarantee. We nevertheless check that each of the seven varieties appears in every partition. A future deployment study must also ask whether beans from the same photography setup or seed lot could be correlated; this dataset does not provide those grouping identifiers.

set.seed(20261106)
sampled_rows <- sample.int(nrow(beans))
n_train <- floor(0.60 * nrow(beans))
n_cal <- floor(0.20 * nrow(beans))
train_ids <- sampled_rows[seq_len(n_train)]
cal_ids <- sampled_rows[seq.int(n_train + 1L, n_train + n_cal)]
test_ids <- sampled_rows[seq.int(n_train + n_cal + 1L, nrow(beans))]
stopifnot(length(unique(c(train_ids, cal_ids, test_ids))) == nrow(beans))

training <- beans[train_ids, , drop = FALSE]
calibration <- beans[cal_ids, , drop = FALSE]
testing <- beans[test_ids, , drop = FALSE]
stopifnot(all(table(training$Class) > 0L), all(table(calibration$Class) > 0L),
          all(table(testing$Class) > 0L))
split_counts <- data.frame(
  Class = bean_levels,
  Train = as.integer(table(training$Class)),
  Calibration = as.integer(table(calibration$Class)),
  Test = as.integer(table(testing$Class))
)
write.csv(split_counts, "04_outputs/02_split_counts.csv", row.names = FALSE)
print(split_counts)
     Class Train Calibration Test
1 BARBUNYA   791         256  275
2   BOMBAY   310         106  106
3     CALI   966         331  333
4 DERMASON  2152         704  690
5    HOROZ  1111         357  392
6    SEKER  1187         405  435
7     SIRA  1608         549  479
Independent partitions and class counts
Class Train Calibration Test
BARBUNYA 791 256 275
BOMBAY 310 106 106
CALI 966 331 333
DERMASON 2152 704 690
HOROZ 1111 357 392
SEKER 1187 405 435
SIRA 1608 549 479

4. Train a classifier that produces class probabilities

A classification tree recursively divides the space of measured seed shapes. Within each terminal region, the fraction of training beans belonging to each variety gives the tree’s estimated class probabilities. We deliberately fix the tree’s complexity controls before looking at calibration or test labels. Using calibration data to tune the tree would compromise the clean role separation needed for split conformal prediction.

The tree model works with the numerical morphology features directly; no global normalization is necessary for axis-aligned splits. The returned probabilities can be coarse or overconfident, which can affect prediction-set size even if the conformal mechanism preserves its marginal coverage claim under assumptions.

# Tree complexity is fixed BEFORE seeing calibration or test labels.
model <- rpart::rpart(
  Class ~ ., data = training, method = "class",
  control = rpart::rpart.control(cp = 0.001, minsplit = 30,
                                  maxdepth = 10, xval = 0)
)
cal_prob <- predict(model, newdata = calibration, type = "prob")
test_prob <- predict(model, newdata = testing, type = "prob")
if (!identical(colnames(cal_prob), bean_levels) ||
    !identical(colnames(test_prob), bean_levels) ||
    any(!is.finite(cal_prob)) || any(!is.finite(test_prob)) ||
    any(abs(rowSums(cal_prob) - 1) > 1e-8) ||
    any(abs(rowSums(test_prob) - 1) > 1e-8)) {
  stop("Class probabilities have unexpected levels or invalid values.")
}

The fitted tree contains 29 terminal leaves. Leaf frequencies produce one estimated probability for each of the seven classes; neither a large probability nor the number of leaves establishes reliable probability calibration. The next step assesses those scores against independent labeled examples.

5. How split conformal decides which labels to include

For each calibration seed, find the tree’s probability assigned to its observed true variety and compute the nonconformity score:

sáµ¢ = 1 − p̂(Yáµ¢ | Xáµ¢).

If the tree assigns the true label a high probability, the score is small. Low confidence in the true label produces a large score. At miscoverage target α = 0.10, sort the calibration scores and choose the conservative finite-sample rank:

k = ⌈(n_cal + 1)(1 − α)⌉, q̂ = s₍â‚–₎.

The method then includes any candidate variety whose score is at most the learned cutoff:

Ĉ(x) = {y : 1 − p̂(y | x) ≤ q̂}.

Using the ceiling rank, rather than an arbitrary 90th percentile interpolation, is what corresponds to the finite-sample split-conformal coverage convention. No test labels are used to learn the threshold. The code also handles the exceptional rank beyond the calibration sample size by selecting an infinite cutoff.

alpha <- 0.10
cal_truth <- match(as.character(calibration$Class), colnames(cal_prob))
cal_scores <- 1 - cal_prob[cbind(seq_len(nrow(cal_prob)), cal_truth)]
k <- ceiling((length(cal_scores) + 1) * (1 - alpha))
cutoff <- if (k > length(cal_scores)) Inf else sort(cal_scores)[k]

# A label belongs to the set when its nonconformity score is <= cutoff.
set_membership <- (1 - test_prob) <= cutoff
colnames(set_membership) <- bean_levels
set_size <- rowSums(set_membership)
test_truth <- match(as.character(testing$Class), bean_levels)
covered <- set_membership[cbind(seq_len(nrow(set_membership)), test_truth)]
point_label <- bean_levels[max.col(test_prob, ties.method = "first")]

The cutoff is 0.411, calculated from 2708 independent calibration scores. A candidate label is retained when its estimated class probability is at least 58.9%. Because this probability threshold is above 50%, two different labels cannot both qualify: their probabilities would sum to more than 100%. This classifier can therefore produce only singleton or empty prediction sets at the observed cutoff. The threshold is not a probability that an individual prediction is correct.

6. Evaluate reliability and usefulness

We now read the untouched test labels for the first time. Coverage is the share of test seeds whose true class occurs inside the prediction set. Mean set size measures ambiguity: a model returning all seven classes is usually of little practical use even though it would cover every label. We also report the ordinary top-class accuracy and empty-set count, which answer different questions.

point_accuracy <- mean(point_label == as.character(testing$Class))
empirical_coverage <- mean(covered)
mean_set_size <- mean(set_size)
empty_sets <- sum(set_size == 0L)
metrics <- data.frame(
  Target_Coverage = 1 - alpha,
  Empirical_Coverage = empirical_coverage,
  Point_Accuracy = point_accuracy,
  Mean_Set_Size = mean_set_size,
  Empty_Sets = empty_sets,
  Calibration_N = length(cal_scores),
  Test_N = nrow(testing),
  Calibration_Cutoff = cutoff
)
class_metrics <- do.call(rbind, lapply(bean_levels, function(bean) {
  use <- as.character(testing$Class) == bean
  data.frame(Class = bean, Test_N = sum(use), Coverage = mean(covered[use]),
             Point_Accuracy = mean(point_label[use] == bean),
             Mean_Set_Size = mean(set_size[use]))
}))
size_metrics <- data.frame(Set_Size = 0:length(bean_levels),
                           Count = tabulate(set_size + 1L, nbins = length(bean_levels) + 1L))
confusion <- as.data.frame(table(
  True_Class = testing$Class,
  Predicted_Class = factor(point_label, levels = bean_levels)
))
set_names <- vapply(seq_len(nrow(testing)), function(i) {
  paste(bean_levels[set_membership[i, ]], collapse = " | ")
}, character(1))
test_predictions <- data.frame(
  True_Class = as.character(testing$Class), Point_Prediction = point_label,
  Prediction_Set = set_names, Set_Size = set_size, Covered = covered
)

write.csv(metrics, "04_outputs/03_overall_metrics.csv", row.names = FALSE)
write.csv(class_metrics, "04_outputs/04_class_metrics.csv", row.names = FALSE)
write.csv(size_metrics, "04_outputs/05_set_size_distribution.csv", row.names = FALSE)
write.csv(confusion, "04_outputs/06_confusion_matrix.csv", row.names = FALSE)
write.csv(test_predictions, "04_outputs/07_test_predictions.csv", row.names = FALSE)
cat(sprintf("Target marginal coverage: %.0f%% | Held-out coverage: %.1f%%\n",
            100 * (1 - alpha), 100 * empirical_coverage))
cat(sprintf("Held-out point accuracy: %.1f%% | Mean set size: %.2f | Empty sets: %d\n",
            100 * point_accuracy, mean_set_size, empty_sets))
print(class_metrics)
print(size_metrics)
Held-out metrics (computed by running this article; not pre-filled)
Target_Coverage Empirical_Coverage Point_Accuracy Mean_Set_Size Empty_Sets Calibration_N Test_N Calibration_Cutoff
0.9 0.89 0.891 0.996 12 2708 2710 0.411

The fitted procedure covers the true label for 2411 of 2710 test beans, or 88.97%, compared with its 90% nominal marginal target. Ordinary point accuracy is 89.11% (2415 correct labels). The mean prediction-set size is 0.9956, and 12 test seeds receive an empty set. An observed test fraction can fall below a marginal target in a realized sample without, by itself, disproving the method’s exchangeability-based coverage guarantee.

Per-variety test coverage, accuracy and set size
Class Test_N Coverage Point_Accuracy Mean_Set_Size
BARBUNYA 275 0.822 0.822 0.996
BOMBAY 106 0.981 0.981 1.000
CALI 333 0.862 0.874 0.988
DERMASON 690 0.925 0.925 1.000
HOROZ 392 0.913 0.913 0.995
SEKER 435 0.915 0.915 1.000
SIRA 479 0.835 0.835 0.990
Test prediction-set cardinality
Set_Size Count
0 12
1 2698
2 0
3 0
4 0
5 0
6 0
7 0

The seven class-specific estimates vary appreciably. BARBUNYA has 82.18% observed coverage on 275 seeds, and SIRA has 83.51% on 479. By contrast, BOMBAY reaches 98.11% on only 106. Subgroup proportions have different sampling precision and are not covered by a simultaneous class-conditional guarantee. Improving the classifier should involve genuinely separate validation, not adjusting the cutoff to fit this test sample.

7. Visualize the trade-off

Three complementary diagnostics reveal what a single accuracy number conceals: the score distribution behind calibration, the breadth of resulting prediction sets, and the degree to which coverage differs among varieties.

png("04_outputs/02_calibration_scores.png", width = 1700, height = 1000, res = 170)
par(mar = c(5, 5, 4, 2))
hist(cal_scores, breaks = 35, xlim = c(0, 1), col = "#7AA6B8", border = "white",
     main = "Calibration: higher scores signal a poorer true-class fit",
     xlab = "Nonconformity score: 1 minus true-class probability")
abline(v = cutoff, col = "#C75050", lwd = 3, lty = 2)
legend("topright", legend = sprintf("90%% cutoff = %.3f", cutoff),
       col = "#C75050", lwd = 3, lty = 2, bty = "n")
dev.off()

png("04_outputs/03_prediction_set_sizes.png", width = 1700, height = 1000, res = 170)
par(mar = c(5, 5, 4, 2))
barplot(size_metrics$Count, names.arg = size_metrics$Set_Size,
        col = "#30738C", border = NA, xlab = "Number of plausible bean classes",
        ylab = "Number of held-out beans", main = "Are prediction sets useful or too broad?")
dev.off()

png("04_outputs/04_coverage_by_class.png", width = 1700, height = 1100, res = 170)
par(mar = c(9, 5, 4, 2))
barplot(class_metrics$Coverage, names.arg = paste0(class_metrics$Class,
        " (n=", class_metrics$Test_N, ")"), las = 2, ylim = c(0, 1),
        col = "#30738C", border = NA, ylab = "Observed held-out coverage",
        main = "Marginal coverage does not guarantee every class is covered")
abline(h = 1 - alpha, col = "#C75050", lwd = 3, lty = 2)
legend("topright", legend = "90% marginal target", col = "#C75050",
       lwd = 3, lty = 2, bty = "n")
dev.off()

writeLines(capture.output(sessionInfo()), "04_outputs/08_R_session_info.txt")
cat("Saved analytical tables and four figures under 04_outputs/.\n")

Histogram of calibration scores between zero and one, with the learned threshold as a red dashed vertical line.

True-class nonconformity scores concentrate near zero, but a tail of difficult calibration cases reaches high scores. The dashed line marks the threshold used to include candidate varieties.

Low nonconformity scores correspond to high estimated probabilities for the known true class; large scores indicate weak support for that label. The cutoff arises from these independent calibration cases, not from the test labels.

Bar plot of prediction-set size with 2,698 sets of size one, 12 sets of size zero, and none larger.

Nearly every held-out bean receives a singleton prediction set; a small number receive no candidate labels. There are no multi-label sets for this fitted threshold.

Of the 2710 test records, 2698 receive a singleton and 12 receive no eligible label; 0 contain multiple labels. Four empty-set cases nevertheless have the correct top-ranked class. Thus point accuracy exceeds conformal coverage by four cases. Empty sets indicate that no score passed the calibrated rule, not that the specimen belongs to a newly discovered class.

Bar chart of observed conformal coverage by true bean class, with sample sizes and a dashed marginal target at 90 percent.

Coverage is uneven across varieties: BARBUNYA, SIRA and CALI lie below the dashed 90% marginal target. The reference is not a per-class coverage guarantee.

The final figure reveals that a useful-looking marginal average can coexist with weaker reliability for particular labels. For instance, BARBUNYA and SIRA remain below 85% on this test set. This may reflect class overlap, the fitted tree’s score quality or ordinary sampling variation; the plot alone cannot identify a causal mechanism. The confusion matrix provides additional descriptive clues: 26 true CALI beans are predicted as BARBUNYA, and 59 true SIRA beans are predicted as DERMASON.

What can and cannot be concluded

  • Supported by this test set: the trained tree’s point accuracy, prediction-set coverage, mean set size, empty-set count and the observed differences among true classes.
  • Cannot conclude: an individual bean has a 90% chance of correct classification; each variety has guaranteed 90% coverage; the model will transfer to different cameras, harvests or regions; or any morphological feature has a causal biological effect on the label.
  • Study limitations: all predictors are image-derived features from one historical dataset without lot or batch identifiers; near-duplicates may remain; the tree is a transparent baseline; changing cameras or measurement pipelines can alter its scores; and the public mirror has not been byte-matched to the UCI archive.

Use this in a thesis or seed-quality project

The same three-way separation applies to pathology, crop grading, pest identification and other multiclass analyses when labels are well-defined and the evaluation units can reasonably be treated as exchangeable. Begin by asking what a row means, whether two rows share a plant/site/lot, whether the class proportions differ in deployment, and whether your application requires subgroup guarantees. If the source study has clusters or time dependence, replace the naive random-split scheme with a validation design suited to that setting and reconsider conformal coverage assumptions.

Sources and credit

  1. Koklu, M. & Ozkan, I. A. (2020). Multiclass classification of dry beans using computer vision and machine learning techniques. Computers and Electronics in Agriculture, 174, 105507. DOI.
  2. UCI Machine Learning Repository, Dry Bean dataset, dataset DOI 10.24432/C50S4B, CC BY 4.0.
  3. Angelopoulos, A. N. & Bates, S. (2023). Conformal Prediction: A Gentle Introduction. Foundations and Trends in Machine Learning. DOI.
  4. Pinned public mirror, with original UCI dataset credited above.

Comments