Build AI in five steps
Every project goes through the same five steps: preparation, & visualization, data , and model evaluation. Build a small spam filter in your and walk through all five.
The five steps
Whatever you build, a spam filter, a or a , the work follows the same five steps. The size of the and the changes; the order of the work does not.
In this course you build a small AI that tells spam messages from normal ones. The data comes from three different places, each in a different format. You will join them, look at them, clean them, teach a model and then score it honestly.
Each step is one short notebook in JupyterLab, right on this page. You run the cell by cell, read what it prints and change it. Each notebook reads the files that the step before it made, and writes new files for the next step.
The five steps
- Data preparation 1-prepare.ipynb
- & visualization 2-analyze.ipynb
- Data 3-preprocess.ipynb
- Model 4-train.ipynb
- Model evaluation 5-evaluate.ipynb
Back to step 1 when the evaluation shows what to fix
The steps make a . After the evaluation you look at the wrong answers, decide on one thing to change, and go round again. You change only one thing per round, so you know what made the score better or worse.
Workflow — what each step makes and when to move on
Move to the next step only when the in the last column is true. If it is not, the problem is in this step, not in a later one.
| Step | Makes | Move on when | |
|---|---|---|---|
| Data preparation |
1-prepare.ipynb
|
data/all.csv
|
The total equals the rows of the three raw files |
| Data analysis & visualization |
2-analyze.ipynb
|
notes.md
|
The cleaning rules are written in notes.md |
| Data preprocessing |
3-preprocess.ipynb
|
data/train.csv · valid.csv · test.csv · vocab.json
|
No text is in two parts (overlap 0) |
| Model training |
4-train.ipynb
|
model.json
|
The went down and model.json is saved |
| Model evaluation |
5-evaluate.ipynb
|
—
|
The scores, the comparison and one next change are written |
The project folder
Everything happens in one folder, basic/, in JupyterLab. The raw data in assets/ and one notebook per step are ready when JupyterLab opens. Each notebook holds the finished code of its step, split into cells: run a cell, read what it prints, then change it and run it again.
basic/
├── assets/ raw data (do not edit)
│ ├── sms.csv message,is_spam (1 / 0)
│ ├── mail.tsv body⇥category (spam / ham)
│ └── chat.jsonl {"text": …, "label": "yes" / "no"}
├── data/ files your programs make
├── 1-prepare.ipynb ①
├── 2-analyze.ipynb ②
├── 3-preprocess.ipynb ③
├── 4-train.ipynb ④
└── 5-evaluate.ipynb ⑤
Why only plain Python
This course uses only the Python (csv, , random, math and collections), so every line runs in the Python inside your and you can see each calculation.
In real projects the same five steps are done with tools: pandas and for data, seaborn and matplotlib for charts, for splitting and classic models, and Keras or for . Each step below shows which tool does the same job, so you can switch to the tools once you understand the .
Type and try
JupyterLab opens next to the lessons (below them on a narrow screen). Look at the raw data first: in the file browser, open basic/assets and double-click each file. Notice that each file stores the text and the answer (spam or not) in a different way.
Done when
You can name the five steps in order, and you can say which file each step makes. You have opened all three raw files in JupyterLab.
If you get stuck
If JupyterLab stays blank, wait a few seconds: Python is downloaded the first time (about 30 ). If you cannot see basic/, click the folder icon at the top left. Never edit the files in assets/: they are the original data, and every step reads from them again when you change something.
Data preparation
Data rarely comes from one place. Here the messages are in three files with different formats:
- (sms.csv): a text file whose columns are separated by commas. opens it as a table.
- TSV (mail.tsv): a text file whose columns are separated by tabs.
- (chat.jsonl): JSON writes data as "name": value pairs inside { }. This file has one JSON object on each line.
Each file names its columns differently and writes the answer differently.
Data preparation means gathering everything into one common format, without changing the content yet. Cleaning comes later, in step 3, after you have looked at the data in step 2. If you clean now, you may throw away something you have not understood yet.
The logic, step by step
-
Read each file csv · json
-
Rename to common columns text · label · source
-
Count the rows (rows)
-
Save one table data/all.csv
csv.DictReader reads a CSV file row by row as a , so r["message"] is the message column. For the TSV file, delimiter="\t" tells it that a tab separates the columns. The JSONL file is read one line at a time with json.loads.
Every row becomes {"text": …, "label": …, "source": …}. The label is copied as it is, so 1, spam and yes all stay different for now. The source column remembers where each row came from; you will need it to compare the sources in step 2.
The same job with real-world tools
With pandas, each file is one read call, and pd.concat stacks them into one table.
pd.read_csv()pd.read_json(lines=True)pd.concat()df.to_csv()
Type and try
Open 1-prepare.ipynb and run the cells one by one with Shift+Enter. After the last cell, open data/all.csv in the file browser and look at the table it made.
1-prepare.ipynbThe full code of this notebook
# Step 1. Data preparation — read three sources and save them in one common format.
import csv
import json
import os
rows = []
# sms.csv: columns message, is_spam (1 or 0)
with open("assets/sms.csv", newline="", encoding="utf-8") as f:
for r in csv.DictReader(f):
rows.append({"text": r["message"], "label": r["is_spam"], "source": "sms"})
# mail.tsv: columns body, category (spam or ham), separated by tabs
with open("assets/mail.tsv", newline="", encoding="utf-8") as f:
for r in csv.DictReader(f, delimiter="\t"):
rows.append({"text": r["body"], "label": r["category"], "source": "mail"})
# chat.jsonl: one JSON object per line, keys text and label (yes or no)
with open("assets/chat.jsonl", encoding="utf-8") as f:
for line in f:
r = json.loads(line)
rows.append({"text": r["text"], "label": r["label"], "source": "chat"})
print("rows by source")
for source in ["sms", "mail", "chat"]:
count = sum(1 for r in rows if r["source"] == source)
print(f" {source:5} {count}")
print("total", len(rows))
os.makedirs("data", exist_ok=True)
with open("data/all.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["text", "label", "source"])
writer.writeheader()
writer.writerows(rows)
print("saved data/all.csv")
Run ▸ Run All CellsWhat you should see
rows by source
sms 65
mail 59
chat 59
total 183
saved data/all.csv
Done when
The notebook prints 65 rows for sms, 59 for mail and 59 for chat, 183 in total. Check this against the raw files: in a new cell, len(open("assets/sms.csv").readlines()) counts the lines of a file, and a CSV or TSV file has one extra line for the column names. Not one row may be lost or added.
If you get stuck
: 'message' means the column name does not match the first line of the file; open assets/sms.csv and compare. means the notebook is not in the basic/ folder; open it from basic/ in the file browser.
Data analysis & visualization
Before you change anything, look. Analysis answers simple questions: How many rows are there? Is any text empty? How does each source write its labels? How long are the messages? Is the same message there twice?
Visualization turns the numbers into a picture so you can see a problem at a glance. Here the charts are drawn with block characters right in the cell output: the longer the bar, the bigger the number.
The result of this step is not a file of data but a short of rules. Each rule comes from something you saw.
The logic, step by step
-
Find empty text text == ""
-
Count labels per source Counter
-
Draw bar charts █ bar()
-
Find duplicates n > 1
-
Write the rules notes.md
Counter counts how often each value appears. Grouping by source shows that sms writes 1 and 0, mail writes ham and spam (and sometimes SPAM or Spam), and chat writes yes and no.
The bar draws value / largest value × 30 blocks, so the largest bar is always 30 blocks long. The spam ratio chart uses a temporary rule to turn the labels into spam or not; the real rule is written in step 3.
For duplicates, each text is first made lower case with single spaces, so "See you at lunch" and "see you at lunch" count as the same message.
The same job with real-world tools
With pandas, isnull().sum() finds empty values, describe() gives the statistics, pivot_table() makes the label table, and seaborn draws the charts.
df.isnull().sum()df.describe()df.pivot_table()sns.countplot()sns.barplot()
Type and try
Open 2-analyze.ipynb and choose Run ▸ Run All Cells. Then write what you found as rules in a new file: File ▸ New ▸ File, renamed to notes.md.
2-analyze.ipynbThe full code of this notebook
# Step 2. Data analysis and visualization — look at the data with numbers and bar charts.
import csv
from collections import Counter
with open("data/all.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
def bar(name, value, top, width=30):
"""One line of a bar chart drawn with text."""
print(f" {name:8} {'█' * round(value / top * width)} {value}")
print("rows:", len(rows))
# 1) Missing values: rows whose text is empty
empty = [r for r in rows if r["text"].strip() == ""]
print("empty text:", len(empty))
# 2) Rows by source (chart)
print("\nrows by source")
by_source = Counter(r["source"] for r in rows)
for source, count in by_source.items():
bar(source, count, max(by_source.values()))
# 3) Label values by source — every source writes the label differently
print("\nlabel values by source")
for source in by_source:
labels = Counter(r["label"] for r in rows if r["source"] == source)
print(f" {source:5}", dict(labels))
# 4) Spam ratio by source (chart, with a temporary label rule)
print("\nspam ratio by source (%)")
for source in by_source:
part = [r for r in rows if r["source"] == source]
spam = sum(1 for r in part if r["label"].lower() in ("1", "spam", "yes"))
bar(source, round(spam / len(part) * 100), 100)
# 5) Text length (chart)
lengths = [len(r["text"]) for r in rows if r["text"].strip()]
print("\ntext length: min", min(lengths), "avg", round(sum(lengths) / len(lengths)), "max", max(lengths))
groups = Counter(min(n // 20, 4) for n in lengths)
names = ["0-19", "20-39", "40-59", "60-79", "80+"]
for g in range(5):
bar(names[g], groups[g], max(groups.values()))
# 6) Duplicates: the same text more than once
texts = Counter(" ".join(r["text"].lower().split()) for r in rows if r["text"].strip())
duplicates = {t: n for t, n in texts.items() if n > 1}
print("\nduplicate texts:", len(duplicates))
for text, n in duplicates.items():
print(f" {n}x {text}")
Run ▸ Run All CellsWhat you should see
rows: 183
empty text: 3
rows by source
sms ██████████████████████████████ 65
mail ███████████████████████████ 59
chat ███████████████████████████ 59
label values by source
sms {'1': 28, '0': 37}
mail {'ham': 33, 'spam': 24, 'SPAM': 1, 'Spam': 1}
chat {'no': 32, 'yes': 27}
spam ratio by source (%)
sms █████████████ 43
mail █████████████ 44
chat ██████████████ 46
text length: min 1 avg 39 max 82
0-19 ███████ 17
20-39 ██████████████████████████████ 75
40-59 ██████████████████████████████ 74
60-79 █████ 13
80+ 1
duplicate texts: 3
3x congratulations! you won a free iphone. click the link to claim it now
3x see you at lunch
2x call me now
Done when
Your notes.md has at least these four rules, each based on a number you saw:
- Drop empty and very short texts (3 empty texts, the shortest text is 1 character).
- Turn every label into 1 (spam) or 0 (not spam): 1, spam, yes and 0, ham, no, ignoring upper and lower case.
- Keep one copy of a duplicated text, and drop a text that has different labels ("call me now" is spam in one source and normal in another).
- Split the data so that each part has about the same spam ratio (it is about 45% in every source).
If you get stuck
If the bars look broken, the font may be missing the block character; the numbers at the end of each bar are what count. If you see no duplicates, check that you lower-cased the text before counting. FileNotFoundError for data/all.csv means 1-prepare.ipynb has not been run yet.
Data preprocessing
Preprocessing turns raw data into data a model can learn from. Every action here comes from a rule you wrote in step 2, and the program prints the row count after each action, so you can see what each rule removed.
Two ideas matter most. First, the test data must stay completely unseen: if the same message is in both train and test, the score will look better than the model really is. Second, anything the model learns from, even the list of words, is built from the train part only.
The logic, step by step
-
Clean the text lower() · split()
-
Unify the labels 1 / 0
-
Remove duplicates set()
-
Split three ways 80 / 10 / 10
-
Words to numbers vocab.json
Cleaning makes the text lower case with one space between words and drops texts shorter than 3 characters. The labels become 1 or 0 using two sets of words; a label in neither set is dropped instead of guessed.
For duplicates, the program first collects every label each text has. A text with one label is kept once; a text with two different labels is dropped, because nobody knows the right answer.
The split shuffles spam and normal rows separately, with random.seed(42) so you get the same result every time, and takes 80% for train, 10% for valid and 10% for test from each group. This keeps the spam ratio the same in all three parts. Finally every word that appears at least twice in train gets a number: this word list (vocab.json) is how text becomes numbers.
The same job with real-world tools
With pandas and scikit-learn: dropna and drop_duplicates clean the table, train_test_split(stratify=…) splits it keeping the ratio, and TfidfVectorizer turns text into numbers.
df.dropna()df.drop_duplicates()train_test_split(stratify=…)TfidfVectorizer
Type and try
Open 3-preprocess.ipynb and run it cell by cell. Each cell is one rule: read the row count it prints and match it with your notes.
3-preprocess.ipynbThe full code of this notebook
# Step 3. Data preprocessing — clean, unify, remove duplicates, split, and turn text into numbers.
import csv
import json
import random
from collections import Counter
SPAM = {"1", "spam", "yes"}
HAM = {"0", "ham", "no"}
with open("data/all.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print("start", len(rows))
# 1) Clean: lower case, one space between words, drop texts shorter than 3 characters
for r in rows:
r["text"] = " ".join(r["text"].lower().split())
rows = [r for r in rows if len(r["text"]) >= 3]
print("after cleaning", len(rows))
# 2) Unify labels: every source becomes 1 (spam) or 0 (not spam)
for r in rows:
label = r["label"].strip().lower()
r["spam"] = 1 if label in SPAM else 0 if label in HAM else None
rows = [r for r in rows if r["spam"] is not None]
# 3) Duplicates: keep one row per text, drop texts that got different labels
labels = {}
for r in rows:
labels.setdefault(r["text"], set()).add(r["spam"])
seen = set()
unique = []
for r in rows:
if len(labels[r["text"]]) == 1 and r["text"] not in seen:
seen.add(r["text"])
unique.append(r)
print("after duplicates", len(unique))
# 4) Split 80 / 10 / 10, keeping the same spam ratio in each part (seed 42 = same result every time)
random.seed(42)
parts = {"train": [], "valid": [], "test": []}
for value in (0, 1):
group = [r for r in unique if r["spam"] == value]
random.shuffle(group)
a, b = round(len(group) * 0.8), round(len(group) * 0.9)
parts["train"] += group[:a]
parts["valid"] += group[a:b]
parts["test"] += group[b:]
for name, part in parts.items():
spam = sum(r["spam"] for r in part)
print(f"{name:5} {len(part):3} rows, spam {spam}")
with open(f"data/{name}.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["text", "spam"], extrasaction="ignore")
writer.writeheader()
writer.writerows(part)
# Check: no text may be in two parts
train_texts = {r["text"] for r in parts["train"]}
overlap = sum(1 for r in parts["valid"] + parts["test"] if r["text"] in train_texts)
print("overlap", overlap)
# 5) Text to numbers: give each word a number, using the train part only
counts = Counter(w for r in parts["train"] for w in r["text"].split())
words = sorted(w for w, n in counts.items() if n >= 2)
vocab = {w: i for i, w in enumerate(words)}
with open("data/vocab.json", "w", encoding="utf-8") as f:
json.dump(vocab, f, indent=1)
print("vocabulary", len(vocab), "words")
Run ▸ Run All CellsWhat you should see
start 183
after cleaning 178
after duplicates 172
train 137 rows, spam 62
valid 18 rows, spam 8
test 17 rows, spam 8
overlap 0
vocabulary 147 words
Done when
The counts go 183 → 178 → 172, the parts are train 137, valid 18 and test 17, and overlap is 0. The has 147 words.
If you get stuck
If overlap is not 0, the duplicates were removed after the split instead of before it. If the counts differ from the numbers above, run 1-prepare.ipynb again, then this notebook from the top with Run ▸ Run All Cells.
Model training
Always start with the simplest possible answer, a baseline. Here it is "always say not spam". Any model you build must beat it, or it is not worth using.
The learning model gives every word a . Spam-like words get a positive weight and normal words a negative one. To judge a message, the model adds up the weights of its words and a bias, then squashes the total into a between 0 and 1.
Training means showing the model every example many times and nudging the weights a little after each guess. The loss measures how wrong the guesses are; it must go down.
The logic, step by step
-
Make a baseline most common
-
Turn text into word numbers features()
-
Guess a probability
-
Nudge the weights weight -= rate × error
-
Save the model model.json
features() turns a message into the numbers of its known words, using vocab.json from step 3. The guess is p = 1 / (1 + e^-(bias + sum of the word weights)); this sigmoid turns any total into a probability.
error = p − y is how wrong the guess was (y is the real answer, 1 or 0). Each weight of a word in the message moves by rate × error in the opposite direction, so the next guess is a little closer. One pass over all the is an ; this program runs 20 epochs.
The weights and bias are saved in model.json. That file is the model: the numbers it learned.
The same job with real-world tools
With scikit-learn this is LogisticRegression().fit(X, y). Deep learning models (Keras Dense layers, or a written in PyTorch) are trained in the same way: guess, measure the loss, nudge the weights.
LogisticRegression().fit()keras Sequential · DensePyTorch
Type and try
Open 4-train.ipynb and run all cells. Watch the loss after each group of epochs, then look at the words the model finds most spam-like and most normal. Change rate and run the training cell again to see what happens.
4-train.ipynbThe full code of this notebook
# Step 4. Model training — a baseline rule first, then a small learning model (logistic regression).
import csv
import json
import math
import random
with open("data/vocab.json", encoding="utf-8") as f:
vocab = json.load(f)
with open("data/train.csv", newline="", encoding="utf-8") as f:
train = [(r["text"], int(r["spam"])) for r in csv.DictReader(f)]
def features(text):
"""Text -> numbers: the numbers of the known words in the text."""
return [vocab[w] for w in dict.fromkeys(text.split()) if w in vocab]
# 1) Baseline: always answer the most common label
spam = sum(y for _, y in train)
baseline = 1 if spam > len(train) - spam else 0
print("baseline answer:", baseline)
# 2) Logistic regression: one weight per word + bias -> probability of spam
weights = [0.0] * len(vocab)
bias = 0.0
rate = 0.3
data = [(features(text), y) for text, y in train]
random.seed(42)
for epoch in range(1, 21):
random.shuffle(data)
total = 0.0
for x, y in data:
p = 1 / (1 + math.exp(-(bias + sum(weights[i] for i in x))))
p = min(max(p, 1e-9), 1 - 1e-9)
total += -(y * math.log(p) + (1 - y) * math.log(1 - p))
error = p - y # how wrong the guess was
bias -= rate * error
for i in x:
weights[i] -= rate * error
if epoch == 1 or epoch % 5 == 0:
print(f"epoch {epoch:2} loss {total / len(data):.4f}")
with open("model.json", "w", encoding="utf-8") as f:
json.dump({"baseline": baseline, "bias": bias, "weights": weights}, f)
print("saved model.json")
words = sorted(vocab, key=lambda w: weights[vocab[w]])
print("spam words:", ", ".join(words[-5:][::-1]))
print("normal words:", ", ".join(words[:5]))
Run ▸ Run All CellsWhat you should see
baseline answer: 0
epoch 1 loss 0.4373
epoch 5 loss 0.0944
epoch 10 loss 0.0481
epoch 15 loss 0.0322
epoch 20 loss 0.0241
saved model.json
spam words: message, now, confirm, here, your
normal words: the, is, are, remember, home
Done when
The loss goes down from about 0.44 to about 0.02, model.json is saved, and the spam words make sense (for example now, confirm, here, your).
If you get stuck
If the loss goes up or jumps around, the rate is too large; try 0.1. If you see math error, check the minus sign in math.exp(-(…)).
Model evaluation
A model is only as good as its score on data it has never seen. You use the valid part while you are still changing things, and the test part only once, at the very end.
Accuracy alone can fool you. The baseline gets more than half right just by saying "not spam" every time, yet it never catches a single spam message. That is why spam filters look at two more numbers:
- Precision: of the messages the model called spam, how many really were spam.
- Recall: of the real spam messages, how many the model caught.
- F1 combines the two into one number.
Finally, read the wrong answers. They tell you what to change in the next round.
The logic, step by step
-
Predict spam or not p ≥ 0.5
-
Count the four cases tp · fp · fn · tn
-
Compute the scores accuracy · F1
-
Compare with the baseline baseline
-
Read the wrong answers wrong answers
A message is called spam when the probability is 0.5 or more. Each answer then falls into one of four cases: tp (spam, called spam), fp (normal, called spam), fn (spam, called normal) and tn (normal, called normal). This is the confusion table.
accuracy = (tp + tn) / all, precision = tp / (tp + fp), recall = tp / (tp + fn), and F1 = 2 × precision × recall / (precision + recall). The program computes the same scores for the baseline and uses the model only if its F1 is higher.
The same job with real-world tools
scikit-learn has a ready function for every score here, and confusion_matrix builds the four-case table.
accuracy_scoreprecision_scorerecall_scoref1_scoreconfusion_matrix
Type and try
Open 5-evaluate.ipynb and run all cells on the valid part. Read the wrong answers and write one change to try next in notes.md. Only when you are finished, change part = "valid" to part = "test" and run everything once more.
5-evaluate.ipynbThe full code of this notebook
# Step 5. Model evaluation — score the model on data it never saw, and compare it with the baseline.
import csv
import json
import math
part = "valid" # change to "test" only once, at the very end
with open("data/vocab.json", encoding="utf-8") as f:
vocab = json.load(f)
with open("model.json", encoding="utf-8") as f:
model = json.load(f)
with open(f"data/{part}.csv", newline="", encoding="utf-8") as f:
rows = [(r["text"], int(r["spam"])) for r in csv.DictReader(f)]
def predict(text):
x = [vocab[w] for w in dict.fromkeys(text.split()) if w in vocab]
p = 1 / (1 + math.exp(-(model["bias"] + sum(model["weights"][i] for i in x))))
return 1 if p >= 0.5 else 0
def scores(answers):
tp = sum(1 for (_, y), a in zip(rows, answers) if y == 1 and a == 1)
fp = sum(1 for (_, y), a in zip(rows, answers) if y == 0 and a == 1)
fn = sum(1 for (_, y), a in zip(rows, answers) if y == 1 and a == 0)
tn = sum(1 for (_, y), a in zip(rows, answers) if y == 0 and a == 0)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return {"accuracy": (tp + tn) / len(rows), "precision": precision, "recall": recall, "f1": f1, "table": (tp, fp, fn, tn)}
model_answers = [predict(text) for text, _ in rows]
base = scores([model["baseline"]] * len(rows))
mine = scores(model_answers)
print(f"{part}: {len(rows)} rows")
print(f"{'':10} {'baseline':>9} {'model':>7}")
for key in ("accuracy", "precision", "recall", "f1"):
print(f"{key:10} {base[key]:9.3f} {mine[key]:7.3f}")
tp, fp, fn, tn = mine["table"]
print("\nconfusion table said spam said normal")
print(f" really spam {tp:9} {fn:11}")
print(f" really normal {fp:9} {tn:11}")
print("\nwrong answers")
for (text, y), a in zip(rows, model_answers):
if y != a:
print(f" answer {y}, model {a}: {text}")
print("\nuse the model" if mine["f1"] > base["f1"] else "\nkeep the baseline")
Run ▸ Run All CellsWhat you should see
valid: 18 rows
baseline model
accuracy 0.556 0.778
precision 0.000 1.000
recall 0.000 0.500
f1 0.000 0.667
confusion table said spam said normal
really spam 4 4
really normal 0 10
wrong answers
answer 1, model 0: dear friend i need your help to move my money. you will get a share
answer 1, model 0: we are hiring. work two hours a day and earn more
answer 1, model 0: make money fast. join my team now
answer 1, model 0: exclusive discount for our best customers. click the link
use the model
Done when
On valid, the model scores F1 0.667 against the baseline's 0.000, so the program says to use the model. Recall is only 0.5: it misses spam that uses words it has not learned, such as money, hiring and share. You have written one change for the next round, for example more spam examples of that kind or keeping words that appear only once.
If you get stuck
ZeroDivisionError means a part has no spam or the model called nothing spam; the program guards precision and recall for this. If your scores differ, run notebooks 3 and 4 again before 5, because each step reads the files of the one before.