SONUB home

Only our team reads this. Don't include passwords or card numbers.

Thank you! We read every message and use it to decide what to improve next.

Close Send
EN English 한국어 日本語 简体中文 繁體中文 हिन्दी বাংলা اردو Español Português Français Deutsch Русский العربية Bahasa Indonesia Tiếng Việt ไทย Türkçe

How to enable notifications

Notifications are unavailable in this browser or on this address. Try a supported browser on the secure SONUB site.

If notifications are blocked, allow them in your browser settings.

  1. Open the site controls beside the address bar, or your browser’s site settings. Set Notifications for this site to Allow.
  2. In your device settings, allow notifications for your browser and check Do Not Disturb or Focus.
  3. Return to SONUB and reload the page. Once notifications are on, the bell disappears.

On iPhone or iPad, add SONUB to your Home Screen, open it there, then allow notifications.

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.

Messy pieces of writing go into a filter machine, duplicates and scraps fall out, and a neat stack of clean data comes out
3

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

  1. Clean the text lower() · split()
  2. Unify the labels 1 / 0
  3. Remove duplicates set()
  4. Split three ways 80 / 10 / 10
  5. 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.

Booking time has passed