Practical Roadmap

Build Your First AI Projects

Move from Python and data inspection to small models, honest evaluation, and an evidence-based application you can run and explain.

Before You Begin

  • Complete AI foundations and literacy if the concepts are new
  • Write Python functions, loops, and simple tests; study introductory Python first if needed
  • Understand basic algebra, averages, and proportions
  • Use public or synthetic datasets and check their licenses

What You Will Build

A reproducible local classification project and a small evidence-retrieval prototype, with baselines, evaluation results, and clearly documented limits.

YOUR COURSE PROJECT · 8 CONNECTED STAGES

Study-Note Classifier

Build a local program that labels tiny fictional study notes as web or security, measures its mistakes, and retrieves a relevant source note. Start with plain Python and a baseline, then inspect one small neural network. The twelve invented notes teach the mechanics; their scores are not evidence of real-world accuracy.

What You Need

  • Python 3 and a text editor
  • A terminal in a study-note-classifier folder
  • PyTorch for the neural-network lesson only; use the official CPU installation selector for your operating system

Set Up Your Project

  1. Create study-note-classifier and run all commands from that folder. Use python or python3 according to your installation and record python --version.
  2. Use only the twelve synthetic records created in the first lesson. No private study notes, cloud API, or downloaded dataset is required.
  3. Keep data.py, features.py, split.py, baseline.py, metrics.py, train.py, retrieve.py, and README.md as separate files so responsibilities remain visible.
  4. Before installing PyTorch, create a project environment with python -m venv .venv. Use .venv\Scripts\python.exe on Windows or .venv/bin/python on macOS/Linux for that environment. Follow the official CPU installation command; no GPU is needed for this tiny exercise.

Markdown file · all lessons, examples and project steps · no account needed

01

Build Confidence with Python and Data

Create twelve labelled synthetic study notes and validate their IDs, text, and category counts before modelling.

What You Will Learn

  • Represent labelled examples with stable IDs and validate their structure.
  • Inspect class counts before choosing a model.

Understand the Idea

Classification means assigning an input to one of a defined set of categories. Our input is a short fictional study-note title; the categories are web and security. A label is the category assigned to an example. The label is training data, not an unquestionable truth: a note about HTTP can reasonably relate to both fields. This exercise deliberately uses a single-label policy and assigns HTTP notes to security. Write that policy down so later disagreements are interpreted consistently.

A Python dictionary stores named fields such as id, text, and label. A list stores the collection of records. The code below creates twelve records from a fixed list, then checks that every ID is unique, every text is nonempty, and every label belongs to the allowed set. These checks catch simple mistakes before they become mysterious model behaviour. Raising an error is better than silently dropping a record, because dropping records changes the dataset you think you are evaluating.

The dataset is tiny, balanced, and intentionally easy. Balanced means the two categories have the same number of examples. Real study notes would include mixed topics, misspellings, different writing styles, and subjects outside the allowed categories. Keep a limitation note from the beginning rather than waiting until the model produces an impressive score. The immediate goal is a reproducible data pipeline you can explain. Training a sophisticated model on poorly understood records would only make the mistakes harder to inspect.

WORKED EXAMPLE

Create and Inspect Twelve Notes

Save as data.py and run python data.py. The file contains the complete synthetic dataset and uses only the Python standard library.

python
from collections import Counter

PAIRS = [
    ("html form", "web"), ("css layout", "web"),
    ("javascript button", "web"), ("http cookie", "security"),
    ("linux permission", "security"), ("network log", "security"),
    ("html button", "web"), ("css form", "web"),
    ("linux log", "security"), ("network permission", "security"),
    ("javascript layout", "web"), ("http permission", "security")
]
NOTES = [{"id": f"n{i}", "text": text, "label": label}
         for i, (text, label) in enumerate(PAIRS, 1)]

def check_notes(rows):
    seen = set()
    for row in rows:
        if not row["text"].strip() or row["label"] not in {"web", "security"}:
            raise ValueError("Invalid note")
        if row["id"] in seen:
            raise ValueError("Duplicate note ID")
        seen.add(row["id"])
    return rows

if __name__ == "__main__":
    rows = check_notes(NOTES)
    print(len(rows))
    print(dict(Counter(row["label"] for row in rows)))
  1. enumerate starts IDs at n1 and preserves the written example order.
  2. Counter counts the labels independently of any classifier.
  3. The main block prints only when the file is run directly; later files can import NOTES without producing extra output.

