Machine Learning Classification for Beginners: Logistic Regression, Decision Trees and Random Forests

Imagine you are studying a collection of Iris flowers. Each flower has four measurements: the lengths and widths of its sepals and petals. A botanist has already labelled 150 examples as setosa, versicolor or virginica. Could you teach a computer to use those measurements to identify the species of a new flower? More importantly, could you show that the model works on flowers it never saw during training? This is a practical introduction to machine learning classification, with three algorithms, carefully separated training and testing, and evidence from real Scikit-Learn calculations.

You will implement Logistic Regression, a Decision Tree and a Random Forest using Python, compare them against a simple most-frequent-class baseline, select a model through stratified five-fold cross-validation and interpret its held-out errors. You will also learn why high accuracy is not sufficient evidence of trustworthiness. The lesson develops binary and multiclass confusion matrices, precision, recall, specificity, macro F1, class imbalance, threshold decisions, ROC and precision–recall curves, and the importance of honest model limitations. By the end, you can reproduce a complete student portfolio project rather than only memorizing commands.

Verified-run disclosure, 25 November 2026: Python 3.13.5, Scikit-Learn 1.8.0, Pandas 2.2.3 and NumPy 2.3.5 were used to execute the real built-in Iris dataset. There are 150 observations, four numeric features, three classes with 50 samples each, and no missing feature cells. With random state 87, an 80/20 stratified split produced 120 training and 30 test records; the training-only model comparison selected Logistic Regression. Its held-out accuracy was 28/30 (93.33%). The separate 100-case binary confusion matrix is entirely fictional classroom arithmetic, not an Iris evaluation.

Figure 1. A repeatable classification process: question, data, stratified split, baseline, cross-validation, held-out test and report.
Figure 1. A repeatable classification process: question, data, stratified split, baseline, cross-validation, held-out test and report.

What is classification in supervised machine learning?

Classification is a type of supervised learning in which an algorithm learns from examples containing both measurements (features) and known categories (target labels). During fitting, the classifier identifies statistical patterns that help distinguish the classes. After training, it predicts a class label for an observation whose answer was not supplied to it. This is different from unsupervised clustering, which looks for groups without predefined target labels. A class code such as 2 is simply an identifier for “virginica,” not a continuous numerical measurement equal to twice class 1.

For Iris, the feature matrix X has four columns per flower—sepal length, sepal width, petal length and petal width, all in centimetres—and the target vector y identifies the actual species. Including the known species label in X would reveal the answer to the algorithm and create target leakage. Other classification examples include recognizing handwritten digits, sorting support tickets or categorizing documents. But a successful Iris demonstration cannot be reused unvalidated for medical, admissions or other consequential decisions.

Classification versus regression

The difference begins with the research question. Classification predicts a category, such as “versicolor”; regression predicts a numerical value, such as 14.5 assessment points. Classification measures include confusion matrices, accuracy, precision, recall and F1. Numerical regression commonly uses MAE, RMSE or R². Despite its name, Logistic Regression is a classifier: it uses a linear predictor within a probability-based classification model rather than ordinary linear regression’s unrestricted numeric outcome. Topic 86’s Student Grade Prediction Project provides a full regression example if you want to compare the workflows.

Figure 2. Regression estimates a quantity, while classification identifies one of predefined classes.
Figure 2. Regression estimates a quantity, while classification identifies one of predefined classes.
QuestionClassificationRegression
What does it predict?A class labelA numerical quantity
Iris exampleFlower speciesEstimated petal length
Typical modelsLogistic Regression, Tree, ForestClassifierLinear/Ridge, TreeRegressor, ForestRegressor
Common evaluationMacro F1, accuracy, confusion matrixMAE, RMSE and R²
Typical interpretationWhich classes are confused?How large are numeric prediction errors?

Binary, multiclass and multilabel classification

Binary classification predicts one of two categories: for example, “virginica” or “not virginica.” In that task we explicitly code the positive class as 1 for virginica and the negative class as 0 for either other species. Multiclass classification chooses exactly one label from at least three alternatives: setosa, versicolor and virginica. This is our main Iris project. Multilabel classification differs again because a single observation may have multiple labels simultaneously—such as an article tagged both “statistics” and “Python.” Do not apply binary confusion-matrix denominators to the full three-class problem without specifying a one-versus-rest interpretation.

Figure 3. Binary and multiclass classifications answer different label-selection questions.
Figure 3. Binary and multiclass classifications answer different label-selection questions.

Why the Iris dataset is an effective first project

Scikit-Learn’s built-in Iris loader makes the same documented examples available without using an outside API or collecting student information. The dataset contains 150 real historical flower observations, four measurements and three target species. The benchmark’s source documentation records its research provenance, including the classic Iris analysis associated with Ronald Fisher; data are available inside Scikit-Learn for teaching and reproducible evaluation. The data contain 50 instances of each class, so each species occupies about 33.33% of the dataset. This is balanced by count, not automatically representative of all flowers in nature.

The four variables describe an individual flower’s sepal and petal lengths and widths in centimetres. A simple two-dimensional petal plot can reveal strong separation between some classes, but the classifier considers all four measurements. Other real classification datasets may contain missing fields, imbalanced labels, unreliable measurements or cases from populations absent at training. The simplicity of Iris makes it accessible for understanding methods; it does not establish that the same 93% test accuracy will occur for flowers recorded by other devices, at other sites or for species not represented in the three training labels.

Figure 4. Verified Iris class counts: 50 setosa, 50 versicolor and 50 virginica.
Figure 4. Verified Iris class counts: 50 setosa, 50 versicolor and 50 virginica.

Set up the Python environment and inspect the data

