• Descriptive
    • Moments
    • Concentration
    • Central Tendency
    • Variability
    • Stem-and-Leaf Plot
    • Histogram & Frequency Table
    • Data Quality Forensics
    • Conditional EDA
    • Quantiles
    • Kernel Density Estimation
    • Normal QQ Plot
    • Bootstrap Plot

    • Multivariate Descriptive Statistics
  • Distributions
    • Binomial Probabilities
    • Geometric Probabilities
    • Negative Binomial Probabilities
    • Hypergeometric Probabilities
    • Multinomial Probabilities
    • Dirichlet
    • Poisson Probabilities

    • Exponential
    • Gamma
    • Erlang
    • Weibull
    • Rayleigh
    • Maxwell-Boltzmann
    • Lognormal
    • Pareto
    • Inverse Gamma
    • Inverse Chi-Square

    • Beta
    • Power
    • Beta Prime (Inv. Beta)
    • Triangular

    • Normal (area)
    • Logistic
    • Laplace
    • Cauchy (standard)
    • Cauchy (location-scale)
    • Gumbel
    • Fréchet
    • Generalized Extreme Value

    • Normal RNG
    • ML Fitting
    • Tukey Lambda PPCC
    • Box-Cox Normality Plot
    • Noncentral t
    • Noncentral F
    • Sample Correlation r

    • Empirical Tests
  • Hypotheses
    • Theoretical Aspects of Hypothesis Testing
    • Bayesian Inference
    • Minimum Sample Size

    • Empirical Tests
    • Multivariate (pair-wise) Testing
  • Models
    • Manual Model Building
    • Guided Model Building
  • Time Series
    • Time Series Plot
    • Decomposition
    • Exponential Smoothing

    • Blocked Bootstrap Plot
    • Mean Plot
    • (P)ACF
    • VRM
    • Standard Deviation-Mean Plot
    • Spectral Analysis
    • ARIMA

    • Cross Correlation Function
    • Granger Causality
  1. Model Building Strategies
  2. 159  Manual Model Building
  • Preface
  • Getting Started
    • 1  Introduction
    • 2  Why Do We Need Innovative Technology?
    • 3  Basic Definitions
    • 4  The Big Picture: Why We Analyze Data
  • Introduction to Probability
    • 5  Definitions of Probability
    • 6  Jeffreys’ axiom system
    • 7  Bayes’ Theorem
    • 8  Sensitivity and Specificity
    • 9  Naive Bayes Classifier
    • 10  Law of Large Numbers

    • 11  Problems
  • Probability Distributions
    • 12  Bernoulli Distribution
    • 13  Binomial Distribution
    • 14  Geometric Distribution
    • 15  Negative Binomial Distribution
    • 16  Hypergeometric Distribution
    • 17  Multinomial Distribution
    • 18  Poisson Distribution

    • 19  Uniform Distribution (Rectangular Distribution)
    • 20  Normal Distribution (Gaussian Distribution)
    • 21  Gaussian Naive Bayes Classifier
    • 22  Chi Distribution
    • 23  Chi-squared Distribution (1 parameter)
    • 24  Chi-squared Distribution (2 parameters)
    • 25  Student t-Distribution
    • 26  Fisher F-Distribution
    • 27  Exponential Distribution
    • 28  Lognormal Distribution
    • 29  Gamma Distribution
    • 30  Beta Distribution
    • 31  Weibull Distribution
    • 32  Pareto Distribution
    • 33  Inverse Gamma Distribution
    • 34  Rayleigh Distribution
    • 35  Erlang Distribution
    • 36  Logistic Distribution
    • 37  Laplace Distribution
    • 38  Gumbel Distribution
    • 39  Cauchy Distribution
    • 40  Triangular Distribution
    • 41  Power Distribution
    • 42  Beta Prime Distribution
    • 43  Sample Correlation Distribution
    • 44  Dirichlet Distribution
    • 45  Generalized Extreme Value (GEV) Distribution
    • 46  Frechet Distribution
    • 47  Noncentral t Distribution
    • 48  Noncentral F Distribution
    • 49  Inverse Chi-Squared Distribution
    • 50  Maxwell-Boltzmann Distribution
    • 51  Distribution Relationship Map

    • 52  Problems
  • Descriptive Statistics & Exploratory Data Analysis
    • 53  Types of Data
    • 54  Datasheets

    • 55  Frequency Plot (Bar Plot)
    • 56  Frequency Table
    • 57  Contingency Table
    • 58  Binomial Classification Metrics
    • 59  Confusion Matrix
    • 60  ROC Analysis

    • 61  Stem-and-Leaf Plot
    • 62  Histogram
    • 63  Data Quality Forensics
    • 64  Quantiles
    • 65  Central Tendency
    • 66  Variability
    • 67  Skewness & Kurtosis
    • 68  Concentration
    • 69  Notched Boxplot
    • 70  Scatterplot
    • 71  Pearson Correlation
    • 72  Rank Correlation
    • 73  Partial Pearson Correlation
    • 74  Simple Linear Regression
    • 75  Moments
    • 76  Quantile-Quantile Plot (QQ Plot)
    • 77  Normal Probability Plot
    • 78  Probability Plot Correlation Coefficient Plot (PPCC Plot)
    • 79  Box-Cox Normality Plot
    • 80  Kernel Density Estimation
    • 81  Bivariate Kernel Density Plot
    • 82  Conditional EDA: Panel Diagnostics
    • 83  Bootstrap Plot (Central Tendency)
    • 84  Survey Scores Rank Order Comparison
    • 85  Cronbach Alpha

    • 86  Equi-distant Time Series
    • 87  Time Series Plot (Run Sequence Plot)
    • 88  Mean Plot
    • 89  Blocked Bootstrap Plot (Central Tendency)
    • 90  Standard Deviation-Mean Plot
    • 91  Variance Reduction Matrix
    • 92  (Partial) Autocorrelation Function
    • 93  Periodogram & Cumulative Periodogram

    • 94  Problems
  • Hypothesis Testing
    • 95  Normal Distributions revisited
    • 96  The Population
    • 97  The Sample
    • 98  The One-Sided Hypothesis Test
    • 99  The Two-Sided Hypothesis Test
    • 100  When to use a one-sided or two-sided test?
    • 101  What if \(\sigma\) is unknown?
    • 102  The Central Limit Theorem (revisited)
    • 103  Statistical Test of the Population Mean with known Variance
    • 104  Statistical Test of the Population Mean with unknown Variance
    • 105  Statistical Test of the Variance
    • 106  Statistical Test of the Population Proportion
    • 107  Statistical Test of the Standard Deviation \(\sigma\)
    • 108  Statistical Test of the difference between Means -- Independent/Unpaired Samples
    • 109  Statistical Test of the difference between Means -- Dependent/Paired Samples
    • 110  Statistical Test of the difference between Variances -- Independent/Unpaired Samples

    • 111  Hypothesis Testing for Research Purposes
    • 112  Decision Thresholds, Alpha, and Confidence Levels
    • 113  Bayesian Inference for Decision-Making
    • 114  One Sample t-Test
    • 115  Skewness & Kurtosis Tests
    • 116  Paired Two Sample t-Test
    • 117  Wilcoxon Signed-Rank Test
    • 118  Unpaired Two Sample t-Test
    • 119  Unpaired Two Sample Welch Test
    • 120  Two One-Sided Tests (TOST) for Equivalence
    • 121  Mann-Whitney U test (Wilcoxon Rank-Sum Test)
    • 122  Bayesian Two Sample Test
    • 123  Median Test based on Notched Boxplots
    • 124  Chi-Squared Tests for Count Data
    • 125  Kolmogorov-Smirnov Test
    • 126  One Way Analysis of Variance (1-way ANOVA)
    • 127  Kruskal-Wallis Test
    • 128  Two Way Analysis of Variance (2-way ANOVA)
    • 129  Repeated Measures ANOVA
    • 130  Friedman Test
    • 131  Testing Correlations
    • 132  A Note on Causality

    • 133  Problems
  • Regression Models
    • 134  Simple Linear Regression Model (SLRM)
    • 135  Multiple Linear Regression Model (MLRM)
    • 136  Logistic Regression
    • 137  Generalized Linear Models
    • 138  Multinomial and Ordinal Logistic Regression
    • 139  Cox Proportional Hazards Regression
    • 140  Conditional Inference Trees
    • 141  Leaf Diagnostics for Conditional Inference Trees
    • 142  Conditional Random Forests
    • 143  Hypothesis Testing with Linear Regression Models (from a Practical Point of View)

    • 144  Problems
  • Introduction to Time Series Analysis
    • 145  Case: the Market of Health and Personal Care Products
    • 146  Decomposition of Time Series
    • 147  Ad hoc Forecasting of Time Series
  • Box-Jenkins Analysis
    • 148  Introduction to Box-Jenkins Analysis
    • 149  Theoretical Concepts
    • 150  Stationarity
    • 151  Identifying ARMA parameters
    • 152  Estimating ARMA Parameters and Residual Diagnostics
    • 153  Forecasting with ARIMA models
    • 154  Intervention Analysis
    • 155  Cross-Correlation Function
    • 156  Transfer Function Noise Models
    • 157  General-to-Specific Modeling
  • Model Building Strategies
    • 158  Introduction to Model Building Strategies
    • 159  Manual Model Building
    • 160  Model Validation
    • 161  Regularization Methods
    • 162  Hyperparameter Optimization Strategies
    • 163  Guided Model Building in Practice
    • 164  Diagnostics, Revision, and Guided Forecasting
    • 165  Leakage, Target Encoding, and Robust Regression
  • References
  • Appendices
    • Appendices
    • A  Method Selection Guide
    • B  Presentations and Teaching Materials
    • C  R Language Concepts for Statistical Computing
    • D  Matrix Algebra
    • E  Standard Normal Table (Gaussian Table)
    • F  Critical values of Student’s \(t\) distribution with \(\nu\) degrees of freedom
    • G  Upper-tail critical values of the \(\chi^2\)-distribution with \(\nu\) degrees of freedom
    • H  Lower-tail critical values of the \(\chi^2\)-distribution with \(\nu\) degrees of freedom