Expected Result

The first line is 12. The second is {'web': 6, 'security': 6}.

PROJECT STAGE 01 / 8

Establish the Data Contract

Builds on: Start with the project folder and the written single-label policy.

  1. Save data.py exactly as shown and run it to verify the twelve-record summary.
  2. Create README.md describing the web/security labels and the policy for HTTP notes.
  3. Record that every example is synthetic and that the same keywords make this an unusually easy dataset.
  4. On a disposable copy, introduce a duplicate ID and confirm check_notes raises an error.
  5. Restore the dataset and list three kinds of real note that these examples do not represent.

Keep This Deliverable

A validated data.py and a README containing the labelling policy and dataset limitations.

Check Your Build

  • The summary reports twelve notes with six in each category.
  • A duplicate ID is rejected, and the original dataset is restored before continuing.

Common Mistakes and Fixes

Treating the provided label as a universal definition of a topic.
State the project’s labelling policy and record ambiguous cases for human review.
Training before checking the input records.
Inspect counts, missing values, duplicates, and scope first.

Check Your Understanding

Why might an HTTP note receive a different label in another project?

Reveal the explanation

Categories depend on the task and labelling policy. HTTP appears in both web development and security; this exercise makes a specific simplifying choice rather than defining a universal taxonomy.

Ready to Move On?

The dataset contains twelve unique notes, six per category, and the README states the HTTP labelling policy and synthetic-data limits.

Open the learning resource
02

Learn the Math through Small Predictions

Represent each note with six keyword features and hand-calculate a rule that can also request human review.

What You Will Learn

  • Turn text into a small numeric feature vector.
  • Calculate a score and distinguish it from a calibrated probability.

Understand the Idea

A model usually needs numbers rather than raw strings. A feature is a measurable property of an input. We will use six simple features: whether the words html, css, javascript, http, linux, and network appear in the note. A vector is an ordered list of these numbers. The order matters: the first position always means html, not whichever word happens to come first in the sentence. This fixed representation becomes the input to both a hand-written rule and the later neural network.

A weighted score multiplies each feature by a weight and adds the results. A positive weight pushes the score toward one category; a negative weight pushes it toward the other. The example assigns positive weights to the three security keywords and negative weights to the web keywords. These weights are chosen by us, so this is a rule-based demonstration, not a trained model. A score of 1 is not a 100 percent probability. It is simply the result of the specified arithmetic.

Representations discard information. Lowercasing and splitting on whitespace handles our controlled two-word notes, but punctuation, synonyms, word order, and meaning are mostly ignored. The phrase “not about linux” still activates linux. A note with no recognised keywords becomes an all-zero vector, so the program needs a review state rather than pretending the input is well understood. This lesson makes the limitations visible before adding optimisation or more parameters.

WORKED EXAMPLE

Calculate a Note Score by Hand

Save as features.py and run python features.py. It is self-contained; later lessons import features and VOCAB from this file.

python
VOCAB = ("html", "css", "javascript", "http", "linux", "network")

def features(text):
    words = set(text.lower().split())
    return [int(word in words) for word in VOCAB]

def rule(text):
    vector = features(text)
    if not any(vector):
        return "review"
    weights = (-1, -1, -1, 1, 1, 1)
    score = sum(value * weight for value, weight in zip(vector, weights))
    return "security" if score > 0 else "web" if score < 0 else "review"

if __name__ == "__main__":
    vector = features("linux permission")
    print(vector)
    print(sum(v * w for v, w in zip(vector, (-1, -1, -1, 1, 1, 1))))
    print(rule("linux permission"))
    print(rule("study habits"))
  1. Only linux is in the vocabulary, so the fifth position is 1 and the others are 0.
  2. The dot product is 1 because the linux weight is positive.
  3. No recognised feature appears in study habits, so the rule returns review.

Expected Result

Four lines: [0, 0, 0, 0, 1, 0], then 1, then security, then review.

PROJECT STAGE 02 / 8

Add an Explainable Representation

Builds on: Use the labels and limitations documented with the twelve-note dataset.

  1. Save features.py and calculate the linux example on paper before running it.
  2. Calculate the vector for html form and confirm the rule returns web.
  3. Try html linux and explain why the equal opposing weights produce review.
  4. Add a representation section to README.md explaining the fixed feature order and missing punctuation handling.
  5. Keep two deliberately difficult examples, study habits and not about linux, as limitation notes rather than secretly changing the dataset.