A Jupyter Notebook, VS Code or Google Colab environment can run this project if it includes compatible NumPy, Pandas, Scikit-Learn and Matplotlib packages. Use a virtual environment where practical, and record software versions because model interfaces and numeric results can change between versions. Our package includes the actual executed notebook and a separate Python source file. After loading the dataset with as_frame=True, inspect its dimensions, descriptive statistics, class counts, missing values and feature names before fitting anything. An observed result of no missing cells is a check on this installed Iris copy, not permission to assume that all datasets are complete.

python -m pip install numpy pandas scikit-learn matplotlib jupyter

from sklearn.datasets import load_iris
iris = load_iris(as_frame=True)
X = iris.data.copy()      # 150 rows x 4 features
y = iris.target.copy()    # 150 class labels
print(X.shape, y.value_counts().sort_index())
print(X.isna().sum())
print(X.describe())
Figure 5. Actual Iris petal measurements in centimetres, plotted by observed species.
Figure 5. Actual Iris petal measurements in centimetres, plotted by observed species.

Inspect plots and distributions rather than concluding that a particular feature “causes” a flower’s species merely because it helps separate the classes. The feature measurements are observable characteristics associated with botanically identified labels, and overlapping regions mean that some labels may still be confused. Always give figures descriptive titles, axis units and species legends; never put an attractive plot ahead of the research question. The rest of the project keeps the original data labels separate and compares models on identical training and test partitions.

Separate training from testing with stratification

A model should be tested on observations it did not use for fitting or candidate selection. We reserve 20% of Iris for final testing, leaving 80% for fitting and cross-validation. Because the dataset is balanced, a stratified split produces 40 training and ten held-out observations per class, or 120 training and 30 test records total. The documented seed 87 makes the exact partition reproducible for this run. Never compute a scaler from all 150 rows before the split: the means and standard deviations of held-out observations would influence model preprocessing and contaminate evaluation.

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=.20, stratify=y, random_state=87
)
print(len(X_train),len(X_test)) # 120, 30
print(y_train.value_counts().sort_index()) # [40, 40, 40]
print(y_test.value_counts().sort_index())  # [10, 10, 10]

Stratification preserves class proportions as closely as possible, helping avoid a test set with no examples of a rare class. It does not eliminate all statistical uncertainty or guarantee a representative sample. If observations come from repeated people, events grouped by source, or a chronological forecasting task, grouped or time-aware validation may be more suitable than a random stratified split. For the Iris teaching exercise, we compare four fixed candidates under one consistent training partition and reserve the last 30 records for final evaluation only.

Establish a baseline classifier

DummyClassifier(strategy="most_frequent") predicts the same class—the one most frequent in the training set—without learning useful distinctions between petal and sepal measurements. Our stratified Iris training data contain a three-way tie; Scikit-Learn’s fitted baseline predicts one consistent class for all observations. On the balanced test set, that happens to be correct for ten of the 30 flowers, yielding 33.33% accuracy. Its macro F1 is only 0.1667 because it fails to identify the other two species. This shows why baseline reporting and per-class metrics add essential context.

Logistic Regression: linear scores and class probabilities

Despite the name, Logistic Regression is primarily used to classify observations. For a binary task it forms a linear score, usually called z, from a weighted combination of features, then transforms that score through the sigmoid function: σ(z)=1/(1+e−z). When z=0, σ(z)=0.5; positive scores give larger estimated probabilities, and negative scores smaller ones. A decision threshold turns a continuous estimated probability into a class choice. These outputs are model estimates and should not automatically be interpreted as perfectly calibrated real-world frequencies.

Figure 6. Mathematically correct sigmoid curve, with 0.5 at z=0.
Figure 6. Mathematically correct sigmoid curve, with 0.5 at z=0.

Iris has three classes rather than two. Modern Scikit-Learn Logistic Regression with an appropriate solver such as lbfgs fits multinomial class scores and uses softmax to form a probability distribution summing to one. For example, an illustrative output (not from a particular measured flower) might be setosa 0.10, versicolor 0.75 and virginica 0.15. The predicted label is versicolor, the class with the largest score. Logistic Regression’s relatively simple structure is useful for learning probabilistic classification, but nonlinear class boundaries may require feature engineering or another model.

Standardization often helps regularized linear models by putting differently scaled measurements on more comparable scales. Use a Pipeline so StandardScaler is fitted only on the training fold during cross-validation, then applied to that fold’s validation observations. This prevents the held-out partition from contributing its statistics. Logistic coefficients depend on feature coding, units and correlations and should not be advertised as causal explanations of botanical differences. Probability calibration also requires a separate check, even if class prediction is accurate.

Decision Trees: readable branching rules

A Decision Tree classifier recursively partitions measurements using rules such as whether petal length is below a particular learned threshold. The initial node is the root; internal nodes contain split conditions, branches represent possible outcomes and terminal leaves assign class predictions or class-probability estimates based on training labels in those leaves. Unlike a standard linear decision surface, trees can capture nonlinear boundaries without a separate feature-scaling step. A single tree can be relatively easy to visualize, but complex trees may fit accidental patterns in the training data and perform poorly on new observations.

Tree algorithms evaluate candidate splits using an impurity measure. Gini impurity=1−Σpᵢ², where pᵢ is a class proportion in a node. In a fictional two-class node containing six A and four B records, Gini=1−(0.6²+0.4²)=0.48; a perfectly homogeneous node has Gini zero. The tree compares the weighted impurity of child nodes, not the smallest isolated child’s score. Students should understand this as a class-mixing measure, not an equation for the probability that a real flower belongs to a class.

Figure 7. Actual Decision Tree fitted on the 120-record Iris training set with maximum depth three.
Figure 7. Actual Decision Tree fitted on the 120-record Iris training set with maximum depth three.

Our fitted-tree figure uses actual training observations and documented feature names. Each node displays a learned threshold and class distribution. Settings such as max_depth, min_samples_leaf and pruning constrain complexity. A deeper tree may reduce training error but need not improve cross-validation performance; the relationship involves bias and variance. For more detail on interpreting nodes and pruning, the already-published Decision Tree Python tutorial extends this material.