Table of contents

  • 159.1 The Manual Model Building App
  • 159.2 The Dataset: Pima.tr
  • 159.3 Fitting a Naive Bayes Classifier
  • 159.4 Comparing with Logistic Regression
  • 159.5 Comparing with a Conditional Inference Tree
  • 159.6 Model Comparison with ROC Curves
  • 159.7 The Effect of Training Percentage
  • 159.8 The Effect of Shuffling
  • 159.9 Practical Exercises
  1. Model Building Strategies
  2. 159  Manual Model Building

159  Manual Model Building

Before using a guided workflow that automates audit, strategy, and validation, it is useful to work through a classification problem manually. In this chapter you will use the app available in the menu Models / Manual Model Building to fit individual models, compare their confusion matrices, and observe how the training percentage and row ordering affect the results.

159.1 The Manual Model Building App

The app available in the menu Models / Manual Model Building provides a direct interface for fitting and comparing classifiers. Its layout contains the following components:

Component Purpose
Bayes tab fit a Gaussian Naive Bayes classifier and inspect its confusion matrix
GLM tab fit an ordinary logistic regression model or a regularized glmnet classifier and inspect its confusion matrix
Tree tab fit either a conditional inference tree or a conditional random forest and inspect its confusion matrix
ROC tab overlay ROC curves for the fitted classifiers on the same plot
Regression tab fit an ordinary or regularized linear regression model with diagnostics for continuous outcomes
Training % slider control the share of data used for training (the rest is held out for testing)
Shuffle switch between keeping the original row order and shuffling before splitting
Laplace set the Laplace smoothing parameter for the Naive Bayes classifier