Keep This Deliverable

A reusable feature function, a transparent keyword rule, and hand-checked examples.

Check Your Build

  • You can explain every position in the six-number vector.
  • Unknown and tied inputs return review instead of a fabricated confidence value.

Common Mistakes and Fixes

Calling a raw score a probability.
Describe the arithmetic and category rule; probability calibration is a separate question.
Changing feature order between training and prediction.
Keep one shared VOCAB constant and import the same feature function everywhere.

Check Your Understanding

Why does “not about linux” expose a weakness in this representation?

Reveal the explanation

The features only record word presence. They do not represent negation or sentence meaning, so linux still activates the same feature as a genuinely Linux-focused note.

Ready to Move On?

You can reproduce the linux vector and score, and unknown or tied inputs return review rather than invented confidence.

Open the learning resource
03

Separate Learning from Evaluation

Freeze training, validation, and test roles for the twelve notes and check record overlap while documenting the fixture’s limited independence.

What You Will Learn

  • Assign distinct roles to training, validation, and test examples.
  • Identify information leakage and overly similar evaluation data.

Understand the Idea

Training data is used to fit a model’s parameters. Validation data helps compare choices such as features or training settings. Test data is reserved for a final evaluation after those choices are fixed. These roles reduce the chance of measuring how well you adapted to the answers instead of how well the system handles new examples. In this teaching dataset the contents are visible, but you should still avoid using the final test labels to tune the model.

Leakage occurs when information unavailable at prediction time influences model development or evaluation. Copying an identical note into training and test is an obvious example. Learning a vocabulary from all records before splitting can also leak information in more realistic workflows. Our six-word vocabulary was chosen explicitly for the exercise, so document it as a hand-designed simplification. Do not describe the final score as an unbiased estimate of general language understanding.

The split below is fixed and balanced within each subset. That makes arithmetic easy and runs reproducible, but it is not a recommended universal split ratio. The validation and test notes reuse keywords seen during training, making them much easier than genuinely new study notes. There are only two final test examples, so one error changes accuracy by fifty percentage points. This is an exercise in procedure, with unusually weak evidence about real performance.

WORKED EXAMPLE

Freeze the Three Data Roles

Save as split.py beside data.py, then run python split.py. Do not reorder NOTES while using this saved split definition.

python
from data import NOTES, check_notes

check_notes(NOTES)
TRAIN = NOTES[:6]
VALIDATION = NOTES[6:10]
TEST = NOTES[10:]

def check_split():
    groups = [TRAIN, VALIDATION, TEST]
    ids = [{row["id"] for row in group} for group in groups]
    if any(ids[a] & ids[b] for a, b in ((0, 1), (0, 2), (1, 2))):
        raise ValueError("An ID appears in more than one split")
    texts = [row["text"].strip().lower() for group in groups for row in group]
    if len(texts) != len(set(texts)):
        raise ValueError("Duplicate note text across the fixture")

if __name__ == "__main__":
    check_split()
    for name, group in (("train", TRAIN), ("validation", VALIDATION), ("test", TEST)):
        print(name, [row["id"] for row in group])
  1. Training uses n1-n6, validation n7-n10, and final test n11-n12.
  2. The ID check prevents the same record from belonging to two groups.
  3. The text check catches exact normalised duplicates, but cannot detect every paraphrase or semantic overlap.

Expected Result

Three lines showing train [n1…n6], validation [n7…n10], and test [n11, n12], with no overlap error.

PROJECT STAGE 03 / 8

Record the Evaluation Boundary

Builds on: Use the unchanged twelve records and the shared feature function.

  1. Save split.py and verify the three printed ID lists.
  2. Write the split IDs into README.md so later data edits cannot silently redefine the experiment.
  3. State which decisions may use validation results and that test results are reserved for the final project review.
  4. On a disposable copy, insert a training record into validation and confirm the overlap check fails.
  5. Explain why different IDs do not guarantee independent examples when the same keywords dominate every split.

Keep This Deliverable

A fixed split file, documented IDs, and a successful leakage-check demonstration.

Check Your Build

  • No ID appears in two groups, and the original split is restored after testing the failure case.
  • The README states that two test notes and repeated keywords cannot establish real-world accuracy.

Common Mistakes and Fixes

Repeatedly choosing settings based on the final test score.
Use validation for development and reserve the final test for a declared final review.
Assuming random splitting automatically prevents every leakage problem.
Check duplicates, groups, time relationships, and features that may reveal labels.