Random Forest: combine many randomized trees

A Random Forest is an ensemble of decision trees trained with randomization. Typically, bootstrap sampling changes which observations each tree sees, while randomized feature consideration changes the candidate splits. The collection thereby learns diverse models rather than repeating one identical tree. For classification, Scikit-Learn aggregates class-probability estimates across trees and selects the class with the largest averaged probability. Forests can reduce some variance compared with a single unrestricted tree, but they use more memory and computational work, can still overfit and are less transparent than one small tree.

Figure 8. Conceptual Random Forest: independently randomized trees contribute to an aggregated prediction.
Figure 8. Conceptual Random Forest: independently randomized trees contribute to an aggregated prediction.

Important forest parameters include n_estimators (number of trees), max_depth (depth limit), min_samples_leaf (minimum terminal-node size), max_features (number of candidate features per split) and class_weight where class imbalance calls for scrutiny. Increasing tree count usually increases computational cost and does not guarantee more meaningful test accuracy. In our fixed teaching comparison, the forest uses 200 trees with a minimum of two samples per leaf; all candidates are judged using the same stratified folds.

Compare the three algorithms conceptually

CriterionLogistic RegressionDecision TreeRandom Forest
MechanismLinear scores and softmaxRecursive if/then rulesEnsemble of randomized trees
Nonlinear patternsOften needs feature engineeringCan learn directlyCan learn directly
ScalingOften usefulUsually unnecessaryUsually unnecessary
InterpretabilityCoefficients with caveatsIndividual branching rulesMore complex ensemble
Main riskUnderfitting or miscalibrationOverfitting if deepStill can overfit
Typical computationRelatively efficientRelatively efficientHigher ensemble cost

Complete training-only comparison with Python

The following runnable code is the core of the accompanying executed notebook. It instantiates the baseline and three classifiers with fixed hyperparameters, uses five StratifiedKFold training folds with shuffle and random seed 87, and compares candidates by macro-averaged F1. Macro F1 computes F1 independently for each species and then averages the three values with equal weight. It is a meaningful teaching selection metric even in the balanced Iris data because it penalizes uneven per-class recognition; it is not universally the right measure for other error costs or highly imbalanced applications.

from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.base import clone

models = {
    "Baseline": DummyClassifier(strategy="most_frequent"),
    "Logistic Regression": make_pipeline(StandardScaler(),
        LogisticRegression(solver="lbfgs",max_iter=2000)),
    "Decision Tree": DecisionTreeClassifier(max_depth=3,random_state=87),
    "Random Forest": RandomForestClassifier(n_estimators=200,
                       min_samples_leaf=2,random_state=87),
}
cv = StratifiedKFold(n_splits=5,shuffle=True,random_state=87)
cv_results = {name:cross_val_score(model,X_train,y_train,
    cv=cv,scoring="f1_macro") for name,model in models.items()}
for name,score in cv_results.items():
    print(name,round(score.mean(),4))
choices = ["Logistic Regression","Decision Tree","Random Forest"]
best_name=max(choices,key=lambda name:cv_results[name].mean())
best_model=clone(models[best_name]).fit(X_train,y_train)
baseline=clone(models["Baseline"]).fit(X_train,y_train)

Placing StandardScaler inside the Logistic Regression Pipeline means each cross-validation training fold fits its own scaling parameters without peeking at the corresponding validation fold. Trees generally do not need feature scaling because they learn threshold splits on individual measurements. The baseline uses the same data partition so it can be compared fairly later. Do not select a model based on its final held-out score and then claim that the test result is an unbiased estimate of model selection: the final test should not decide which candidate wins.

Actual five-fold cross-validation results

ModelMean TRAINING CV macro F1Role
Dummy baseline0.1667Reference, not candidate
Logistic Regression0.9580Selected by highest CV macro F1
Decision Tree0.9414Alternative candidate
Random Forest0.9496Alternative candidate
Figure 9. Measured training-only five-fold macro F1 for baseline and candidate Iris classifiers.
Figure 9. Measured training-only five-fold macro F1 for baseline and candidate Iris classifiers.

The exact means from this run were 0.958036 for Logistic Regression, 0.941438 for Decision Tree and 0.949605 for Random Forest. The training-only baseline achieved 0.166667. Logistic Regression won under the stated rule, but the scores are close and the training sample is small. The result does not establish a statistically significant universal ranking or imply that one algorithm should always be used. A different split, seed, hyperparameter policy, measured feature set or application-specific loss function could lead to another selection.

Final held-out test results: interpret rather than exaggerate

After selection, Logistic Regression was refitted on all 120 training records and evaluated once on the untouched 30-record test set. The baseline predicted one species for every test flower, obtaining 10/30=33.33% accuracy. The selected classifier got 28/30=93.33% accuracy, with macro F1=0.9333 and balanced accuracy=0.9333. Balanced accuracy for the three-class task is the average recall of the three labels. These numbers reflect one reproducible test partition; they do not by themselves measure probability calibration, generalization to unknown species or future deployment safety.

from sklearn.metrics import (accuracy_score,balanced_accuracy_score,
    f1_score,confusion_matrix,classification_report)

y_pred=best_model.predict(X_test)
y_base=baseline.predict(X_test)
for label,pred in [("Baseline",y_base),("Selected",y_pred)]:
    print(label,"accuracy",accuracy_score(y_test,pred),
          "macro F1",f1_score(y_test,pred,average="macro"),
          "balanced accuracy",balanced_accuracy_score(y_test,pred))
print(confusion_matrix(y_test,y_pred,labels=[0,1,2]))
print(classification_report(y_test,y_pred,
      target_names=iris.target_names,zero_division=0))

Read the real three-class confusion matrix