The app fits each model on the training rows and evaluates it on the held-out rows. This is a single holdout split — the simplest form of validation, discussed in detail in Chapter 160.

In this chapter the scope remains classification, so the discussion will concentrate on the Bayes, GLM, Tree, and ROC tabs. The Regression tab is still useful to explore later when the outcome is continuous, but it is not needed for the Pima example.

Interactive Shiny app (click to load).
Open in new tab

159.2 The Dataset: Pima.tr

The dataset used in this chapter is Pima.tr from the MASS package — a cleaned teaching subset of 200 female patients of Pima Indian heritage with no missing values. The full research dataset (PimaIndiansDiabetes2 from mlbench) contains additional observations and missing entries that require imputation before modeling. This chapter uses the clean subset so that the focus stays on the model building workflow rather than on data cleaning. The guided workflow in Section 163.5 also uses Pima.tr, so the manual and guided results can be compared directly.

data("Pima.tr", package = "MASS")

str(Pima.tr)
'data.frame':   200 obs. of  8 variables:
 $ npreg: int  5 7 5 0 0 5 3 1 3 2 ...
 $ glu  : int  86 195 77 165 107 97 83 193 142 128 ...
 $ bp   : int  68 70 82 76 60 76 58 50 80 78 ...
 $ skin : int  28 33 41 43 25 27 31 16 15 37 ...
 $ bmi  : num  30.2 25.1 35.8 47.9 26.4 35.6 34.3 25.9 32.4 43.3 ...
 $ ped  : num  0.364 0.163 0.156 0.259 0.133 ...
 $ age  : int  24 55 35 26 23 52 25 24 63 31 ...
 $ type : Factor w/ 2 levels "No","Yes": 1 2 1 1 1 2 1 1 1 2 ...