Check Your Understanding

Why is a perfect result on two test notes weak evidence?

Reveal the explanation

The sample is tiny and unrepresentative; each example changes the score greatly. In this fixture the same hand-chosen keywords also recur across all splits, making the task unusually easy.

Ready to Move On?

The 6/4/2 split is recorded, overlap checks work, and the final test is reserved for the declared capstone check.

Open the learning resource
04

Build a Baseline before a More Complex Model

Compare a majority-label baseline with the earlier keyword rule on the same four validation notes.

What You Will Learn

  • Build a simple reference classifier before fitting a neural network.
  • Compare meaningful behaviours using the same validation examples.

Understand the Idea

A baseline is a simple system that establishes a minimum useful comparison. Our first baseline always predicts the most common training label. Because this training subset has three web and three security notes, we explicitly break the tie in favour of web. The tie rule matters: hidden ordering should not silently determine results. On the balanced validation set, this baseline gets two of four labels correct without reading the text at all.

The second reference is the keyword rule from the earlier lesson. It uses a hand-designed representation and weights, so it is still not a trained model. Comparing it with the majority baseline tells you whether the chosen text features carry information in this fixture. They do, because we constructed the dataset around those keywords. This should make you more cautious about interpreting a perfect result, not more confident that the classifier understands arbitrary notes.

Keep the inputs and scoring identical for every system. If one method is evaluated on easier examples, the comparison does not answer which method is more useful. Also record review outputs: refusing to label an unfamiliar input can be appropriate, but it should not disappear from the denominator when you report coverage. For the four controlled validation notes, the keyword rule makes four predictions and should get all four correct. Later, mixed-topic and unknown notes will show its limits.

WORKED EXAMPLE

Compare Majority and Keyword Baselines

Save as baseline.py beside data.py, split.py, and features.py, then run python baseline.py.

python
from collections import Counter
from split import TRAIN, VALIDATION, check_split
from features import rule

def majority_label(rows):
    counts = Counter(row["label"] for row in rows)
    return "web" if counts["web"] >= counts["security"] else "security"

def evaluate(rows, predict):
    predictions = [predict(row["text"]) for row in rows]
    correct = sum(prediction == row["label"] for prediction, row in zip(predictions, rows))
    return correct, len(rows), predictions

if __name__ == "__main__":
    check_split()
    label = majority_label(TRAIN)
    for name, predict in (("majority", lambda text: label), ("keyword", rule)):
        correct, total, predictions = evaluate(VALIDATION, predict)
        print(f"{name}: {correct}/{total}; {predictions}")
  1. The majority choice is derived only from TRAIN, with an explicit tie policy.
  2. Both systems receive the same four validation texts.
  3. The keyword system’s perfect result reflects the deliberately simple fixture and must be reported with that limitation.

Expected Result

majority: 2/4 with four web predictions. keyword: 4/4 with predictions web, web, security, security.

PROJECT STAGE 04 / 8

Save the Baseline Evidence

Builds on: Use the frozen split and the feature rule already checked by hand.

  1. Save baseline.py and predict both validation scores before running it.
  2. Run the script and record the full output in baseline-results.txt.
  3. Check the four predictions against the original labels one row at a time.
  4. Try the rule on study habits and html linux, recording review as an explicit result.
  5. Write a short model-selection note explaining what a later trained system would need to improve.

Keep This Deliverable

Two baseline results and a comparison note covering accuracy, review behaviour, complexity, and limitations.

Check Your Build

  • The majority baseline scores 2/4 and the keyword baseline scores 4/4 on the fixed validation subset.
  • The comparison does not silently discard review outputs or change the evaluation examples.

Common Mistakes and Fixes

Assuming a neural network is useful merely because it is more complex.
Compare its actual behaviour and maintenance cost with the simple baseline.
Reporting a percentage without the number of examples.
Always include the numerator, denominator, split, and dataset limitations.

Check Your Understanding

What does a neural network need to justify replacing the keyword rule here?

Reveal the explanation

It needs a concrete benefit on meaningful examples or another requirement, such as better handling of varied language. Matching a perfect score on this tiny fixture while adding dependencies is not enough.

Ready to Move On?

The recorded majority score is 2/4 and the keyword score is 4/4, with review cases and synthetic-data limits explained.

Open the learning resource
05

Choose Metrics That Reveal Important Mistakes