A multiclass confusion matrix has actual labels along rows and predicted labels along columns in our convention. Diagonal entries are correctly classified examples; off-diagonal entries reveal which classes were confused. In the measured held-out matrix, all ten setosa observations were identified correctly. Nine versicolor were correctly labelled, with one mistaken for virginica; nine virginica were correctly labelled, with one mistaken for versicolor. This is 28 correct out of 30. The two errors are not cosmetic: they illustrate why a headline accuracy percentage cannot tell you which class distinctions remain difficult.

Figure 10. Actual held-out Iris test confusion matrix for the selected Logistic Regression; 28/30 correct.
Figure 10. Actual held-out Iris test confusion matrix for the selected Logistic Regression; 28/30 correct.
Actual speciesPred. setosaPred. versicolorPred. virginicaRecall
Setosa1000100%
Versicolor09190%
Virginica01990%

Per-class precision happens to be 100%, 90% and 90% in this small test, matching the respective recalls because each predicted-class total equals the corresponding true-class total. Macro F1 averages the three class F1 values—1.0, 0.9, 0.9—to obtain approximately 0.9333. This numerical coincidence between accuracy, macro F1 and balanced accuracy is a property of this particular confusion matrix, not a general identity for every multiclass model.

Binary confusion matrix: one carefully defined positive class

A binary confusion matrix distinguishes True Positive (TP), False Positive (FP), False Negative (FN) and True Negative (TN). Always state which class counts as positive and whether matrix rows or columns contain the actual values. The separate classroom exercise below deliberately uses 100 invented cases: TP=24, FP=6, FN=8 and TN=62. Its total is 100; 32 are actual positives and 68 actual negatives. The arithmetic example is unrelated to the real Iris classifier, allowing students to practise formulas without mistaking constructed values for measured model predictions.

Figure 11. Fictional 100-case binary confusion matrix for arithmetic instruction; NOT Iris test output.
Figure 11. Fictional 100-case binary confusion matrix for arithmetic instruction; NOT Iris test output.

Calculate accuracy, precision, recall, specificity and F1

For the fictional binary matrix, accuracy=(TP+TN)/N=(24+62)/100=86%. Accuracy answers how many observations were classified correctly overall. Precision=TP/(TP+FP)=24/30=80% answers how many predicted positives were truly positive; it matters when a false alarm is costly. Recall=TP/(TP+FN)=24/32=75%, also called sensitivity, answers how many actual positives were found; it matters when missing a positive case is costly. Neither precision nor recall describes every possible error consequence.

Specificity=TN/(TN+FP)=62/68≈91.18% measures how well actual negatives were correctly recognized. F1=2×precision×recall/(precision+recall)=0.7742≈77.42% is the harmonic mean of precision and recall; it does not explicitly include TN. Balanced accuracy=(recall+specificity)/2≈83.09% summarizes the two class recall rates with equal weight. False positive rate=FP/(FP+TN)=6/68≈8.82%. Metric calculations need special conventions when denominators are zero; Scikit-Learn lets you explicitly select a zero-division policy, rather than pretending an undefined ratio was measured normally.

MetricFictional 100-case resultInterpretation
Accuracy86.00%86 cases correctly classified
Precision80.00%Four of five predicted positives are correct
Recall / sensitivity75.00%Three of four actual positives found
Specificity91.18%Most actual negatives correctly rejected
F177.42%Balance of positive precision and recall
Balanced accuracy83.09%Average positive and negative recall
False positive rate8.82%Share of negatives predicted positive

Macro, weighted and micro classification averages

In multiclass classification, metrics must be aggregated using a clearly named method. For macro averaging, compute each class’s precision, recall or F1 in a one-versus-rest view, then take their ordinary arithmetic mean, giving every species equal weight. A weighted average uses the number of actual records belonging to each class as weights. Micro averaging first adds the relevant class decisions, then calculates the metric; for single-label multiclass tasks when all classes are included, micro precision, recall and F1 are numerically equal to accuracy. Macro F1 is the mean of the three separate F1 values and is not, in general, the F1 obtained by inserting macro precision and macro recall into the binary harmonic-mean formula.

Why high accuracy can hide class imbalance

Imagine an entirely fictional dataset of 100 observations: 95 negatives and five positives. A classifier that predicts negative for everyone obtains 95% accuracy but finds none of the five positives. Its positive-class recall is zero. This is why understanding class support, macro scores, recall, precision and the consequences of each kind of error matters. For genuinely imbalanced problems, stratified splits, class weights, an appropriate evaluation metric, better data collection or carefully controlled resampling may be useful. If oversampling is attempted, perform it inside training folds, not before the split, so copies or generated observations do not contaminate validation. Iris itself is evenly distributed by class count.

Probability thresholds change decisions, not the underlying scores

Binary classifiers often produce an estimated positive-class probability. Consider the fictional value P(positive)=0.70. At threshold 0.50, it becomes positive; at threshold 0.80, negative. The score is unchanged, but the decision rule has changed. Across multiple observations, lowering a threshold typically identifies more positives while increasing some false alarms; raising it can reduce false alarms while missing additional actual positives. A useful threshold must reflect an explicit cost or policy and be selected using appropriate training/validation evidence rather than optimized repeatedly on the final test set.

For the separate real-data extension, we define the positive class as virginica and the negative class as the other two Iris species. Using the same seed 87 but a new stratified binary 80/20 split, a scaled Logistic Regression model produces positive-class probabilities for thirty held-out flowers. Its predictions at threshold 0.50 yield TN=19, FP=1, FN=2 and TP=8: accuracy 90%, precision about 88.89%, recall 80% and specificity 95%. These are real results from the binary extension, not the selected three-class model and not the fictional 100-case arithmetic.

from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix,roc_auc_score,average_precision_score

binary_target=(iris.target==2).astype(int)   # virginica=1
Xbt,Xbe,ybt,ybe=train_test_split(X,binary_target,
     test_size=.2,stratify=binary_target,random_state=87)