diabetes_share <- round(prop.table(table(Pima.tr$type)), 3)

knitr::kable(
  data.frame(class = names(diabetes_share), share = as.numeric(diabetes_share)),
  caption = "Outcome shares in Pima.tr"
)
Outcome shares in Pima.tr
class share
No 0.66
Yes 0.34

The outcome is unbalanced: roughly two thirds of the patients do not have diabetes. This matters for classification because a model that always predicts the majority class would already achieve about 66% accuracy without learning anything from the predictors.

159.3 Fitting a Naive Bayes Classifier

The Bayes tab in the app fits a Gaussian Naive Bayes classifier (see Chapter 21 for the full treatment). The model assumes that each predictor follows a normal distribution within each class and uses Bayes’ theorem to compute the posterior probability of each class for a new observation.

The output shows:

  • the prior probabilities for each class (based on the training data),
  • the class-conditional means and standard deviations for each predictor,
  • a confusion matrix on the held-out rows.

The confusion matrix (see Chapter 59) is the primary evaluation tool here. It shows how many held-out observations were correctly classified and how many were misclassified. From the confusion matrix you can read off the sensitivity and specificity (see Chapter 8): sensitivity measures how well the model detects positive cases (diabetes present), and specificity measures how well it identifies negative cases (diabetes absent).

159.4 Comparing with Logistic Regression

The GLM tab fits a logistic regression model (see Chapter 136) on the same training data with the same predictors. Logistic regression does not assume normally distributed predictors. Instead, it models the log-odds of the target as a linear function of the predictors.

Compare the confusion matrix from the GLM tab with the one from the Bayes tab. The two models may agree on most cases but differ on borderline observations. The confusion matrix lets you see exactly where they disagree: does one model miss more positive cases (lower sensitivity) while the other produces more false positives (lower specificity)?

The same tab now also exposes ridge, lasso, elastic net, and an automatic penalty-family search through glmnet (see Chapter 161). When you switch on regularization, the app does not silently refit in the background during every UI change. You explicitly launch the search with Fit regularized GLM, the fit runs asynchronously, and the app shows a progress/wait message if another heavy search is already using the compute slot.

159.5 Comparing with a Conditional Inference Tree

The Tree tab fits a conditional inference tree by default (see Chapter 140). Unlike the two previous models, the tree does not produce coefficients. It partitions the data into groups using a sequence of binary splits and assigns the majority class in each terminal node.

The tree has two distinctive properties:

  • it is directly interpretable as a decision diagram,
  • it automatically selects predictors and split points using permutation tests.

Compare its confusion matrix with the earlier two. A tree may produce higher specificity but lower sensitivity (or the reverse) depending on where the splits fall. The question is not which model is universally best but which model produces the most useful trade-off for the problem at hand.

The same Tree tab also includes a selector for cforest (see Chapter 142). That option replaces one interpretable tree by an ensemble of many trees. The forest is usually harder to explain as a single diagram, but it can produce better predictive performance. The app therefore lets you compare ctree and cforest directly inside the same tab before you move to the ROC comparison.

For binary targets, both the GLM tab and the Tree tab expose a threshold slider. The fitted model first produces a probability for the positive class; the threshold then converts that probability into a final yes/no classification. Lowering the threshold makes positive predictions easier to trigger, which typically increases sensitivity but may reduce specificity and precision.

159.6 Model Comparison with ROC Curves

The ROC tab overlays the ROC curves of the fitted classifiers on the same plot (see Chapter 60 for the full treatment of ROC analysis). The ROC curve traces sensitivity against the false positive rate as the classification threshold varies from 0 to 1.

The area under the ROC curve (AUC) summarizes discrimination: an AUC of 0.5 means the model is no better than random guessing, and an AUC of 1.0 means perfect separation. The ROC tab reports the AUC for each model, so you can compare their discriminative ability directly.