Calculate explicit error counts, precision, recall, and accuracy using a diagnostic fixture and the saved baseline predictions.

What You Will Learn

  • Calculate a confusion matrix, precision, and recall with explicit denominators.
  • Relate a metric to the kind of mistake the application cares about.

Understand the Idea

Accuracy is the fraction of predictions that match the labels. It can hide unequal performance when one category is much more common. A classifier that always chooses web could look accurate in a collection containing mostly web notes while missing every security note. A confusion matrix counts the combinations of actual and predicted categories. For this lesson, call security the positive category; positive is a naming convention, not a judgement that one topic is better.

A true positive is an actual security note predicted as security. A false positive is a web note incorrectly predicted as security. A false negative is a security note missed as web. Precision asks how many predicted security notes were actually security. Recall asks how many actual security notes were found. The denominators differ, so write them out before calculating. If a denominator is zero, report the metric as undefined for that case rather than quietly inventing a percentage.

Use the deliberately imperfect predictions below to practise the arithmetic. They are a diagnostic fixture, not output claimed from your trained model. One example in each confusion-matrix cell makes the numbers easy to check. In a real sorting app, the cost of a misplaced note and the availability of human review would influence which metric matters. No metric compensates for unclear labels or an unrepresentative dataset, and four examples are insufficient for a stable performance claim.

WORKED EXAMPLE

Calculate Four Outcomes Explicitly

Save as metrics.py and run python metrics.py. This example is self-contained and uses four intentionally chosen predictions.

python
def metrics(actual, predicted):
    if len(actual) != len(predicted) or not actual:
        raise ValueError("Need equal nonempty lists")
    if set(actual + predicted) - {"web", "security"}:
        raise ValueError("Expected web/security labels")
    tp = sum(a == "security" and p == "security" for a, p in zip(actual, predicted))
    fp = sum(a == "web" and p == "security" for a, p in zip(actual, predicted))
    fn = sum(a == "security" and p == "web" for a, p in zip(actual, predicted))
    tn = sum(a == "web" and p == "web" for a, p in zip(actual, predicted))
    return {"TP": tp, "FP": fp, "FN": fn, "TN": tn,
            "accuracy": (tp + tn) / len(actual),
            "precision": tp / (tp + fp) if tp + fp else None,
            "recall": tp / (tp + fn) if tp + fn else None}

if __name__ == "__main__":
    print(metrics(["web", "web", "security", "security"],
                  ["web", "security", "security", "web"]))
  1. The four pairs produce one true positive, one false positive, one false negative, and one true negative.
  2. Accuracy is 2/4, precision is 1/2, and recall is 1/2.
  3. None represents an undefined ratio when its denominator is zero; the caller should explain that state.

Expected Result

The dictionary contains TP=1, FP=1, FN=1, TN=1 and accuracy=0.5, precision=0.5, recall=0.5.

PROJECT STAGE 05 / 8

Add an Error Analysis

Builds on: Use the baseline predictions and fixed labels, while keeping the diagnostic fixture clearly separate.

  1. Save metrics.py and calculate all four counts by hand before running it.
  2. Apply metrics to the majority baseline’s validation predictions and explain why security recall is zero.
  3. Apply it to the keyword baseline and record the four-example denominator beside every perfect metric.
  4. Write one fictional example of a false positive and one of a false negative that a learner would notice.
  5. Decide how a future interface should display review cases rather than forcing every unknown note into a category.

Keep This Deliverable

A checked metrics function and an error-analysis note connecting counts to user-visible mistakes.

Check Your Build

  • You can explain the difference between precision and recall using their denominators.
  • A zero-denominator metric is reported as undefined rather than as a fabricated success score.

Common Mistakes and Fixes

Swapping actual and predicted labels when counting errors.
Write each pair in a two-column table and label the positive category first.
Celebrating high accuracy on a highly imbalanced collection.
Inspect per-category errors and compare with the majority baseline.

Check Your Understanding

What happens to security recall if the classifier predicts web for every note?

Reveal the explanation

It is zero when actual security notes exist, because none are found. Precision for security is undefined because there are no predicted security notes.

Ready to Move On?

You can explain every denominator and report undefined ratios honestly when no positive predictions exist.

Open the learning resource
06

Understand a Small Neural-Network Training Loop

Train one small CPU PyTorch network on the same six-feature representation and compare its observed validation behaviour with the simpler baseline.