binary_model=make_pipeline(StandardScaler(),
     LogisticRegression(solver="lbfgs",max_iter=2000)).fit(Xbt,ybt)
positive_col=list(binary_model.classes_).index(1)
score=binary_model.predict_proba(Xbe)[:,positive_col]
labels=(score>=0.5).astype(int)
print(confusion_matrix(ybe,labels,labels=[0,1]))
print("ROC AUC:",roc_auc_score(ybe,score))
print("Average precision:",average_precision_score(ybe,score))
Figure 12. Different thresholds change observed precision and recall on the real held-out binary Iris extension; this graph is diagnostic, not a test-set threshold-selection policy.
Figure 12. Different thresholds change observed precision and recall on the real held-out binary Iris extension; this graph is diagnostic, not a test-set threshold-selection policy.

ROC curves and precision–recall curves

A Receiver Operating Characteristic (ROC) curve plots the true-positive rate (recall) against the false-positive rate at many thresholds, not just the default 0.50. ROC-AUC summarizes ranking discrimination and is not the percentage of correctly classified observations. Using the actual held-out scores from our binary Iris extension gives ROC-AUC=0.985. This describes how that binary model ranked the sample, not perfect calibration or assured future accuracy. A single confusion matrix has only one threshold operating point; it cannot reconstruct a full ROC curve.

Figure 13. Actual ROC curve from held-out positive-class probability scores for virginica vs other Iris; ROC-AUC 0.985.
Figure 13. Actual ROC curve from held-out positive-class probability scores for virginica vs other Iris; ROC-AUC 0.985.

A precision–recall curve plots precision against recall as the score threshold varies. It can be especially informative when the positive class is rare because precision depends strongly on the positive class’s prevalence. Average precision summarizes the PR curve differently from ROC-AUC, so the two statistics should not be compared as if they represent the same quantity. The actual binary Iris extension yielded average precision≈0.9733 on its 30 held-out observations; that high number is a small benchmark result, not a universal operational guarantee.

Figure 14. Actual precision–recall curve from held-out virginica probability scores; average precision approximately 0.9733.
Figure 14. Actual precision–recall curve from held-out virginica probability scores; average precision approximately 0.9733.

Probability calibration, overfitting and uncertainty

A model can classify the correct species frequently but produce estimated probabilities that are poorly calibrated. Calibration concerns whether observations assigned scores near 0.70 are positive about 70% of the time under suitable data and grouping conditions. Logistic Regression, single trees and forests do not automatically provide perfect calibrated probabilities. A reliability diagram compares predicted probability groups with observed frequencies; calibration methods must be fitted on training/validation data, then assessed on untouched observations. On a dataset as small as Iris, calibration curves are themselves noisy, so use them educationally rather than to assert high-precision probability reliability.

Overfitting means capturing training-specific noise that generalizes poorly; underfitting means the model is insufficiently flexible or fails to learn the useful structure. A shallow linear model may miss complex nonlinear interactions, while a very deep unpruned tree can create fragile splits. A forest can reduce some single-tree variability but is not immune to error. Compare training and validation behaviour and investigate fold variability. If tuning tree depth, Logistic Regression regularization C or forest leaf size, search candidates using training-only cross-validation and preserve the held-out test for the final report. More trees, parameters or depth do not automatically improve generalization.

Feature importance, dataset shift and responsible classification

Logistic Regression coefficients describe the fitted class-score model under a particular scaling and feature representation. A small Decision Tree exposes human-readable thresholds; a Random Forest may supply impurity-based importance summaries. However, correlated features and different importance methods complicate interpretation, and importance is not proof of causality. Permutation importance on appropriate validation data can help measure model reliance, but it too depends on the evaluation setup. The Iris project is a compact historical benchmark. A model expecting four numerical measurements cannot directly classify arbitrary flower photographs or recognize unknown species; it may confidently assign an unfamiliar input to one of its known classes.

Figure 15. Responsible use requires data quality, error-cost awareness, calibrated probabilities where needed and human oversight.
Figure 15. Responsible use requires data quality, error-cost awareness, calibrated probabilities where needed and human oversight.

A wrong flower label usually has different consequences from a false medical diagnosis, finance decision or educational admission outcome. In real classification systems, false positives and false negatives may affect people unequally, data may omit groups, and predictions may be exposed to sensitive personal information. Ethical development requires provenance, privacy, transparent testing, domain expertise, external validation, meaningful human oversight and safeguards against discriminatory outcomes. Students should not deploy their unvalidated classroom classifier for high-stakes decisions, regardless of a strong Iris benchmark score. Also avoid loading untrusted serialized Python model files, which can execute malicious code during deserialization.

Why model selection must be separated from the final test

Even a correctly executed model can become misleading if the test set is repeatedly consulted. Our selection used mean macro F1 over five training-only stratified folds. Each validation fold was excluded from fitting that fold’s candidate estimator, including its scaling. Only after selecting Logistic Regression did we fit it to the full 120 training observations and report the held-out 30-flower matrix. If students later change C, tree depth, features or class thresholds because they dislike the final test, they have effectively started tuning against that test; an independent new test would then be required for an unbiased final evaluation. The goal is not the most flattering metric but a reproducible and honest measurement.

Classical stratified folds suit this compact independent-observation teaching benchmark, but some datasets require more careful splitting. Repeated measurements of the same person, location or device may need group-level separation; time-dependent observations may need chronological validation; rare target classes may require specialized metrics and collection strategies. Model selection must be defined in relation to the intended new observations, not merely the availability of a convenient function. If a validation fold contains only a few minority examples, reported precision, recall or F1 can be unstable or undefined. Disclose the sample support and any zero-division convention.

Saving and reproducing the complete project