This comparison is more informative than comparing confusion matrices at a single threshold because the ROC curve shows how each model behaves across all possible thresholds.

159.7 The Effect of Training Percentage

The training percentage slider controls how much of the data is used for fitting and how much is held out for evaluation. Moving the slider from 0.6 to 0.95 changes the balance between two competing concerns:

  • more training data generally produces a better-fitted model,
  • less held-out data produces a noisier estimate of held-out performance.
library(naivebayes)
naivebayes 1.0.0 loaded
For more information please visit: 
https://majkamichal.github.io/naivebayes/
set.seed(42)
train_percs <- c(0.5, 0.6, 0.7, 0.8, 0.9)
accuracies <- numeric(length(train_percs))

for (i in seq_along(train_percs)) {
  n <- nrow(Pima.tr)
  idx <- sample(seq_len(n), size = floor(train_percs[i] * n))
  train_data <- Pima.tr[idx, ]
  test_data <- Pima.tr[-idx, ]

  nb_fit <- naive_bayes(type ~ ., data = train_data)
  test_x <- subset(test_data, select = -type)
  preds <- predict(nb_fit, newdata = test_x)
  accuracies[i] <- mean(preds == test_data$type)
}

barplot(
  accuracies,
  names.arg = train_percs,
  xlab = "Training percentage",
  ylab = "Held-out accuracy",
  ylim = c(0, 1),
  col = "steelblue",
  border = NA
)
abline(h = mean(accuracies), lty = 2, col = "grey40")

Naive Bayes accuracy at different training percentages on Pima.tr

Each bar represents a single random split. If you run this code again with a different seed, the bars will change — sometimes substantially. That instability is exactly the problem that repeated holdout (Section 160.3) is designed to address.

159.8 The Effect of Shuffling

The shuffle option in the app controls whether the rows are randomized before the training/test split is made. If the data happen to be sorted by the target variable (or by any variable correlated with the target), a non-shuffled split can assign most of one class to training and most of the other class to testing. The result is a split that does not represent the population.

sorted_pima <- Pima.tr[order(Pima.tr$type), ]

n <- nrow(sorted_pima)
idx_no_shuffle <- seq_len(floor(0.8 * n))

cat("Class distribution in test set without shuffling:\n")
Class distribution in test set without shuffling:
print(table(sorted_pima[-idx_no_shuffle, "type"]))

 No Yes 
  0  40 
set.seed(99)
idx_shuffled <- sample(seq_len(n), size = floor(0.8 * n))

cat("\nClass distribution in test set with shuffling:\n")

Class distribution in test set with shuffling:
print(table(sorted_pima[-idx_shuffled, "type"]))

 No Yes 
 23  17 

The non-shuffled split assigns almost all positive cases to the test set (because they were sorted to the end). The shuffled split preserves the original class balance approximately. Stratified holdout (Section 160.4) goes one step further: it guarantees that the class proportions in training and test are as close to the population proportions as possible.

This is also one of the important differences between the manual and guided workflows. The manual app uses a simple sequential split unless you turn on shuffling yourself. The guided app, by contrast, automatically uses shuffled repeated holdout for tabular regression and stratified shuffled repeated holdout for tabular classification. So if you compare the same dataset across the two apps, different validation results can arise simply because the splitting discipline is stronger in the guided workflow.

159.9 Practical Exercises

  1. Open the app with the Pima dataset and remove glu (glucose) from the predictor set. How does the confusion matrix change for each of the three models? Which model is most affected by losing that predictor?
  2. Set the training percentage to 0.6 and record the accuracy for all three models. Then set it to 0.9 and record the accuracy again. Does the ranking of models change?
  3. Compare the ROC curves at 0.7 and 0.9 training percentage. Which model shows the most stable AUC?
  4. Using the confusion matrix from the Bayes tab, compute the sensitivity and specificity by hand and verify that your values match the app output.
  5. After completing this chapter, open the guided Pima session in Section 163.5 and compare the models available there with the three models you used here. What does the guided workflow add that the manual workflow does not provide?
158  Introduction to Model Building Strategies
160  Model Validation

© 2026 Patrick Wessa. Provided as-is, without warranty.

Feedback: e-mail | Anonymous contributions: click to copy (Sats) | click to copy (XMR)

Cookie Preferences