What You Will Learn

  • Trace a small neural network’s forward, loss, gradient, and update steps.
  • Evaluate a trained model separately from its training loop.

Understand the Idea

A neural network combines numerical operations with adjustable parameters. Our input is the same six-feature vector used by the keyword rule. The first linear layer maps six numbers to four hidden values; ReLU replaces negative hidden values with zero; the second linear layer produces two scores, one per category. These output scores are called logits. The example uses cross-entropy loss to compare logits with integer labels, where web is 0 and security is 1. Do not apply softmax before this loss.

Training repeats four operations: compute predictions, calculate loss, compute gradients, and update parameters. A gradient describes how changing a parameter would affect the loss locally. The optimiser uses it to adjust the parameters. zero_grad clears old gradients because PyTorch otherwise accumulates them. backward computes new gradients, and step applies an update. The model trains only on TRAIN. Validation is inspected afterwards with gradient recording disabled, so evaluation does not accidentally become another training step.

Use the official PyTorch installation selector for a supported CPU package in the project environment; package compatibility depends on your operating system and Python version. A random seed makes a run more repeatable within a given setup, but does not promise identical results across releases or machines. Record the actual loss and predictions rather than copying an expected perfect score. This toy network is for understanding the training loop; it has no demonstrated advantage over the transparent keyword rule on these engineered features.

WORKED EXAMPLE

Train One Small CPU Network

Save as train.py beside the earlier files. Install PyTorch in the project environment first, then run that environment’s Python interpreter on train.py. No GPU or dataset download is used.

python
import torch
from torch import nn
from split import TRAIN, VALIDATION, check_split
from features import features

if __name__ == "__main__":
    check_split()
    torch.manual_seed(7)
    x = torch.tensor([features(row["text"]) for row in TRAIN], dtype=torch.float32)
    y = torch.tensor([0 if row["label"] == "web" else 1 for row in TRAIN], dtype=torch.long)
    model = nn.Sequential(nn.Linear(6, 4), nn.ReLU(), nn.Linear(4, 2))
    loss_fn = nn.CrossEntropyLoss()
    optimiser = torch.optim.SGD(model.parameters(), lr=0.1)
    initial = loss_fn(model(x), y).item()
    model.train()
    for _ in range(300):
        optimiser.zero_grad()
        loss = loss_fn(model(x), y)
        loss.backward()
        optimiser.step()
    model.eval()
    with torch.no_grad():
        final = loss_fn(model(x), y).item()
        vx = torch.tensor([features(row["text"]) for row in VALIDATION], dtype=torch.float32)
        predicted = model(vx).argmax(dim=1).tolist()
    print("input shape:", tuple(x.shape))
    print("loss decreased:", final < initial)
    print("validation labels:", predicted)
    print("torch:", torch.__version__)
    torch.save(model.state_dict(), "note-model.pt")
  1. The input shape is six training rows by six features; labels are a one-dimensional integer tensor.
  2. CrossEntropyLoss receives raw two-score logits and class indices, not already normalised probabilities.
  3. The checkpoint contains model parameters only; reproducing the model also requires its architecture and feature order.

Expected Result

The input-shape line is (6, 6). Record whether loss decreased and the four observed validation labels; exact floating-point values and predictions are not guaranteed across environments. A local note-model.pt is created.

PROJECT STAGE 06 / 8

Explain and Review the Training Run

Builds on: Reuse the unchanged data split, features, baselines, and metrics.

  1. Create the environment and install a supported CPU PyTorch build using the official instructions.
  2. Run train.py and save the actual Python/PyTorch versions, loss-decrease result, and validation predictions.
  3. Label each part of the loop as forward calculation, loss, gradient calculation, or parameter update.
  4. Compare the four validation predictions with the keyword baseline using the same labels.
  5. Write a decision note explaining whether the network offers any practical benefit here and why the checkpoint alone is insufficient to reproduce the project.

Keep This Deliverable

A local parameter checkpoint, recorded environment and validation results, and an explained training loop.

Check Your Build

  • Only training labels influence parameter updates; validation is evaluated outside the training loop.
  • The comparison reports observed results and acknowledges that the synthetic keyword task favours the simpler baseline.

Common Mistakes and Fixes

Applying softmax before CrossEntropyLoss.
Pass raw logits; the loss handles the needed normalisation internally.
Forgetting zero_grad and unintentionally accumulating gradients.
Clear gradients before each backward call in this training loop.

Check Your Understanding