Reproducibility requires more than saving a screenshot of an accuracy number. Record the exact Iris loader and its provenance, feature names, class mapping, software versions, random seed 87, split proportions, model hyperparameters, stratification rules, CV folds, selected scoring metric, and full final classification report. The companion notebook executed eight Python cells successfully; a source script exports the actual test predictions and result summary to CSV and JSON. Other students can re-run the pipeline and check the coordinates of confusion-matrix figures rather than trusting an invented chart. A fitted object serialized using pickle or joblib should only be loaded from a trusted source, and compatibility with the original library environment matters.

The original loader makes this project accessible without third-party credentials or private school records. However, the scientific limits remain visible: four numerical measurements do not represent flower images, and three labels do not exhaust the world’s biological species. An unknown species may still be forced into one of the trained labels. Predictions can also change with measurement errors, collection procedures, new environments or distribution shift. When learning from an algorithm, distinguish a successful benchmark classification from a validated research conclusion about botany or a production-grade recognition system.

Common classification mistakes and how to avoid them

The compact reference table below gathers 45 practical mistakes. Each correction is tied to a reason; it is not a recommendation to apply every technique automatically. Treat the table as an audit companion to the full Data Quality, Model Evaluation, Decision Tree and AI Bias lessons, which are linked below. Wide tables scroll inside their own boundaries on mobile instead of making the entire article overflow.

Incorrect practiceWhy problematicBetter approachExample
Confusing tasksMisstates targetDefine category vs numberSpecies vs petal length
Selecting model before targetWrong objectiveName class outcomesIris three labels
Leaking y into XImpossible performanceExclude targetSpecies not in measurements
Ignoring class mappingMisreads predictionsPrint target_names0 means setosa
Calling multiclass multilabelWrong metric setupDefine one label per flowerIris has one species
Skipping class countsConceals imbalanceTabulate support50 per species
Training on all 150No unbiased evaluationReserve 30 held out80/20 split
Testing on trainingOptimistic errorUse unseen rowsHoldout
No stratificationMay omit a classUse stratify=y40 train per class
Scaling before splitEvaluation leakagePipeline fit in foldsStandardScaler
Scaling test separatelyIncompatible unitsTransform with trained scalerLR Pipeline
No baselineNo meaningful referenceDummyClassifierMost frequent
Logistic called regression targetMisreads outputExplain softmax labelsSpecies
Confusing score with labelThreshold overlookedSeparate predict_probaBinary 0.70
Assuming perfect calibrationConfidence misleadingAssess calibration0.7 frequency check
Deprecated multinomial settingVersion breakCurrent solver APIlbfgs
Unrestricted treeOverfit riskValidate depthmax_depth=3
Deeper always betterTraining focusCompare CVFold errors
Forest always winsNo universal rankingSelect by CVLR selected here
No hyperparameter recordIrreproducibleLog settingsForest 200 trees
Tuning on test setTest contaminationUse training CVC / max_depth
Calling CV a test scoreMisreports evaluationLabel stageCV .958 vs test .933
Accuracy onlyHides subgroup failureAdd macro F195/5 example
Precision vs recall mixedWrong denominatorLabel TP+FP vs TP+FN24/30 vs 24/32
Specificity vs precisionWrong negativesTN/(TN+FP)62/68
F1 called accuracyDifferent summariesExplain harmonic mean77.42% vs 86%
Macro vs weighted mixedHides rare classesName averagingEqual vs support
Undefined positive classAmbiguous matrixState positive=1Virginica binary
Reversed matrix axesWrong FP/FNLabel rows actual24,6,8,62
Fixed 0.5 always optimalIgnores error costsValidate threshold0.70 score
Test-tuned thresholdOptimistic outcomeSelect on validationNot held-out test
ROC-AUC called precisionDifferent meaningUse correct curvesRanking vs PPV
Importance called causeCausal overclaimDescribe model reliancePetal features
Correlated features ignoredUnstable rankingExplain correlationPetal dimensions
Ignoring calibrationProbability misreadCheck reliability0.7 predictions
Ignoring dataset shiftFails off-sampleExternal testsDifferent instruments
Assuming Iris universalOvergeneralizationDescribe benchmark150 flowers
Inventing performanceScientific deceptionRun real code28/30 actual
Inventing confusion matrixMisleading visualUse y_test, predictions3×3 observed
Ignoring uncertaintyOverconfidenceReport support30 test flowers
Loading unknown pickleSecurity riskTrusted artifacts onlyNo unknown joblib
High-stakes deploymentPotential harmDomain validationNo clinical decisions
Ignoring privacy/fairnessUnequal harmsReview governanceNo private labels
No seeds or versionsNot reproducibleRecord environmentSeed 87
Unexecuted code claimed testedFalse verificationRun and inspect notebook8 executed cells

A practical four-week classification learning roadmap

WeekCore topicsDeliverable
1Supervised learning, features, labels, binary/multiclass, Iris inspection150×4 dataset profile and class scatter plot
2Baseline, Logistic Regression, tree/forest, stratified splitThree candidate Pipelines and checked split
3CV, confusion matrix, precision, recall, thresholds and ROC/PRReal test report plus synthetic metric worksheet
4Capstone, model card, 30 practice questions, responsible AIReproducible notebook and research report

Beginner learners can spend extra time on one topic before moving to the next. The most useful milestone is being able to explain why a model was selected, not simply to run a script with no errors. Students with prior Python experience can focus on class-specific error consequences, probability calibration, validation uncertainty and interpreting different score summaries. As a final audit, confirm five things: correct dataset and labels; no target or preprocessing leakage; a simple baseline; training-only selection followed by a final held-out test; and an ethical explanation of how the model should and should not be used.

Ten-task capstone: Classifying Iris Flowers with Three Algorithms

