Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 8: Chapter 11 – Training and Testing a Machine Learning Model

Byte by Byte › Book 8: Real-World Coding, Data and AI › Chapter 11: Training and Testing a Machine Learning Model

Chapter 11: Training and Testing a Machine Learning Model

Illustration from Byte by Byte Book 8: Chapter 11 – Training and Testing a Machine Learning Model

🔎 The Case

The warning bell rings when the river crosses the danger mark, but by then the water is already in the fields. Kachui asks the question that matters: "Can we know the night before?" Beautine's archive holds 400 past days: rainfall today, rainfall yesterday, the morning level, and whether it flooded. In Book 7 you learned the AI project cycle and how decision trees work. Now you will build one for real, in code.

💡 The Concepts

Machine learning (ML) finds patterns in example data instead of following rules a programmer wrote. In supervised learning, each example has features (inputs, called X) and a label (the right answer, called y). The model learns a mapping from X to y.

  • Classification: the label is a category (flood / no flood, spam / not spam).
  • Regression: the label is a number (tomorrow's level in metres).

Unsupervised learning has no labels; it finds groups (clustering). Reinforcement learning learns by trial, reward and penalty (game-playing AIs).

The workflow:

  1. Collect and clean data (Chapter 7).
  2. Choose features and label.
  3. Split the data: a training set (usually 70–80%) to learn from, and a test set the model never sees during training.
  4. Train (fit) the model on the training set.
  5. Predict on the test set and compare predictions with the true labels.
  6. Improve and repeat.

Why a separate test set? Testing on training data is like marking your own exam with the answer key you studied from. A model can memorise its training examples and still fail on new ones.

Overfitting and underfitting.

  • Overfitting: the model learns the training data too closely, including its noise. Very high training accuracy, lower test accuracy. A decision tree with unlimited depth often does this.
  • Underfitting: the model is too simple to capture the pattern. Poor accuracy on both.
  • The goal is generalisation: good performance on data the model has never seen.

Hyperparameters are settings you choose before training, such as a tree's max_depth . Parameters are what the model learns.

scikit-learn ( sklearn ) is Python's main ML library. Every model follows the same pattern: model.fit(X_train, y_train) , then model.predict(X_test) .

🛠️ Build It

The archive data is generated here with a fixed random seed so everyone gets the same results.

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
n = 400
data = pd.DataFrame({
    "rain_today": rng.uniform(0, 100, n).round(),
    "rain_yesterday": rng.uniform(0, 100, n).round(),
    "morning_level": rng.uniform(1.5, 3.5, n).round(2),
})
risk = (0.02 * data["rain_today"] + 0.01 * data["rain_yesterday"]
        + 1.2 * data["morning_level"] + rng.normal(0, 0.4, n))
data["flood"] = (risk > 5.0).astype(int)
print(data.head())
print(data["flood"].value_counts())
X = data[["rain_today", "rain_yesterday", "morning_level"]]
y = data["flood"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=1, stratify=y)
for depth in [1, 3, None]:
    model = DecisionTreeClassifier(max_depth=depth, random_state=1)
    model.fit(X_train, y_train)
    train_acc = accuracy_score(y_train, model.predict(X_train))
    test_acc = accuracy_score(y_test, model.predict(X_test))
    print(f"max_depth={depth}: train {train_acc:.2f}, test {test_acc:.2f}")
model = DecisionTreeClassifier(max_depth=3, random_state=1).fit(X_train, 
y_train)
plt.figure(figsize=(14, 6))
plot_tree(model, feature_names=list(X.columns), class_names=["No flood", 
"Flood"], filled=True)
plt.show()
tonight = pd.DataFrame({"rain_today": [70], "rain_yesterday": [40], 
"morning_level": [2.8]})
print("Prediction:", model.predict(tonight)[0])
print("Probability of flood:", model.predict_proba(tonight)[0][1].round(2))

Record the three lines of train and test accuracy. Which depth overfits? Which underfits? Read the tree diagram: which feature does it split on first?

( stratify=y keeps the same flood/no-flood proportion in both sets. random_state makes the split repeatable.)

✅ Case Closed

The unlimited tree scores 100% on training data but only 82% on the test set: it memorised the archive. The one-question tree (depth 1) underfits at 70%. The depth-3 tree does best on the test set, 88%, and is simple enough for Kachui to read. Its first question is about the morning level. Glim suggests adding the model to the gauges. Memoon says, "Not yet. Accuracy alone can hide a dangerous kind of mistake." That is the next chapter.

Career Spotlight: Machine Learning Engineer. Builds, trains, tests and deploys ML models in products: recommendations, fraud detection, medical imaging.

❓ Test Yourself

  1. What are features and labels? Name them for a model that predicts whether an email is spam.
  2. Classification or regression: (a) predicting house prices (b) recognising handwritten digits (c) tomorrow's temperature?
  3. Why must the test set be kept separate from training?
  4. A model scores 99% on training data and 61% on test data. What is happening? Suggest one fix.
  5. What is the difference between a parameter and a hyperparameter?
  6. Challenge: Retrain with test_size=0.4 . Does test accuracy change? Try max_depth 2, 4 and 6 and find the best on the test set.

📚 Key Terms

machine learning · supervised learning · unsupervised learning · reinforcement learning · feature · label · classification · regression · clustering · training set · test set · train_test_split · fit · predict · predict_proba · overfitting · underfitting · generalisation · hyperparameter · parameter · max_depth · scikit-learn · random seed · stratify

Keep learning with Byte by Byte

Explore Book 8: Real-World Coding, Data and AI. Find the ebook, purchase details and teaching slides on MemuniCity.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...