Why does a lower training loss not establish useful real-world performance?

Reveal the explanation

It shows better fit to the training objective on these six examples. Unseen language, label ambiguity, dataset bias, and application needs still require independent evaluation.

Ready to Move On?

You can explain the forward, loss, backward, and update steps, record the environment, and assess results without claiming real-world accuracy.

Open the learning resource
07

Build a Small Application That Shows Its Evidence

Add a local word-overlap search that returns a source passage and a visible no-match state beside the study-note category.

What You Will Learn

  • Retrieve a relevant source passage and show its identifier.
  • Distinguish retrieval from generation and handle absent evidence.

Understand the Idea

Classification assigns a category; retrieval finds material relevant to a query. Add retrieval to the same study-note project so a learner can see an explanatory note rather than only a category label. The small corpus below contains three original teaching passages with stable IDs. Our retrieval score counts overlapping words between the query and each passage. This is an intentionally simple search baseline, not an embedding model or a language model.

Tokenisation here extracts lowercase letter sequences so punctuation does not prevent a basic match. Sets remove repeated words; a repeated query word therefore cannot inflate the score. The code picks the highest overlap and uses the written source order to break ties. If no words overlap, it returns no matching source. A match is only evidence that words overlap, not that the passage answers every possible question containing those words. Show the exact passage so the reader can assess its relevance.

Retrieval-augmented generation adds a generation step that receives retrieved material. We stop before that step because a source-backed local lookup already serves this project and is easy to verify. If you later add a model, require it to distinguish the supplied evidence from unsupported additions and evaluate its answers separately. Retrieving a real source does not make every generated sentence correct. Keep this working retrieval baseline so you can compare whether additional complexity improves the actual learner experience.

WORKED EXAMPLE

Return a Source, Not an Invented Answer

Save as retrieve.py and run python retrieve.py. The complete three-passage corpus is included; no model, network, or extra package is needed.

python
import re

DOCS = [
    {"id":"D1", "text":"HTML labels connect a form control to its description."},
    {"id":"D2", "text":"Linux permissions control which users may read or change a file."},
    {"id":"D3", "text":"HTTP status codes describe the response to a request."}
]

def words(text):
    return set(re.findall(r"[a-z]+", text.lower()))

def retrieve(query):
    query_words = words(query)
    ranked = [(len(query_words & words(doc["text"])), index, doc)
              for index, doc in enumerate(DOCS)]
    score, _, doc = max(ranked, key=lambda item: (item[0], -item[1]))
    return doc if score > 0 else None

if __name__ == "__main__":
    for query in ("linux permissions", "banana recipe"):
        source = retrieve(query)
        print(source["id"] + ": " + source["text"] if source else "No matching source")
  1. The first query shares linux and permissions with D2, so that source wins.
  2. The second query shares no words with the corpus and receives an explicit missing-evidence result.
  3. The source text is returned unchanged, giving the reader something concrete to inspect.

Expected Result

First: D2: Linux permissions control which users may read or change a file. Second: No matching source.

PROJECT STAGE 07 / 8

Connect Labels to Inspectable Evidence

Builds on: Use the classifier’s review concept and the project’s preference for explainable local behaviour.

  1. Save retrieve.py and verify the two exact outputs before changing the corpus.
  2. Create a small demo that calls rule(query) and retrieve(query), displaying the category or review state alongside the returned source.
  3. Try a query with only common words and explain why simple overlap may choose an irrelevant passage.
  4. Write three relevant-query checks and one absent-topic check, each with the expected source ID or no-match result.
  5. Document that retrieval is implemented but answer generation is intentionally not part of this version.

Keep This Deliverable

A local source lookup and a small category-plus-source demonstration with visible failure behaviour.

Check Your Build

  • linux permissions retrieves D2 and banana recipe returns no matching source.
  • The interface or console shows the exact source passage and does not fabricate a generated explanation.

Common Mistakes and Fixes

Calling any retrieved passage a verified answer.
Inspect whether the passage actually addresses the query and keep its ID visible.
Hiding no-match cases behind a confident fallback response.
Return an explicit no-source state and ask for a better query or more evidence.

Check Your Understanding

What would turn this retrieval tool into a retrieval-augmented generation system?

Reveal the explanation

Adding a language-model generation step that uses the retrieved passages as context. That new step would need its own factuality and boundary tests; the current program only returns source text.

Ready to Move On?

The Linux query returns D2, the banana query returns no source, and the project clearly distinguishes retrieval from generation.