Each task below asks learners to provide an objective, the Python method, authentic evidence, a defensible interpretation, a common mistake and a short extension. The executable notebook and PDF capstone are designed for individual work or a guided classroom. Use the real built-in Iris data for model results, while keeping the separate 100-case binary matrix solely for manual arithmetic. No task requires collecting personal information or publishing untrusted datasets. Do not copy the provided results without independently reproducing the notebook in your own compatible environment.

Capstone 1 — Define the classification task

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Identify three species, four cm-valued features and one target; exclude target from X.

Student extension: Explain how this differs from Topic 86 numerical regression.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 2 — Inspect the Iris dataset

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Use load_iris(as_frame=True), verify shape (150,4), 50 per class and missing counts.

Student extension: Plot at least two measured features and discuss overlap.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 3 — Visualize distributions

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Make a class-frequency chart, petal scatter and one measured-feature histogram.

Student extension: Explain that two displayed features are not all four model inputs.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 4 — Create a stratified split

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Use 80/20, seed 87; verify 120/30 and 40/10 for every species.

Student extension: Explain why the test stays untouched.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 5 — Train the dummy baseline

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Fit most_frequent on training data and evaluate on held out.

Student extension: Calculate 10/30 baseline accuracy.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 6 — Fit three classifiers

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: StandardScaler+Logistic Regression, max-depth-3 Tree, 200-tree Forest.

Student extension: Record exact hyperparameters and versions.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 7 — Use five-fold CV

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: StratifiedKFold on training only, select by highest mean macro F1.

Student extension: Report LR .9580, Tree .9414 and Forest .9496 for verified run.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 8 — Evaluate selected model

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Fit selected LR on all train rows and report true 3×3 test matrix and class report.

Student extension: Confirm 28/30 test accuracy and two off-diagonal mistakes.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 9 — Explore binary thresholds

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Virginica positive, predict_proba column checked, compute ROC/PR curves.

Student extension: Distinguish separate binary model and synthetic 100-case worksheet.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Capstone 10 — Write a responsible research report

Objective: independently reproduce and explain this stage before revealing the reference.

Show method and evidence

Method and verification: Document source, code, training/test, CV, plots, limitations, ethics and model card.

Student extension: State why benchmark success is not universal deployment evidence.

Common mistake: treating validation results as final test findings or copying illustrative numbers as real predictions.

Which Classifier Would You Choose? Eight interactive scenarios

Scenario 1: Simple approximately linear separation

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

A scaled Logistic Regression may be an efficient interpretable starting point; still evaluate class errors and calibration.

Scenario 2: Readable if/then decisions are essential

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

A constrained Decision Tree is easier to inspect than a forest; validate its performance, not just readability.

Scenario 3: Measurements interact nonlinearly

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

A Decision Tree or Random Forest may represent interactions; compare by training-only validation.

Scenario 4: Rare positive class is often missed

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

Inspect recall, class support and macro metrics; balancing or threshold changes need validation.

Scenario 5: False negatives are especially costly

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

Consider positive recall and the consequences of false alarms, not overall accuracy alone.

Scenario 6: Perfect training score but poor validation

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

This is evidence of poor generalization or overfitting; try constrained complexity and appropriate CV.

Scenario 7: Species label included among input features

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

Target leakage makes evaluation meaningless; remove the label from X.

Scenario 8: Accurate classes but unreliable probabilities

Show hint

Identify whether the main issue is the decision boundary, interpretability, error costs, data leakage or calibration.

Show explanation

Investigate probability calibration on appropriate validation data, not just labels.

Thirty original classification practice questions

The full printable question set and answer guide are available below. The thirty expandable exercises on this page progress from definitions to arithmetic and responsible model interpretation. Students should state class definitions, denominators, the evaluation partition and the original-versus-synthetic data source whenever a result is numerical. The first 10 assess foundations; Questions 11–20 practise calculations; Questions 21–30 examine validation, thresholds and responsible use. The eight scenarios above are additional discussion activities, not claimed as extra numbered exam questions.

Level 1 — Classification Foundations

Question 1: Define supervised classification

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Use labeled data to learn a mapping from features to discrete classes.

Common mistake: Do not conflate a numeric code with continuous target.

Question 2: Classification versus regression

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Species is a category; numerical examination score is regression.

Common mistake: Logistic Regression classifies despite its name.

Question 3: What is supervised learning?

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Training pairs known labels with features, and testing uses unseen observations.

Common mistake: Do not put label in X.

Question 4: Identify Iris’s four features

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Sepal length, sepal width, petal length, petal width, all in cm.

Common mistake: Species is the target, not a feature.

Question 5: Identify target labels

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Setosa, versicolor, virginica; codes 0,1,2.

Common mistake: Codes are identifiers.

Question 6: Define binary classification

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Two labels; virginica vs other is an Iris extension.

Common mistake: Different task from three-class Iris.

Question 7: Define multiclass classification

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Exactly one label from three or more categories.

Common mistake: Not multilabel.

Question 8: Why inspect class balance?

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Unequal support can make accuracy misleading; Iris is 50/50/50.

Common mistake: Balanced isn’t necessarily representative.

Question 9: Why reserve the held-out test?

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: It evaluates after fitting and training-only model selection.

Common mistake: Don’t tune on test.

Question 10: What baseline is used?

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Most-frequent DummyClassifier, one class for every flower.

Common mistake: Baseline test accuracy 10/30.

Level 2 — Calculations and Model Evaluation

Question 11: Compute class proportions

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 50/150=33.33% per species.

Common mistake: Use total 150.

Question 12: Compute split sizes

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 80% of 150=120 train; 20%=30 test; 40/10 per class.

Common mistake: Stratification preserved classes.

Question 13: Interpret three illustrative probabilities

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 0.10, 0.75, 0.15 implies versicolor; total 1.00.

Common mistake: Not measured for a particular flower.

Question 14: Calculate Gini impurity

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 1-(.6²+.4²)=.48; a pure node has 0.

Common mistake: Split evaluation uses weighted child impurity.

Question 15: Identify binary matrix entries

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: TP24,FP6,FN8,TN62, total 100.

Common mistake: Fictional, not Iris.

Question 16: Calculate accuracy

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: (24+62)/100=86%.

Common mistake: Overall accuracy hides minority errors.

Question 17: Calculate precision

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 24/(24+6)=80%.

Common mistake: Predicted positives denominator.

Question 18: Calculate recall

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 24/(24+8)=75%.

Common mistake: Actual positives denominator.

Question 19: Calculate specificity

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 62/(62+6)=91.18%.

Common mistake: Not precision.

Question 20: Calculate F1-score

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: 2(.8)(.75)/(.8+.75)=0.7742 ≈77.42%.

Common mistake: Does not explicitly include TN.

Level 3 — Advanced Interpretation

Question 21: Calculate balanced accuracy

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: (.75+.9117647)/2 ≈83.09%.

Common mistake: Different from ordinary 86%.

Question 22: Explain imbalanced accuracy

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Predict negative on 95 negatives and 5 positives: 95% accuracy, 0% positive recall.

Common mistake: Track class support.

Question 23: Explain macro F1

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Average per-class F1 values equally.

Common mistake: Not F1 of macro precision/recall.

Question 24: Precision versus recall

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Precision: correctness among predicted positives; recall: positives found.

Common mistake: Costs of FP and FN differ.

Question 25: Threshold 0.5 vs 0.8

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: For score .70: positive at .50, negative at .80.

Common mistake: Choose threshold on validation.

Question 26: Identify data leakage

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Target included in X or scaling before split leaks information.

Common mistake: Use train-only Pipeline.

Question 27: Explain tree overfitting

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Deep tree may memorize training noise; compare validation.

Common mistake: More depth isn’t universally better.

Question 28: Interpret actual CV results

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: LR .9580, Tree .9414, Forest .9496; LR selected by macro F1.

Common mistake: CV is not held-out test.

Question 29: Choose best algorithm responsibly

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Consider validation, task costs, interpretability and data shift.

Common mistake: No universally best classifier.

Question 30: Write evaluation recommendation

Show hint

Check the relevant feature/target definition, class support, denominator, split or scientific limitation.

Show worked answer

Verified answer: Document source, seed87, split, baseline, CV, LR test28/30, errors, ethics.

Common mistake: No high-stakes inference.

Download the classification learning resources

The following original teaching materials are hosted in the connected Notes for SHS WordPress media library. The complete ZIP accompanying this lesson also contains the executed eight-cell notebook, reproducible source script, real held-out prediction CSV, numerical result JSON, figure files, environment requirements and model card. It deliberately does not redistribute a separate copied Iris CSV; students use the standard Scikit-Learn loader, which records source provenance. The Sheets-compatible file is an XLSX workbook whose formula values were checked, but it has not been executed in native online Google Sheets.

Optional structured machine-learning courses

Students who prefer a guided syllabus can explore machine learning courses on Coursera and Scikit-Learn courses on Udemy. These are ordinary provider discovery links and not approved affiliate-tracked destinations for this article; no verified course-level tracking URL or ad creative was available. If affiliate links are subsequently added by the site’s authorized editor, they should include an honest disclosure, valid sponsored-link attributes and a checked course destination. Costs, course availability and certification conditions should be verified on the provider’s current page.

Frequently asked classification questions

What is classification in machine learning?

A supervised task in which a model predicts predefined categories from input measurements.

How is classification different from regression?

Classification predicts labels, while regression predicts numeric outcomes.

What is binary classification?

A two-class prediction task such as virginica versus not virginica.

What is multiclass classification?

Selecting one label from three or more mutually exclusive classes, as in Iris.

Why is Logistic Regression a classifier?

It transforms linear scores into class-probability estimates and class decisions.

How does a Decision Tree work?

It follows learned feature-threshold splits to terminal class-predicting leaves.

How does Random Forest work?

It aggregates predictions from multiple randomized trees.

Is Random Forest always better?

No. On this fixed Iris training-CV comparison, Logistic Regression had the highest macro F1.

What is the confusion matrix?

A table matching actual labels to predicted labels, revealing both correct predictions and class confusions.

Why can accuracy be misleading?

A majority-class classifier may score highly while missing all minority-class instances.

Precision versus recall?

Precision evaluates predicted positives; recall evaluates identification of actual positives.

What is specificity?

The fraction of actual negatives correctly predicted negative.

What is macro F1?

The arithmetic mean of each class’s separately calculated F1-score.

What is a classification threshold?

A rule translating an estimated positive-class score or probability into a binary label.

How can I prevent data leakage?

Exclude target labels from features, split early and fit learned preprocessing within training folds.

Conclusion: choose the classifier that fits the problem

Logistic Regression combines linear class scores with probability estimates; Decision Trees express predictions through branching rules; and Random Forests combine many randomized trees. Each has strengths, limitations and different interpretability or computational costs. A successful classification study begins by understanding its data and labels, defining appropriate error measures, setting aside a genuine test set, comparing against a baseline, fitting preprocessing within training-fold validation, and reporting the resulting confusion matrix with honest limitations. In our measured Iris exercise, Logistic Regression performed best by the predeclared training CV macro F1 criterion and classified 28 of 30 held-out flowers correctly.

That result is an example of responsible reproducible analysis, not a universal endorsement of one model. The small historical benchmark has no private pupil records, but a strong score on familiar flower measurements does not imply the same reliability with unfamiliar species, image data, changing measurements or high-stakes applications. Work through the downloadable notebook, binary metrics worksheet and capstone. Reproduce the numbers, investigate the two observed class mistakes, explain the difference between probability scores and labels, and record why each model decision was made. That reasoning—not a single impressive accuracy figure—is the foundation of trustworthy classification.

Official research and software references

Related Notes for SHS lessons