Open the learning resource
08

Package a Project with Honest Limits

Package the study-note data, code, checks, and limitations, then run a declared final evaluation of the selected baseline.

What You Will Learn

  • Package the data, feature definition, evaluation evidence, and run instructions together.
  • Perform a declared final check without overstating the result.

Understand the Idea

Reproducibility means another person can follow the recorded procedure and understand or recreate the result under stated conditions. A model file alone is insufficient. The project also needs its input data, label policy, feature order, architecture if used, environment details, and the exact evaluation procedure. Keep generated checkpoints separate from source files and document how to recreate them. Do not load arbitrary downloaded model files merely to test your packaging; this project only needs artifacts you produced yourself.

Make a final selection before inspecting the reserved test result. The transparent keyword baseline is a reasonable choice for this tiny demonstration because it is easy to explain and the neural network has no established advantage. The code below tests that chosen rule on n11 and n12, then checks the retrieval behaviour. The expected two-of-two result is a mechanical fixture check, not evidence of real note-classification accuracy. Once you inspect this test result, record that it has been used; further tuning would require fresh evaluation examples.

Write a model or system card in plain language: intended use, excluded use, dataset origin, labels, evaluation counts, known failures, and the next meaningful improvement. Keep the difficult examples from earlier lessons, including unknown vocabulary, mixed topics, and negation. A credible portfolio explains these limitations rather than hiding them behind a screenshot of a perfect score. The project is complete when someone can run it, see evidence, and understand when it should ask for review.

WORKED EXAMPLE

Run the Declared Final Checks

Save as final_check.py beside baseline.py, split.py, features.py, and retrieve.py. This uses the keyword system selected before opening the final test result and does not require PyTorch.

python
from split import TEST, check_split
from features import rule
from baseline import evaluate
from retrieve import retrieve

check_split()
correct, total, predictions = evaluate(TEST, rule)
assert (correct, total) == (2, 2)
assert rule("study habits") == "review"
assert rule("html linux") == "review"
assert retrieve("linux permissions")["id"] == "D2"
assert retrieve("banana recipe") is None
print(f"Final fixture: {correct}/{total}; {predictions}")
print("Review and retrieval checks passed")
print("Synthetic fixture only; no real-world accuracy claim")
  1. The final classification check uses the two reserved records and the previously selected rule.
  2. Review and retrieval checks cover behaviour outside the two-label happy path.
  3. The printed limitation travels with the result so a copied log does not imply a broader performance claim.

Expected Result

Final fixture: 2/2; ['web', 'security']. Then Review and retrieval checks passed, followed by the synthetic-fixture limitation.

PROJECT STAGE 08 / 8

Finish an Honest AI Project

Builds on: Combine the dataset, representation, split, baseline, metrics, optional trained network, and source lookup.

  1. Write the selected-system decision before running final_check.py, then save the actual final output.
  2. Complete README.md with file roles, Python requirements, standard-library run commands, and separate optional PyTorch setup.
  3. Create system-card.md covering intended use, synthetic data, label ambiguity, evaluation counts, and known failure examples.
  4. Copy the source files to a fresh practice folder and follow the README without relying on earlier conversation context.
  5. Propose a next dataset collection plan with permission, clearer labels, independent examples, and a new evaluation split before adding more model complexity.

Keep This Deliverable

A reproducible local study-note project with final checks, a system card, and an evidence-based next-step plan.

Check Your Build

  • The standard-library baseline and retrieval checks run without installing PyTorch.
  • The final report includes 2/2 and the synthetic two-example limitation together.
  • A fresh-folder run succeeds using only the documented files and commands.

Common Mistakes and Fixes

Publishing a perfect percentage without the dataset and denominator.
Report the exact counts and limitations beside the result.
Treating the reserved test as a permanent tuning dashboard.
Record when it was used and obtain fresh evaluation examples before further model selection.

Check Your Understanding

What is the strongest honest claim this finished project supports?

Reveal the explanation

You implemented and checked a small, reproducible classification-and-retrieval pipeline on defined synthetic fixtures. It demonstrates engineering understanding, not validated performance on arbitrary real study notes.

Ready to Move On?

A fresh-folder run reproduces the standard-library checks, and the 2/2 fixture score is always presented with its synthetic two-example limitation.

Open the learning resource

Project References

HACKTRONIAN_CLI // COMMAND PALETTE
QUICK_EXEC: