What is data science, and how do I use this guide?
Data science is using data to answer questions and make better decisions. A shop asks "which products will sell next month?", a hospital asks "which patients need attention first?", a bank asks "is this payment fraud?". A data scientist collects the data, cleans it, looks for patterns, builds a model (a recipe that learned from past examples) and checks whether it can be trusted.
How each module works
- In plain words (purple box): the idea explained with an everyday example. Read this first.
- Dotted words: tap or hover for a one-line definition. The full list is in the Glossary tab.
- Try it (dashed boxes): drag sliders and click to see the idea work.
- Python example (dark boxes): real code you can copy, with the output it produced. Every example that shows an output was actually run to produce it.
- Check yourself: short quizzes at the end of each module.
Beginner view
Beginner view (switch at the top) folds the Python examples closed and hides the correction notes, so you can focus on ideas. Tap any "Python example" bar to open it, or switch to Full detail to open them all.
You don't need to know programming or maths to start. Formulas are always explained in words next to them.
The learning path
- Frame & prepare dataModules 01–07: the project lifecycle, installing Python, Python basics, SQL, pandas, databases, exploring and cleaning data
- Reason with numbersModules 08–13: maths, probability, hypothesis tests, A/B tests, correlation
- Build & ship modelsModules 14–20: regression, classic ML, validation, metrics, forecasting, deployment
- Deep learningModules 21–23: neural networks and image models
- Generative AIModules 24–32: LLMs, token costs, Hugging Face, RAG, enterprise AI, Jev, interview prep, career roadmap
The data science lifecycle, end to end
Every data science project follows roughly the same loop: understand the problem, get the data, clean it, explore it, build a model, check that it works, put it to use, then watch it and improve it. Most of the time goes into the early steps (problem and data), not the model. The industry standard name for this loop is CRISP-DM.
Everyday example: A doctor listens (problem), runs tests (data), reads results (explore), diagnoses (model), checks the treatment worked (evaluate), and follows up (monitor).
Explore the lifecycle
InteractiveClick a stage to see what happens there, the questions to ask, the tools used, and which modules teach it.
Framing the problem well
Turn a wish into a question
- Vague: "Use AI to reduce churn."
- Precise: "Each month, rank current customers by their chance of cancelling in the next 30 days, so the retention team can call the top 500."
- This fixes the target (cancels within 30 days), the unit (customer-month), the action (calls) and the budget (500).
Pick metrics before modelling
- Business metric: customers retained, money saved.
- Model metric: recall in the top 500, ROC-AUC.
- Baseline: what happens with no model (e.g. call customers at random, or those with the most complaints). A model must beat it.
Types of ML problem
- Regression: predict a number (price, demand).
- Classification: predict a category (churn yes/no, spam).
- Clustering: find groups with no labels (segments).
- Forecasting: predict future values in time order.
- Ranking / recommendation: order items for each user.
- Generation: produce text, images or code (LLMs).
Roles on a data team
- Data analyst: reporting, dashboards, answering "what happened".
- Data scientist: experiments, statistics, predictive models.
- Data engineer: pipelines, warehouses, data quality.
- ML / AI engineer: deploying and running models and LLM apps.
Ethics belongs in every stage: check whether the data is representative, whether the model treats groups fairly, whether personal data is protected, and whether people affected can get a decision explained.
Python example A complete mini project: predict customer churn
# End-to-end mini project: predict which customers will cancel (churn) import numpy as np, pandas as pd from sklearn.model_selection import train_test_split from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, roc_auc_score import joblib # 1. Data (synthetic here; normally pd.read_csv or SQL) rng = np.random.default_rng(0) n = 2000 df = pd.DataFrame({ "tenure_months": rng.integers(1, 72, n), "monthly_bill": rng.normal(60, 20, n).round(2), "support_calls": rng.poisson(1.5, n), "contract": rng.choice(["monthly", "yearly"], n, p=[0.6, 0.4]), }) risk = -2 + 0.6*df.support_calls - 0.04*df.tenure_months + 1.2*(df.contract == "monthly") df["churned"] = (rng.random(n) < 1/(1+np.exp(-risk))).astype(int) df.loc[rng.choice(n, 50, replace=False), "monthly_bill"] = np.nan # some missing values # 2. Explore print(df.shape, "| churn rate:", round(df.churned.mean(), 3)) print(df.isna().sum()[df.isna().sum() > 0].to_dict()) # 3. Split BEFORE any fitting, to avoid leakage X, y = df.drop(columns="churned"), df.churned X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42) # 4. Preprocess + model in one pipeline num = ["tenure_months", "monthly_bill", "support_calls"] prep = ColumnTransformer([ ("num", Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), num), ("cat", OneHotEncoder(handle_unknown="ignore"), ["contract"]), ]) model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))]) model.fit(X_tr, y_tr) # 5. Evaluate on the untouched test set proba = model.predict_proba(X_te)[:, 1] print("ROC-AUC:", round(roc_auc_score(y_te, proba), 3)) print(classification_report(y_te, model.predict(X_te), digits=2)) # 6. Save for deployment joblib.dump(model, "churn_model.joblib") new = pd.DataFrame([{"tenure_months": 3, "monthly_bill": 80, "support_calls": 4, "contract": "monthly"}]) print("Churn risk for a new customer:", round(model.predict_proba(new)[0, 1], 2))
(2000, 5) | churn rate: 0.188
{'monthly_bill': 50}
ROC-AUC: 0.77
precision recall f1-score support
0 0.84 0.98 0.91 325
1 0.73 0.21 0.33 75
accuracy 0.84 400
macro avg 0.79 0.60 0.62 400
weighted avg 0.82 0.84 0.80 400
Churn risk for a new customer: 0.81
The ROC-AUC of 0.77 is decent, but recall for churners is only 0.21 at the default 0.5 threshold: the model misses most leavers. Module 17 shows the fix (class weights, a lower threshold).
Install Python and set up your environment
To run the examples in this guide you need three things: Python itself, a virtual environment (a private box of libraries for each project, so projects don't break each other), and an editor to write and run code. Setup takes about 20 minutes, once. If you want to skip installing entirely, use Google Colab in your browser.
Everyday example: A virtual environment is like a separate toolbox for each job. Upgrading the hammer in the plumbing box doesn't change the one in the carpentry box.
Option A · No install (fastest start)
- Open colab.research.google.com and sign in with a Google account.
- Click New notebook, paste an example, press Shift + Enter.
- Most libraries (pandas, scikit-learn, TensorFlow, PyTorch) are already installed. Add others with
!pip install langgraph.
Good for learning. For real projects, install locally (Option B).
Which Python version?
- The newest release on python.org is 3.14 (as of September 2026).
- For data science, 3.12 or 3.13 is the safest choice: big libraries such as TensorFlow sometimes take months to support the newest version.
- You can have several versions installed; each virtual environment uses one.
Option B · Install on your computer
Setup steps for your computer
InteractivePick an editor
| Editor | Best for | How to start |
|---|---|---|
| VS Code | Scripts and notebooks in one place; the most common choice | Install VS Code, add the Python and Jupyter extensions, open your project folder, then Python: Select Interpreter → choose .venv |
| JupyterLab | Step-by-step analysis with charts next to code | python -m pip install jupyterlab then jupyter lab (inside your activated environment) |
| PyCharm | Larger Python projects | New Project → "Virtualenv" interpreter |
| Google Colab | No install, free GPU for small experiments | colab.research.google.com |
Running code
A script (.py file)
- Save the code as
hello.pyin your project folder. - Activate the environment.
- Run
python hello.pyin the terminal.
A notebook (.ipynb)
- Create a notebook in VS Code or JupyterLab and choose the
.venvkernel. - Paste code into a cell.
- Press Shift + Enter; the output appears below the cell.
Libraries for this guide
python -m pip install numpy pandas scipy scikit-learn statsmodels matplotlib seaborn jupyterlab
Later modules: langgraph, transformers, sentence-transformers faiss-cpu, keras tensorflow or torch, tiktoken, fastapi uvicorn.
Keep API keys secret
- Never paste keys into code or notebooks you share.
- Put them in a
.envfile (add it to.gitignore):ANTHROPIC_API_KEY=... - Load with
python-dotenv:from dotenv import load_dotenv; load_dotenv(). The official SDKs read the key from the environment automatically.
When something goes wrong
| Error | Why | Fix |
|---|---|---|
'python' is not recognized (Windows) | Python isn't on PATH | Use py instead of python, or reinstall and tick "Add python.exe to PATH" |
command not found: python (Mac/Linux) | The command is named python3 | Use python3; inside an activated venv, python works |
ModuleNotFoundError: No module named 'pandas' | Installed in a different environment, or not at all | Activate the venv, then python -m pip install pandas. In VS Code/Jupyter, select the .venv interpreter/kernel |
error: externally-managed-environment | The system Python is protected (Mac Homebrew, newer Linux) | Create and activate a virtual environment first |
| Activation blocked in PowerShell | Script execution policy | Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, or use Command Prompt |
| Wrong library version / conflicts | Shared global installs | One venv per project, and pin versions in requirements.txt |
Use python -m pip install … rather than plain pip install …. It guarantees the library goes into the Python you are actually running.
Python example Check that your setup works
# check_setup.py: run this after installing to confirm your environment works import sys, importlib print("Python", sys.version.split()[0], "at", sys.executable) print("Inside a virtual environment:", sys.prefix != sys.base_prefix) for pkg in ["numpy", "pandas", "scipy", "sklearn", "matplotlib", "seaborn", "statsmodels"]: try: m = importlib.import_module(pkg) print(f" OK {pkg:12s} {getattr(m, '__version__', '')}") except ImportError: print(f" MISSING {pkg:12s} -> python -m pip install {'scikit-learn' if pkg == 'sklearn' else pkg}")
Python 3.11.15 at /usr/bin/python3 Inside a virtual environment: False OK numpy 2.4.4 OK pandas 3.0.2 OK scipy 1.17.1 OK sklearn 1.8.0 OK matplotlib 3.10.9 OK seaborn 0.13.2 OK statsmodels 0.15.0
Output from the machine that built this guide; your paths and versions will differ. "Inside a virtual environment: True" is what you want to see.
Python basics and the Python ecosystem
Python is the language most data scientists use. You write short instructions, and Python carries them out line by line. On its own it handles numbers, text, lists and files. Add a library (a toolbox someone else wrote, like pandas or scikit-learn) and the same few lines can clean a million rows or train a model.
Everyday example: Python is a kitchen; libraries are appliances. You learn to use the kitchen once, then plug in a blender (pandas) or an oven (PyTorch) as the recipe needs.
The 20 concepts a data analyst uses daily
| Concept | What it's for | Syntax |
|---|---|---|
| Variables & data types | Store numbers, text, true/false | x = 10; name = "John"; is_valid = True |
| Lists | Ordered, changeable collection | data = [1, 2, 3] |
| Tuples | Ordered, fixed collection (coordinates) | coords = (10, 20) |
| Sets | Unique values; fast "is it in here?" checks | ids = {1, 2, 3} |
| Dictionaries | Key → value pairs; JSON and API data | user = {"name": "John", "age": 25} |
| If / else | Decisions | if x > 10: print("High") |
| Loops | Repeat for each item | for item in data: print(item) |
| Functions | Reusable logic | def add(a, b): return a + b |
| List comprehensions | Filter and transform a list in one line | [x*2 for x in data if x > 5] |
| Error handling | Keep pipelines running when data is bad | try: int(a) except ValueError: ... |
| File handling | Read and write files safely | with open("file.txt") as f: text = f.read() |
| NumPy arrays | Fast maths on many numbers | np.array([1, 2, 3]) |
| pandas DataFrame | Tables | df = pd.read_csv("file.csv") |
| Filtering | Select rows | df[df["age"] > 25] |
| Group by | Totals per group (KPIs) | df.groupby("region")["sales"].sum() |
| Merging | Join tables like SQL | pd.merge(df1, df2, on="id") |
| Apply | Custom logic per value | df["col"].apply(lambda x: x*2) |
| Matplotlib | Basic charts | import matplotlib.pyplot as plt; plt.plot(x, y) |
| Seaborn | Statistical charts, heatmaps | sns.heatmap(df.corr()) |
import matplotlib..pyplot (one dot: matplotlib.pyplot) and syntort pandas as pd (should be import pandas as pd).The Python ecosystem: which library for which job
| Job | Library |
|---|---|
| Data analysis | pandas (tables), NumPy (numbers), Polars / PySpark (big data) |
| Visualisation | Matplotlib, Seaborn, Plotly |
| Machine learning | scikit-learn, XGBoost |
| Deep learning | PyTorch, TensorFlow / Keras |
| Computer vision / NLP | OpenCV / NLTK, spaCy, Hugging Face Transformers |
| AI agents and LLM apps | LangChain, LangGraph, LlamaIndex |
| Apps and APIs | Streamlit (ML demo apps), FastAPI, Flask, Django (web) |
| Automation | Airflow (workflows), Boto3 (AWS), Selenium (browsers), BeautifulSoup (web scraping) |
| Desktop apps | Kivy |
Getting started: install Python via Anaconda or python.org, then work in Jupyter or Google Colab (Colab needs no installation). Run each example in this guide and change one thing at a time to see what happens.
Lambda functions
A lambda is a tiny, nameless function written on one line. Use it when you need a quick rule just once, typically inside map(), filter(), sorted() or pandas apply(). If the logic needs several steps, write a normal def function instead.
Everyday example: A sticky note saying "sort by age" instead of writing a full instruction manual.
| Use | Code | Result |
|---|---|---|
Syntax: lambda args: expression | square = lambda x: x * x; square(5) | 25 |
| Several parameters | add = lambda a, b: a + b; add(10, 20) | 30 |
| Returns the expression automatically | is_even = lambda n: n % 2 == 0 | is_even(4) → True |
Transform each item: map() | list(map(lambda x: x * x, [1, 2, 3, 4])) | [1, 4, 9, 16] |
Keep matching items: filter() | list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])) | [2, 4] |
Custom sort: sorted(key=...) | sorted(["apple", "banana", "kiwi"], key=lambda w: len(w)) | ['kiwi', 'apple', 'banana'] |
| Sort records by a field | sorted(employees, key=lambda e: e["age"]) | youngest first |
| pandas column rule | df["price"].apply(lambda p: "high" if p > 100 else "low") | a new label per row |
Lambda or def?
- lambda: one expression, used once, passed straight into another function.
- def: several statements, needs a name, a docstring, tests, or reuse.
def calculate(x, y): total = x + y; return total * 2can't be a lambda.
Good habits
- A list comprehension is often clearer than
map/filter:[x*x for x in nums if x % 2 == 0]. - Don't assign lambdas to names in real code (
square = lambda ...); style guides preferdef square(x):. It's fine for learning. - On large DataFrames, vectorised code (
np.where(df.price > 100, "high", "low")) is much faster thanapply(lambda …).
Python example Every lambda pattern from the sheet, plus pandas
square = lambda x: x * x # 1. syntax: lambda arguments: expression add = lambda a, b: a + b # 2. several parameters is_even = lambda n: n % 2 == 0 # 3. the expression's value is returned print(square(5), add(10, 20), is_even(4), is_even(5)) numbers = [1, 2, 3, 4, 5] print(list(map(lambda x: x * x, numbers))) # 4. transform every item print(list(filter(lambda x: x % 2 == 0, numbers))) # 5. keep items that match words = ["apple", "banana", "kiwi"] print(sorted(words, key=lambda w: len(w))) # 6. custom sort order employees = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}] print([e["name"] for e in sorted(employees, key=lambda e: e["age"])]) # 8. real-world sort # Same results, often clearer, with a comprehension print([x * x for x in numbers], [x for x in numbers if x % 2 == 0]) # In pandas, lambdas turn up in apply() import pandas as pd df = pd.DataFrame({"price": [120, 80, 300]}) df["band"] = df["price"].apply(lambda p: "high" if p > 100 else "low") print(df.to_dict("list"))
25 30 True False
[1, 4, 9, 16, 25]
[2, 4]
['kiwi', 'apple', 'banana']
['Bob', 'Alice', 'Charlie']
[1, 4, 9, 16, 25] [2, 4]
{'price': [120, 80, 300], 'band': ['high', 'low', 'high']}
All outputs match the source sheet.
Python example Python fundamentals in one script
# Core Python in 20 lines: the building blocks behind every analysis sales = [120, 340, 95, 410, 230] # list: ordered, changeable customer = {"name": "Asha", "city": "Pune"} # dict: key -> value point = (10, 20) # tuple: fixed, can't change cities = {"Pune", "Delhi", "Pune"} # set: duplicates removed print(type(sales).__name__, len(sales), "| set:", sorted(cities)) total = 0 for s in sales: # loop if s > 200: # condition total += s print("sum of big sales:", total) big = [s * 1.1 for s in sales if s > 200] # list comprehension print("with 10% uplift:", [round(b, 1) for b in big]) def summary(values, label="sales"): # function with a default argument return f"{label}: n={len(values)}, mean={sum(values)/len(values):.1f}" print(summary(sales)) try: # error handling rate = int("12%") except ValueError as e: print("could not convert:", e) with open("notes.txt", "w") as f: # file handling f.write("Asha,Pune\n") with open("notes.txt") as f: print("file says:", f.read().strip())
list 5 | set: ['Delhi', 'Pune'] sum of big sales: 980 with 10% uplift: [374.0, 451.0, 253.0] sales: n=5, mean=239.0 could not convert: invalid literal for int() with base 10: '12%' file says: Asha,Pune
Data wrangling: Excel, SQL, pandas and NumPy
Think of data as a giant spreadsheet. Data wrangling means tidying it: keeping the rows and columns you need, sorting, joining two lists by a shared ID, and filling in blanks. Excel does this by clicking. SQL and pandas do it by writing instructions, which work on millions of rows and can be re-run tomorrow with one command. NumPy is the fast number engine underneath pandas.
Everyday example: Matching your phone contacts to your call log using the phone number is a join.
Most of a data scientist's time goes into loading, filtering, joining and aggregating data. The same operation exists in all three tools; learn the mapping so you can move between them.
| Task | Excel | SQL | Python (pandas) |
|---|---|---|---|
| Load data | File › Open | SELECT * FROM t; | df = pd.read_csv("file.csv") |
| Filter rows | =FILTER(A2:B10, B2:B10>100) | WHERE col > 100 | df[df["col"] > 100] |
| Select columns | Column letters | SELECT c1, c2 | df[["c1","c2"]] |
| Sort | Data › Sort | ORDER BY col DESC | df.sort_values("col", ascending=False) |
| Group / aggregate | Pivot Table | SELECT dept, COUNT(*) … GROUP BY dept | df.groupby("dept").size() or .agg() |
| Count rows | =COUNTA(A2:A100) | SELECT COUNT(*) | len(df) / df.shape[0] |
| Mean / sum | =AVERAGE() =SUM() | AVG(x) SUM(x) | df["x"].mean() .sum() |
| Remove duplicates | Data › Remove Duplicates | SELECT DISTINCT … | df.drop_duplicates() |
| Join tables | XLOOKUP / VLOOKUP | A JOIN B ON A.id = B.id | pd.merge(df1, df2, on="id") |
| New column | =B2*0.1 | salary*0.1 AS bonus | df["bonus"] = df["salary"]*0.1 |
| Rename column | Edit header | col AS new_name | df.rename(columns={"old":"new"}) |
| Missing data | =IF(ISBLANK(A2),"N/A",A2) | IS NULL, COALESCE() | df.fillna("N/A") / df.dropna() |
| Export | Save As CSV/XLSX | Client export / INTO OUTFILE | df.to_csv("out.csv", index=False) |
| Visualize | Insert › Charts | Use a BI tool | df.plot(), seaborn, matplotlib |
Habits that save you later
- Prefer
df = df.rename(...)overinplace=True; it chains cleanly and is the direction pandas is heading. COUNT(*)counts rows;COUNT(col)skips NULLs. Same idea aslen(df)vsdf["col"].count().- Always check row counts before and after a join. A many-to-many key silently multiplies rows.
SQL clause order
Written: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
Executed: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
That is why a column alias from SELECT can't be used in WHERE, and why aggregates are filtered with HAVING.
NumPy essentials
pandas is built on NumPy. Arrays are fixed-type, n-dimensional and vectorised: one operation runs over every element without a Python loop.
| Task | Code | Result / note |
|---|---|---|
| Create | np.array([1, 2, 3]) | 1-D array |
| Zeros / ones / identity | np.zeros((2,3)), np.ones((2,3)), np.eye(3) | Shape passed as a tuple |
| Ranges | np.arange(0, 10, 2) · np.linspace(0, 1, 5) | [0 2 4 6 8] (stop excluded) · [0 .25 .5 .75 1] (stop included) |
| Random | rng = np.random.default_rng(42); rng.random((2,3)) | Modern API; older np.random.rand(2,3) still works |
| Inspect | arr.shape, arr.ndim, arr.dtype | Dimensions, number of axes, element type |
| Reshape | arr.reshape(3, 2), arr.reshape(-1, 1) | −1 = infer that axis; total size must match |
| Index / slice | arr[0, 1], arr[1:4], arr[:, 0] | Slices are views: editing them edits the original. Use .copy(). |
| Boolean mask | arr[arr > 0] | Filter elements; combine with &, | |
| Broadcasting | arr + 5, X - X.mean(axis=0) | Shapes align from the right; size-1 axes stretch |
| Aggregate | np.sum, np.mean, np.std, np.min/np.max | axis=0 down columns, axis=1 across rows |
| Position of extreme | np.argmax(arr) / np.argmin(arr) | Index, not value; used to turn softmax output into a class |
| Combine / split | np.concatenate((a,b)), np.vstack((a,b)), np.hstack, np.split(arr, 3) | split needs equal parts; array_split doesn't |
| Matrix multiply | A @ B | A * B is element-wise, not matrix multiplication |
np.std defaults to the population formula (ddof=0); pandas .std() defaults to the sample formula (ddof=1). The same column gives slightly different numbers in each.
Python example Join, filter and group with pandas
import pandas as pd orders = pd.DataFrame({"order_id": [1, 2, 3, 4, 5], "cust_id": [10, 11, 10, 12, 11], "amount": [250, 120, 90, None, 300]}) customers = pd.DataFrame({"cust_id": [10, 11, 12], "city": ["Pune", "Delhi", "Pune"]}) df = orders.merge(customers, on="cust_id", how="left") # JOIN df["amount"] = df["amount"].fillna(0) # missing -> 0 big = df[df["amount"] > 100] # WHERE amount > 100 print(big[["order_id", "city", "amount"]]) summary = (df.groupby("city")["amount"] # GROUP BY city .agg(orders="count", total="sum", avg="mean") .sort_values("total", ascending=False)) print(summary)
order_id city amount
0 1 Pune 250.0
1 2 Delhi 120.0
4 5 Delhi 300.0
orders total avg
city
Delhi 2 420.0 210.000000
Pune 3 340.0 113.333333
Database scaling and performance
A database is like a library. An index is the catalogue: you find a book without walking every shelf. Caching keeps the most popular books at the front desk. Replication puts copies in other branches so more people can read at once. Sharding splits the collection across buildings (A–M here, N–Z there) when one building is full.
Everyday example: A slow website is often one missing index away from being fast.
When queries slow down or data outgrows one machine, there are ten standard levers. Try the cheap ones (indexes, query fixes, caching) before the expensive ones (sharding).
| Technique | What it does | Helps with | Trade-off |
|---|---|---|---|
| Indexing | A B-tree of keys + row pointers, so lookups skip a full scan | Reads on filtered / joined / sorted columns | Slower writes, extra storage |
| Query optimisation | Read the execution plan (EXPLAIN ANALYZE), rewrite the query, add the right index | Slow individual queries | Needs profiling skill |
| Caching | Keep hot results in memory (Redis, Memcached); fall back to the DB on a miss | Repeated reads | Stale data; invalidation is hard |
| Connection pooling | Reuse a fixed set of DB connections across app requests (PgBouncer, HikariCP) | Many short requests | Pool size must be tuned |
| Vertical scaling | Bigger server: more CPU, RAM, faster storage | Everything, quickly | Hard ceiling; cost rises steeply |
| Replication | Primary takes writes; replicas copy it and serve reads | Read scaling, availability | Replica lag: reads may be slightly stale |
| Sharding | Split rows across nodes by a shard key (range, hash or directory) | Write scaling, very large data | Cross-shard joins, hot shards, rebalancing |
| Vertical partitioning | Split wide tables by column (core vs rarely-used profile columns) | Wide rows, I/O | More joins to reassemble |
| Denormalisation | Store duplicated columns (e.g. customer_name on orders) to skip joins | Read-heavy workloads | Update anomalies; must keep copies in sync |
| Materialised views | Persist a query's result and refresh it on a schedule | Dashboards, heavy aggregates | Data is only as fresh as the last refresh |
-- Find out why a query is slow, then index the filter column EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42; CREATE INDEX idx_orders_customer ON orders(customer_id); -- Pre-compute a dashboard aggregate CREATE MATERIALIZED VIEW yearly_sales AS SELECT EXTRACT(YEAR FROM order_date) AS year, SUM(amount) AS total_sales FROM orders GROUP BY 1; REFRESH MATERIALIZED VIEW yearly_sales;
Range vs hash sharding
- Range (ids 1–1000 → node 1): easy range queries, but new ids all land on the last shard.
- Hash (hash(id) mod N): even spread, but range queries hit every shard.
Why this matters for data science
- Feature queries and model-serving lookups hit these same databases.
- Read analytics from a replica or warehouse, not the production primary.
Python example See an index speed up a query (SQLite, built into Python)
import sqlite3, random, time con = sqlite3.connect(":memory:") con.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, customer_id INT, amount REAL)") con.executemany("INSERT INTO orders(customer_id, amount) VALUES (?, ?)", [(random.randint(1, 50_000), random.random()*100) for _ in range(500_000)]) q = "SELECT COUNT(*), SUM(amount) FROM orders WHERE customer_id = 4242" def timed(): t = time.perf_counter(); con.execute(q).fetchone(); return (time.perf_counter() - t) * 1000 print("plan before:", con.execute("EXPLAIN QUERY PLAN " + q).fetchone()[-1]) before = timed() con.execute("CREATE INDEX idx_cust ON orders(customer_id)") print("plan after: ", con.execute("EXPLAIN QUERY PLAN " + q).fetchone()[-1]) after = timed() print(f"before {before:.1f} ms -> after {after:.2f} ms")
plan before: SCAN orders plan after: SEARCH orders USING INDEX idx_cust (customer_id=?) before 15.7 ms -> after 0.03 ms
Exact timings vary by machine; the change from SCAN (read every row) to SEARCH USING INDEX is the point.
Types of analytics and univariate EDA
Before cooking, you check your ingredients. Exploratory data analysis (EDA) is checking each column: what's a typical value, how much values vary, and anything strange (a customer aged 200 is a typo). The four kinds of analytics work like a doctor: what happened (symptoms), why (diagnosis), what's next (prognosis), what to do (prescription).
Everyday example: Average house price in a town with one mansion: the median tells the truer story.
Analytics matures from describing the past to recommending action. Each level answers a different question, and each rests on the one before it.
| Type | Question | Techniques | Example |
|---|---|---|---|
| Descriptive | What happened? | Aggregates, KPIs, dashboards, bar/pie charts | Monthly sales report; revenue by region |
| Diagnostic | Why did it happen? | Drill-down, segmentation, correlation, root-cause analysis | Traffic dropped in April: campaign ended? site issue? seasonality? |
| Predictive | What is likely to happen? | Regression, time-series forecasting, classification, ML | Next quarter's sales, customer churn, product demand |
| Prescriptive | What should we do? | Optimisation, simulation, A/B tests, decision models | Choose between more ad spend (+15%), a discount (+10%) or a product fix (+20%) |
Prescriptive estimates like "+20% sales" are themselves predictions with uncertainty. Compare options on expected value and risk (and cost), not the point estimate alone.
Univariate analysis: one column at a time
The first step of EDA. Before comparing variables, learn each one: its typical value, spread, shape, and unusual points. The column's type decides the summary and the plot.
| Variable type | Summarise with | Plot with |
|---|---|---|
| Numeric, continuous (age, salary) | describe(), std(), skew() | histogram, KDE, box plot |
| Numeric, discrete (rooms, children) | value_counts(), median() | bar, histogram |
| Categorical (city, gender) | value_counts(normalize=True), nunique() | sorted bar / count plot |
| Datetime (order_date) | dt.year.value_counts() | line, bar |
Centre
- Mean is dragged by outliers; median resists them; mode works for any type.
- Mean > median suggests right skew (a long tail of high values, typical of salaries).
Spread
- Two columns can share a mean and behave very differently.
std(),var(), range (max − min), IQR = Q3 − Q1.
Shape
- Skewness: |skew| < 0.5 roughly symmetric; 0.5–1 moderate; > 1 strong. Sign gives the long tail's side.
- Kurtosis: pandas
kurt()reports excess kurtosis, so 0 means normal-like tails; large positive values mean heavy tails.
Outliers
IQR rule: flag values below \(Q_1 - 1.5\,IQR\) or above \(Q_3 + 1.5\,IQR\). Alternative: \(|z| > 3\).
Box-plot whiskers stop at those fences; points beyond are drawn individually.
20 statistics terms at a glance
| Term | Plain meaning | Example |
|---|---|---|
| Mean | Add up, divide by the count | 2, 4, 6, 8, 10 → 6 |
| Median | Middle value once sorted | 1, 3, 5, 7, 9 → 5 |
| Mode | Most frequent value | Most common shoe size sold |
| Range | Largest minus smallest | 10 to 45 → 35 |
| Variance / standard deviation | How far values typically sit from the mean | Test scores ± 8 marks |
| Population vs sample | Everyone you care about vs the subset you measured | All customers vs 500 surveyed |
| Percentile | Share of values below a point | 75th percentile: 75% score lower |
| Quartiles | 25th, 50th, 75th percentiles (Q1, median, Q3) | Drawn as a box plot |
| Distribution | How often each value occurs | A histogram shows it |
| Normal distribution | Symmetric bell curve around the mean | Heights, measurement errors |
| Skewness | Lopsidedness; the long tail's side | Salaries: right-skewed |
| Outlier | A value far from the rest | A ₹10 crore order among ₹500 orders |
| Correlation, regression, probability, hypothesis, p-value, confidence interval | Covered in Modules 09–14 | |
Try it: why the median resists outliers
InteractiveSeven people's monthly salaries, in thousands. Drag the slider to give the last person a much bigger salary, as if the CEO joined the group.
- \(Q_1 = 25\), \(Q_3 = 32\), so \(IQR = 7\)
- Lower fence \(= 25 - 1.5(7) = 14.5\); upper fence \(= 32 + 10.5 = 42.5\)
- Any age below 14.5 or above 42.5 is flagged.
describe() output with min 20 and max 40. Both extremes sit inside 14.5–42.5, so that column would have 0 outliers. The two outputs come from different example data.# A univariate pass you can run on any DataFrame for col in df.select_dtypes("number").columns: s = df[col] print(col, s.describe().round(2).to_dict()) print("skew", round(s.skew(), 2), "| nulls", s.isnull().sum()) s.plot(kind="hist", bins=20, title=col); plt.show() s.plot(kind="box", title=col); plt.show() for col in df.select_dtypes("object").columns: print(df[col].value_counts(normalize=True).head(10))
Check nulls before trusting any summary: missing data biases the mean and the counts. Move to bivariate analysis only once each column is understood.
Choosing the right plot
| Plot | Shows | Example | Code |
|---|---|---|---|
| Line | Trend over time or another ordered axis | Stock price, daily traffic | df.plot(x="date", y="visits") |
| Area (stacked) | Trend plus contribution of parts | Revenue by segment over time | df.plot.area() |
| Bar | Compare categories | Sales by product | s.sort_values().plot.barh() |
| Histogram | Distribution of one numeric variable | Age distribution | df["age"].plot.hist(bins=20) |
| Box | Five-number summary and outliers | Salary by department | sns.boxplot(x="dept", y="salary", data=df) |
| Violin | Box plot + density shape | Test scores across classes | sns.violinplot(...) |
| Scatter | Relationship between two numeric variables | Height vs weight | df.plot.scatter(x="h", y="w") |
| Bubble | Scatter + a third variable as size | Revenue vs profit, size = users | plt.scatter(x, y, s=size) |
| Heatmap | Magnitude across a matrix | Correlation matrix | sns.heatmap(df.corr(), annot=True) |
| Pair plot | All pairwise scatters + distributions | First look at a dataset | sns.pairplot(df, hue="class") |
| Pie / donut | Part of a whole, few slices | Market share | s.plot.pie() |
Pie and donut charts are hard to compare once there are more than 3–4 slices or the slices are similar in size; a sorted bar chart almost always reads faster. Start bar charts at zero; line charts need not.
Python example First look at a dataset
import numpy as np, pandas as pd rng = np.random.default_rng(1) df = pd.DataFrame({ "age": rng.normal(35, 8, 200).round(), "salary": rng.lognormal(10.8, 0.4, 200).round(-2), # right-skewed, like real salaries "city": rng.choice(["Delhi", "Pune", "Mumbai"], 200, p=[.5, .3, .2]), }) print(df["salary"].describe().round(0)) print("mean vs median:", round(df.salary.mean()), round(df.salary.median())) print("skew:", round(df.salary.skew(), 2)) q1, q3 = df.salary.quantile([.25, .75]); iqr = q3 - q1 outliers = df[(df.salary < q1 - 1.5*iqr) | (df.salary > q3 + 1.5*iqr)] print("IQR outliers:", len(outliers)) print(df.city.value_counts(normalize=True).round(2)) # Plots (open in Jupyter): # df.salary.plot.hist(bins=30); df.boxplot(column="salary", by="city")
count 200.0 mean 50505.0 std 19802.0 min 18300.0 25% 37075.0 50% 46850.0 75% 60300.0 max 169400.0 Name: salary, dtype: float64 mean vs median: 50505 46850 skew: 1.79 IQR outliers: 7 city Delhi 0.51 Pune 0.28 Mumbai 0.20 Name: proportion, dtype: float64
Mean above median and skew 1.79 both say salaries have a long right tail.
Data cleaning and feature engineering
Real data is messy: blanks, typos, duplicates, numbers stored as text, the same thing spelled three ways. Cleaning fixes these. Feature engineering then turns raw columns into inputs a model can use well, such as "days since last purchase" instead of a raw date. Good features usually matter more than a fancy algorithm.
Everyday example: Washing and chopping vegetables before cooking. Skip it and even a great recipe tastes bad.
| Problem | How to spot it | Typical fix |
|---|---|---|
| Missing values | df.isna().sum() | Drop rows (if few), fill with median / mode, or model-based imputation. Add a "was missing" flag. |
| Duplicates | df.duplicated().sum() | df.drop_duplicates(); decide which copy to keep |
| Wrong types | df.dtypes shows numbers as object | pd.to_numeric, pd.to_datetime, astype |
| Inconsistent labels | value_counts() shows "pro", "Pro ", "PRO" | .str.strip().str.lower(), mapping dictionaries |
| Impossible values | describe() min / max (age 240) | Treat as missing, cap (winsorise), or check the source |
| Outliers | Box plot, IQR rule, z-score | Keep if real (and use robust models), otherwise correct or remove |
Try it: what happens when you fill missing values?
InteractiveTen customers' ages. Two are missing (—) and one is a typo (240). Pick a strategy and see how the typical age changes.
Feature engineering
| Technique | Example | Why |
|---|---|---|
| One-hot encoding | city → city_Delhi, city_Pune (0/1) | Models need numbers; avoids fake order (Delhi < Pune) |
| Ordinal encoding | size S/M/L → 1/2/3 | When the categories do have an order |
| Scaling | StandardScaler: (x − mean) / std; MinMaxScaler: 0–1 | Needed for distance-based and gradient-based models (k-NN, SVM, neural nets); trees don't care |
| Log transform | log(salary) | Tames right skew and big outliers |
| Date parts | month, weekday, days since signup | Raw dates mean nothing to a model |
| Ratios and aggregates | spend per month, orders in last 30 days | Captures behaviour the raw columns hide |
| Binning | age → 18–25, 26–40, 41+ | Simpler, more robust to noise |
| Text features | word counts, TF-IDF, embeddings | Turns text into numbers |
Pipeline does this for you.Python example Clean a messy table and build features
import numpy as np, pandas as pd from sklearn.preprocessing import StandardScaler raw = pd.DataFrame({ "customer": ["A", "B", "B", "C", "D", "E"], "age": ["34", "29", "29", None, "51", "240"], # text, a missing value, a typo "plan": ["Basic", "pro", "pro", "Pro", "basic", "Pro"], "joined": ["2024-01-05", "2023-11-20", "2023-11-20", "2024-03-02", "2022-07-15", "2024-02-10"], "spend": [120.0, 340.0, 340.0, np.nan, 95.0, 410.0], }) df = raw.drop_duplicates().copy() # 1. duplicates df["age"] = pd.to_numeric(df["age"]) # 2. fix types df["joined"] = pd.to_datetime(df["joined"]) df["plan"] = df["plan"].str.strip().str.title() # 3. consistent labels df.loc[df["age"] > 110, "age"] = np.nan # 4. impossible values -> missing df["age_missing"] = df["age"].isna().astype(int) # 5. keep a flag, then impute df["age"] = df["age"].fillna(df["age"].median()) df["spend"] = df["spend"].fillna(df["spend"].median()) # 6. Feature engineering df["tenure_days"] = (pd.Timestamp("2024-06-30") - df["joined"]).dt.days df["spend_per_month"] = (df["spend"] / (df["tenure_days"] / 30)).round(1) df = pd.get_dummies(df, columns=["plan"], drop_first=True) # 7. one-hot encode # 8. Scale numeric features (fit on training data only in real projects) df[["age_z", "spend_z"]] = StandardScaler().fit_transform(df[["age", "spend"]]).round(2) print(df.drop(columns=["joined"]).to_string(index=False))
customer age spend age_missing tenure_days spend_per_month plan_Pro age_z spend_z
A 34.0 120.0 0 177 20.3 False -0.32 -0.98
B 29.0 340.0 0 223 45.7 True -0.98 0.83
C 34.0 230.0 1 120 57.5 True -0.32 -0.07
D 51.0 95.0 0 716 4.0 False 1.93 -1.18
E 34.0 410.0 1 141 87.2 True -0.32 1.40
Customer B's duplicate row is gone, text ages became numbers, the 240 typo became missing and was filled, and 'pro/Pro/basic' became one clean 0/1 column.
Math foundations for AI
You don't need to be a mathematician, just a few tools. A matrix is a table of numbers the computer multiplies in bulk. A derivative tells you which way is downhill and how steep it is. Gradient descent is walking downhill in fog, one careful step at a time, until you reach the lowest point: the model with the smallest error.
Everyday example: Adjusting the shower: too hot, turn a little; still too hot, turn a little more.
Twelve formulas cover most of what you'll meet in ML papers and libraries. Each one shows up again in a later module.
Linear algebra: matrix multiplication
\(C = AB\), with \(c_{ij} = \sum_k a_{ik} b_{kj}\): row \(i\) of A dotted with column \(j\) of B. Needs A's columns = B's rows.
\(\begin{bmatrix}1&2\\3&4\end{bmatrix}\begin{bmatrix}5&6\\7&8\end{bmatrix} = \begin{bmatrix}19&22\\43&50\end{bmatrix}\); e.g. \(c_{11} = 1\cdot5 + 2\cdot7 = 19\). In NumPy: A @ B.
Calculus: the derivative
\(f'(x) = \lim_{h\to0} \dfrac{f(x+h)-f(x)}{h}\): the slope of the tangent line.
Gradients are derivatives with respect to every parameter; backpropagation computes them with the chain rule.
Probability: Bayes
\(P(A\mid B) = \dfrac{P(B\mid A)\,P(A)}{P(B)}\)
Posterior = likelihood × prior / evidence. Full treatment in Module 09.
Statistics: mean and variance
\(\bar x = \frac1n\sum x_i\)
Population \(\sigma^2 = \frac1n\sum(x_i-\mu)^2\); sample \(s^2 = \frac{1}{n-1}\sum(x_i-\bar x)^2\)
\(n-1\) (Bessel's correction) makes the sample estimate unbiased.
Linear regression cost (MSE)
\(J(\theta) = \frac1n\sum(y_i-\hat y_i)^2\)
Logistic regression: sigmoid
\(\sigma(z) = \dfrac{1}{1+e^{-z}}\) turns any score into a probability in (0, 1).
Optimisation: gradient descent
\(\theta \leftarrow \theta - \alpha\,\nabla_\theta J(\theta)\)
Step against the gradient; \(\alpha\) is the learning rate.
Loss functions
MSE (regression) as above.
Binary cross-entropy: \(L = -\frac1n\sum[y_i\log\hat y_i + (1-y_i)\log(1-\hat y_i)]\)
Distance
Euclidean: \(d(x,y) = \sqrt{\sum(x_i-y_i)^2}\)
(1, 2) to (4, 6): \(\sqrt{9+16} = 5\). Used by k-NN and k-means, which is why features need scaling. Text embeddings usually use cosine similarity instead.
Regularisation
L2 / Ridge: \(J = \text{MSE} + \lambda\sum_j\theta_j^2\) shrinks weights.
L1 / Lasso: \(J = \text{MSE} + \lambda\sum_j|\theta_j|\) can set weights to exactly 0 (feature selection).
PCA: covariance matrix
\(\operatorname{Cov}(X_c) = \frac{1}{n-1}X_c^\top X_c\), with \(X_c\) mean-centred.
Its eigenvectors are the principal components; eigenvalues give the variance each explains.
Neural networks
ReLU \(\max(0,x)\), tanh, sigmoid. Detail in Module 22.
Try it: gradient descent, step by step
InteractiveThe curve is the error (loss) for each value of one weight w. The lowest point is at w = 3. Each step moves w downhill by learning rate × slope. Try a tiny learning rate, then a huge one.
Python example Matrix multiplication, a derivative, and gradient descent from scratch
import numpy as np A = np.array([[1, 2], [3, 4]]); B = np.array([[5, 6], [7, 8]]) print("A @ B =\n", A @ B) f = lambda x: x**2 h = 1e-5 print("numeric derivative of x^2 at x=3:", round((f(3 + h) - f(3)) / h, 3)) # exact answer: 6 # Gradient descent: learn w, b for y = w*x + b x = np.array([1, 2, 3, 4, 5], dtype=float); y = 2*x + 1 w, b, lr = 0.0, 0.0, 0.05 for step in range(1000): err = (w*x + b) - y w -= lr * 2 * (err * x).mean() # dMSE/dw b -= lr * 2 * err.mean() # dMSE/db print(f"learned w={w:.3f}, b={b:.3f} (true: 2, 1)") a, c = np.array([1, 2]), np.array([4, 6]) print("euclidean distance:", np.linalg.norm(a - c))
A @ B = [[19 22] [43 50]] numeric derivative of x^2 at x=3: 6.0 learned w=2.000, b=1.000 (true: 2, 1) euclidean distance: 5.0
Probability essentials
Probability is a number from 0 (impossible) to 1 (certain). Rolling a 6 on a die is 1/6. Conditional probability updates that number when you learn something new: the chance of rain given dark clouds. Bayes' theorem is the rule for updating what you believe when evidence arrives.
Everyday example: A positive result on a test for a rare disease is still usually a false alarm. Try the calculator below.
Basics
Equally likely outcomes: \(P(A) = \dfrac{n(A)}{n(S)}\), with \(0 \le P(A) \le 1\), \(P(S)=1\), \(P(\varnothing)=0\).
Complement: \(P(A') = 1 - P(A)\)
Addition
\(P(A\cup B) = P(A) + P(B) - P(A\cap B)\)
Mutually exclusive (\(A\cap B=\varnothing\)): \(P(A\cup B) = P(A)+P(B)\)
At least one: \(P(A\cup B) = 1 - P(A'\cap B')\)
Only A, not B: \(P(A - B) = P(A) - P(A\cap B)\)
Conditional and multiplication
\(P(A\mid B) = \dfrac{P(A\cap B)}{P(B)}\), for \(P(B)>0\)
\(P(A\cap B) = P(A)\,P(B\mid A) = P(B)\,P(A\mid B)\)
Chain rule: \(P(A\cap B\cap C) = P(A)P(B\mid A)P(C\mid A\cap B)\)
Independence
\(A\) and \(B\) are independent if \(P(A\cap B) = P(A)P(B)\), equivalently \(P(A\mid B)=P(A)\).
Independent is not the same as mutually exclusive. Two exclusive events with non-zero probability are always dependent: if one happens, the other can't.
Total probability and Bayes
For a partition \(A_1,\dots,A_n\): \(P(B) = \sum_i P(A_i)P(B\mid A_i)\)
Binomial distribution
\(n\) independent trials, success probability \(p\):
\(P(X=r) = \binom{n}{r} p^r (1-p)^{n-r}\)
\(E(X) = np\), \(\operatorname{Var}(X) = np(1-p)\)
Example: exactly 3 heads in 10 fair flips = \(\binom{10}{3}/2^{10} = 120/1024 \approx 0.117\).
Try it: Bayes for a diagnostic test
InteractiveWith 1% prevalence, a 95%-sensitive test with a 5% false-positive rate gives only about a 16% chance of disease after a positive result. Rare conditions produce mostly false alarms. This is the same effect that makes precision low on imbalanced data (Module 18).
Probability distributions
A distribution describes how likely each possible value is. Discrete distributions have countable values (0, 1, 2 …); continuous ones can take any value in a range. Picking the right one lets you model uncertainty, simulate data, and choose the right test or model.
| Distribution | Type | Models | Formula | Mean | Example |
|---|---|---|---|---|---|
| Bernoulli(p) | Discrete | One yes/no outcome | \(P(X{=}1)=p,\ P(X{=}0)=1-p\) | \(p\) | Is this email spam? |
| Binomial(n, p) | Discrete | Successes in n independent tries | \(\binom{n}{k}p^k(1-p)^{n-k}\) | \(np\) | Correct answers in a 10-question quiz |
| Poisson(λ) | Discrete | Count of events in a fixed time or space | \(e^{-\lambda}\lambda^k/k!\) | \(\lambda\) | Customers arriving per hour |
| Normal(μ, σ) | Continuous | Symmetric values around an average | \(\frac{1}{\sigma\sqrt{2\pi}}e^{-(x-\mu)^2/2\sigma^2}\) | \(\mu\) | Heights, measurement noise |
| Uniform(a, b) | Continuous | Every value in a range equally likely | \(\frac{1}{b-a}\) | \(\frac{a+b}{2}\) | Random numbers, weight initialisation |
| Exponential(λ) | Continuous | Waiting time between events; memoryless | \(\lambda e^{-\lambda x}\) | \(1/\lambda\) | Time until the next support call |
Normal-distribution rule of thumb (68–95–99.7): about 68% of values lie within 1 standard deviation of the mean, 95% within 2, and 99.7% within 3.
Try it: explore the distributions
InteractivePython example Work with distributions in SciPy
from scipy import stats print("Bernoulli p=0.3 P(X=1):", stats.bernoulli.pmf(1, 0.3)) print("Binomial n=10 p=.5 P(X=5):", round(stats.binom.pmf(5, 10, 0.5), 4)) print("Poisson λ=2 P(X=0):", round(stats.poisson.pmf(0, 2), 4), " P(X≤3):", round(stats.poisson.cdf(3, 2), 4)) h = stats.norm(loc=170, scale=8) # heights: mean 170 cm, sd 8 print("Normal: P(height < 186) =", round(h.cdf(186), 4), "| 95% range:", [round(float(v), 1) for v in h.interval(0.95)]) print("Uniform[0,10]: P(X < 3) =", stats.uniform(0, 10).cdf(3)) w = stats.expon(scale=5) # mean wait 5 minutes (λ = 0.2) print("Exponential mean 5: P(wait > 10) =", round(w.sf(10), 4)) sample = stats.norm(0, 1).rvs(size=10_000, random_state=0) print("simulated mean/sd:", round(sample.mean(), 3), round(sample.std(), 3))
Bernoulli p=0.3 P(X=1): 0.3 Binomial n=10 p=.5 P(X=5): 0.2461 Poisson λ=2 P(X=0): 0.1353 P(X≤3): 0.8571 Normal: P(height < 186) = 0.9772 | 95% range: [154.3, 185.7] Uniform[0,10]: P(X < 3) = 0.3 Exponential mean 5: P(wait > 10) = 0.1353 simulated mean/sd: -0.018 0.988
P(wait > 10) for the exponential equals e⁻² = 0.1353, matching Poisson P(X = 0) with λ = 2: two views of the same random process.
Python example Simulate and calculate probabilities
import numpy as np from scipy import stats rng = np.random.default_rng(0) rolls = rng.integers(1, 7, size=100_000) print("P(six) simulated:", round((rolls == 6).mean(), 4), "| exact:", round(1/6, 4)) # Binomial: exactly 3 heads in 10 fair flips, and at least 8 print("P(X=3):", round(stats.binom.pmf(3, 10, 0.5), 4)) print("P(X>=8):", round(stats.binom.sf(7, 10, 0.5), 4)) # Bayes: rare disease, good test prior, sens, fpr = 0.01, 0.95, 0.05 p_pos = sens*prior + fpr*(1 - prior) print("P(disease | positive):", round(sens*prior / p_pos, 3))
P(six) simulated: 0.1654 | exact: 0.1667 P(X=3): 0.1172 P(X>=8): 0.0547 P(disease | positive): 0.161
p-values, confidence intervals and hypothesis testing
Think of a court trial. We start by assuming "innocent": the null hypothesis says there's no real effect. The p-value asks: if that were true, how surprising would this evidence be? Very surprising (usually below 0.05) means we reject it. Not surprising means "not proven", which is not the same as proven innocent. A confidence interval is a range of believable values, like "the true average is probably between 47 and 53".
Everyday example: Ten heads in a row makes you doubt the coin is fair. Try the coin simulator below.
A p-value is the probability of seeing a result at least as extreme as the one observed, assuming the null hypothesis \(H_0\) is true. It measures how surprising your data would be in a world with no effect.
The workflow
- State \(H_0\) (no effect) and \(H_1\) (an effect).
- Choose \(\alpha\) before looking: 0.05 is common; 0.01 is stricter.
- Choose one- or two-tailed before looking.
- Compute the test statistic and p-value.
- If \(p < \alpha\), reject \(H_0\). Otherwise, fail to reject.
- Report effect size and confidence interval too.
A p-value is NOT
- The probability that \(H_0\) is true.
- The probability the result happened "by chance".
- A measure of how big or important the effect is.
- Proof of no effect when \(p \ge 0.05\). Say "fail to reject", never "accept \(H_0\)".
Statistical vs practical significance
With a huge sample, a trivial effect can reach \(p < 0.001\). With a tiny sample, a meaningful effect may miss 0.05. Always report the effect size (mean difference, odds ratio, \(r\), Cohen's \(d\)) and a confidence interval.
Example: \(\beta = 0.42\), 95% CI 0.15–0.69, \(p = 0.003\). The CI tells you direction, plausible range and significance (it excludes 0) in one line.
Common mistakes
- Choosing a one-tailed test after seeing the data.
- Running many tests and reporting only the significant ones (p-hacking). Correct with Bonferroni or Benjamini–Hochberg.
- Treating significance as causation.
- Changing the hypothesis after seeing results.
| Truth \ Decision | Reject \(H_0\) | Fail to reject \(H_0\) |
|---|---|---|
| \(H_0\) true | Type I error (false positive), rate \(=\alpha\) | Correct |
| \(H_0\) false | Correct; probability \(=\) power \(=1-\beta\) | Type II error (false negative), rate \(=\beta\) |
Try it: is this coin fair?
InteractiveYou flip a coin and count heads. Assume the coin is fair (that's the null hypothesis). The bars show how often each number of heads happens with a fair coin. Orange bars are results at least as extreme as yours; together they make the p-value.
Confidence intervals
Reading a CI
- Sample mean 50, 95% CI (47.2, 52.8): margin of error ±2.8.
- Correct meaning: if you repeated the study many times, 95% of intervals built this way would contain the true mean.
- Wider = less precise. Higher confidence or smaller n makes it wider; the width shrinks with \(\sqrt n\), so 4× the data halves it.
CI and tests agree
- A 95% CI that excludes the null value (e.g. 0 for a difference) ⇔ two-sided \(p < 0.05\).
- The CI also shows the size and direction of the effect, which a p-value can't.
- Use \(t\) instead of \(z\) when σ is estimated from the sample, especially for small n.
The golden rule: never interpret a p-value in isolation. Look at the hypothesis, effect size, CI, test assumptions and the real-world meaning together.
Python example One-sample t-test with a confidence interval
import numpy as np from scipy import stats # Delivery times (minutes). Claim: average is 30. times = np.array([31, 34, 29, 35, 33, 30, 36, 32, 34, 31, 37, 33]) t, p = stats.ttest_1samp(times, popmean=30) print(f"mean={times.mean():.2f}, t={t:.2f}, p={p:.4f}") ci = stats.t.interval(0.95, df=len(times)-1, loc=times.mean(), scale=stats.sem(times)) print("95% CI:", np.round(ci, 2)) print("Reject H0 (mean = 30)?", p < 0.05)
mean=32.92, t=4.16, p=0.0016 95% CI: [31.37 34.46] Reject H0 (mean = 30)? True
p = 0.0016 < 0.05 and the 95% CI (31.4 to 34.5) excludes 30, so deliveries take longer than claimed.
Three tests: one-sample Z, one-way ANOVA, Mann–Whitney U
Different questions need different tests, like different kitchen tools. A Z-test checks whether one group's average matches a claim. ANOVA checks whether three or more groups differ (do three fertilisers grow different plants?). Mann–Whitney compares two groups when data is lopsided, using rankings instead of raw values.
Everyday example: "Our bulbs last 1000 hours." A Z-test on 50 bulbs checks that claim.
| Test | Question it answers | Use when |
|---|---|---|
| One-sample Z | Is a sample mean different from a claimed value \(\mu_0\)? | \(\sigma\) known, \(n \ge 30\). If \(\sigma\) is unknown, use a one-sample t-test. |
| One-way ANOVA | Do 3+ group means differ? | Independent groups, roughly normal, similar variances. Follow up with Tukey HSD to find which groups differ. |
| Mann–Whitney U | Do two independent groups come from the same distribution? | Ordinal or skewed data; non-parametric alternative to the two-sample t-test. |
One-sample Z test
Critical values: two-tailed \(\pm z_{\alpha/2}\) (±1.96 at 5%); right-tailed \(z_\alpha\) (1.645); left-tailed \(-z_\alpha\).
A maker claims bulbs last 1000 h. A sample of 50 averages 960 h; \(\sigma = 120\). Test at 5%, two-tailed.
- \(H_0: \mu = 1000\), \(H_1: \mu \ne 1000\)
- \(SE = 120/\sqrt{50} = 16.97\); \(z = (960-1000)/16.97 = -2.36\)
- Critical value ±1.96. Since −2.36 < −1.96, reject \(H_0\). Two-tailed \(p \approx 0.018\).
- The mean lifetime differs from 1000 h at the 5% level.
One-way ANOVA
A: 8, 9, 6, 7, 10 (mean 8.0) · B: 12, 11, 13, 12, 14 (mean 12.4) · C: 7, 8, 9, 6, 10 (mean 8.0). \(N = 15\), \(k = 3\), \(\alpha = 0.05\).
- Grand mean \(= 142/15 = 9.467\)
- \(SS_B = 5(8-9.467)^2 + 5(12.4-9.467)^2 + 5(8-9.467)^2 = 10.76 + 43.02 + 10.76 = 64.53\)
- \(SS_W = 10 + 5.20 + 10 = 25.20\)
- \(MS_B = 64.53/2 = 32.27\); \(MS_W = 25.20/12 = 2.10\); \(F = 15.37\)
- \(F_{crit}(2, 12) = 3.89\). Since 15.37 > 3.89, reject \(H_0\) (\(p \approx 0.0005\)). At least one mean differs; B is the obvious candidate.
| Source | SS | df | MS | F |
|---|---|---|---|---|
| Between | 64.53 | 2 | 32.27 | 15.37 |
| Within | 25.20 | 12 | 2.10 | — |
| Total | 89.73 | 14 | — | — |
Mann–Whitney U
Rank all values together (average ranks for ties), sum ranks per group, compute U, take the smaller one. Reject \(H_0\) if \(U \le U_{crit}\). For large samples use \(z = (U-\mu_U)/\sigma_U\), with \(\mu_U = n_1n_2/2\) and \(\sigma_U = \sqrt{n_1n_2(n_1+n_2+1)/12}\).
A: 12, 14, 16, 18, 20, 22, 24, 26 · B: 10, 11, 13, 15, 17, 19, 21, 23
- Ranks of A in the combined list: 3, 5, 7, 9, 11, 13, 15, 16 → \(R_A = 79\). Ranks of B: 1, 2, 4, 6, 8, 10, 12, 14 → \(R_B = 57\). Check: \(79 + 57 = 136 = 16 \cdot 17/2\).
- \(U_A = 64 + 36 - 79 = 21\); \(U_B = 64 + 36 - 57 = 43\). Check: \(21 + 43 = 64 = n_1 n_2\).
- \(U = 21\). \(U_{crit}\) (n₁ = n₂ = 8, two-tailed, α = 0.05) = 13.
- 21 > 13, so fail to reject \(H_0\) (exact \(p \approx 0.28\)). No significant difference.
Python example Z-test, ANOVA and Mann–Whitney with SciPy
import numpy as np from scipy import stats # One-sample Z (sigma known) z = (960 - 1000) / (120 / np.sqrt(50)) print(f"z = {z:.2f}, two-tailed p = {2*stats.norm.cdf(-abs(z)):.4f}") # One-way ANOVA A, B, C = [8, 9, 6, 7, 10], [12, 11, 13, 12, 14], [7, 8, 9, 6, 10] F, p = stats.f_oneway(A, B, C) print(f"ANOVA F = {F:.2f}, p = {p:.4f}") # Mann-Whitney U a = [12, 14, 16, 18, 20, 22, 24, 26]; b = [10, 11, 13, 15, 17, 19, 21, 23] U, p = stats.mannwhitneyu(a, b, alternative="two-sided") print(f"Mann-Whitney U = {U:.0f}, p = {p:.3f}")
z = -2.36, two-tailed p = 0.0184 ANOVA F = 15.37, p = 0.0005 Mann-Whitney U = 43, p = 0.279
These match the worked examples above.
A/B testing and the chi-square test
An A/B test is a fair race. Visitors are randomly split: half see the old version (A), half the new one (B). Because the split is random, the only systematic difference between the groups is the change you made, so a difference in results is caused by that change. Statistics then tells you whether the difference is bigger than luck alone would produce.
Everyday example: Testing two headlines for the same news story and keeping the one more people click.
Steps
- Pick one primary metric (e.g. conversion rate) and the smallest lift worth detecting.
- Work out the sample size needed before starting.
- Randomise users (not page views) into A and B.
- Run for the planned duration, ideally full weeks. Don't stop early when it "looks significant".
- Test the difference: two-proportion z-test or chi-square.
- Report the lift with a confidence interval, then decide.
Common traps
- Peeking: checking daily and stopping at the first p < 0.05 inflates false positives.
- Too many metrics: something will be "significant" by chance.
- Novelty effect: users click new things at first, then settle.
- Sample ratio mismatch: a 50/50 split that arrives as 52/48 signals a bug.
Chi-square test of independence
For counts in a table (group × outcome): \(\chi^2 = \sum \frac{(O - E)^2}{E}\), where \(O\) is observed and \(E\) is the count expected if group and outcome were unrelated.
For a 2×2 table it gives the same p-value as the two-proportion z-test (\(\chi^2 = z^2\)).
Sample size, roughly
Per group: \(n \approx \dfrac{(z_{\alpha/2} + z_\beta)^2\,[p_1(1-p_1) + p_2(1-p_2)]}{(p_2 - p_1)^2}\)
With α = 0.05 and 80% power, \((1.96 + 0.84)^2 \approx 7.8\). Halving the lift you want to detect needs about 4× the visitors.
Try it: A/B test calculator
InteractivePython example Analyse an A/B test
import numpy as np from scipy import stats from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep # Old page (A) vs new page (B) visitors = np.array([5000, 5000]) conversions = np.array([400, 460]) rate = conversions / visitors print("conversion rates:", rate, "| relative lift:", f"{rate[1]/rate[0] - 1:.1%}") z, p = proportions_ztest(conversions, visitors) lo, hi = confint_proportions_2indep(conversions[1], visitors[1], conversions[0], visitors[0]) print(f"z = {z:.2f}, p = {p:.4f}, 95% CI for B - A: [{lo:.4f}, {hi:.4f}]") # Same question as a chi-square test on the 2x2 table table = [[400, 5000 - 400], [460, 5000 - 460]] chi2, p2, dof, _ = stats.chi2_contingency(table, correction=False) print(f"chi-square = {chi2:.2f}, p = {p2:.4f}")
conversion rates: [0.08 0.092] | relative lift: 15.0% z = -2.14, p = 0.0323, 95% CI for B - A: [0.0010, 0.0230] chi-square = 4.58, p = 0.0323
Note that chi-square p equals the z-test p (χ² = z²).
Covariance and correlation
Correlation measures how two things move together, on a scale from −1 (one goes up, the other goes down) through 0 (no pattern) to +1 (they rise together perfectly). It shows that things move together, never why.
Everyday example: Ice-cream sales and sunburns rise together, because of summer, not because ice cream burns you.
Correlation measures the strength and direction of a linear relationship. Regression (next module) models that relationship so you can predict one variable from another. Neither proves causation.
Covariance: direction only
> 0 move together; < 0 move oppositely; 0 no linear relationship. Its size depends on units, so a covariance of 12 says nothing about strength.
Divide by \(n\) for a population, \(n-1\) for a sample (pandas df.cov() and NumPy np.cov use \(n-1\)).
Pearson r: strength and direction
Unit-free, always between −1 and +1. Rough guide: |r| < 0.3 weak, 0.3–0.7 moderate, > 0.7 strong.
Watch out for
- r only sees linear patterns: a perfect U-shape can give r ≈ 0.
- One outlier can create or destroy a correlation. Plot first.
- For ranks or monotonic curves, use Spearman's ρ.
- In simple regression, \(R^2 = r^2\).
Try it: what does a correlation look like?
Interactive| Hours X | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|
| Score Y | 50 | 60 | 68 | 72 | 78 | 85 | 90 | 95 |
- \(\bar X = 44/8 = 5.5\); \(\bar Y = 598/8 = 74.75\)
- \(\sum(X-\bar X)(Y-\bar Y) = 261\); \(\sum(X-\bar X)^2 = 42\); \(\sum(Y-\bar Y)^2 = 1641.5\)
- \(r = 261 / \sqrt{42 \times 1641.5} = 261 / 262.57 = 0.994\)
- Significance: \(df = 6\), critical \(r \approx 0.707\) at α = 0.05. Since 0.994 > 0.707, it is significant (\(p \approx 5\times10^{-7}\)).
- A very strong positive linear relationship. Fitted line: \(\hat Y = 40.57 + 6.21X\), about 6 points per extra hour. Still association, not proof of causation.
Python example Correlation matrix, Pearson and Spearman
import pandas as pd from scipy import stats df = pd.DataFrame({"hours": [2, 3, 4, 5, 6, 7, 8, 9], "score": [50, 60, 68, 72, 78, 85, 90, 95], "tv_hours": [5, 4, 5, 3, 4, 2, 3, 1]}) print(df.corr().round(3)) # correlation matrix r, p = stats.pearsonr(df.hours, df.score) rho, p_s = stats.spearmanr(df.hours, df.score) print(f"Pearson r = {r:.3f} (p = {p:.1e}); Spearman rho = {rho:.3f}") print("sample covariance:", round(df.hours.cov(df.score), 2))
hours score tv_hours hours 1.000 0.994 -0.849 score 0.994 1.000 -0.830 tv_hours -0.849 -0.830 1.000 Pearson r = 0.994 (p = 5.3e-07); Spearman rho = 1.000 sample covariance: 37.29
Simple linear regression (OLS) and regression metrics
Draw the best straight line through a cloud of dots, then use it to predict. "Each extra hour of study adds about 6 marks." Best means the line with the smallest total squared miss. Fancier algorithms draw curves or steps instead of straight lines.
Everyday example: Estimating a taxi fare: a fixed start fee (intercept) plus a price per km (slope).
Ordinary Least Squares picks the line \(\hat{Y} = b_0 + b_1X\) that minimises the sum of squared residuals.
Estimates
Assumptions (LINE)
- Linear relationship
- Independent errors
- Normally distributed errors
- Equal variance of errors (homoscedasticity)
| X | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Y | 5 | 7 | 9 | 11 | 13 | 15 | 17 | 19 |
- \(n = 8\), \(\sum X = 36\), \(\sum Y = 96\), \(\sum X^2 = 204\), \(\sum XY = 516\)
- \(b_1 = \dfrac{8(516) - 36(96)}{8(204) - 36^2} = \dfrac{4128 - 3456}{1632 - 1296} = \dfrac{672}{336} = 2\)
- \(\bar X = 4.5\), \(\bar Y = 12\); \(b_0 = 12 - 2(4.5) = 3\)
- \(\hat{Y} = 3 + 2X\). Each extra unit of X adds 2 to Y. The points lie exactly on the line, so \(R^2 = 1\).
Try it: draw your own data, watch the line fit
InteractiveClick or tap inside the chart to add points. The best-fit line and its numbers update instantly. Dashed lines are the residuals: each point's miss.
Regression metrics
| Metric | Formula | Read it as |
|---|---|---|
| MAE | \(\frac{1}{n}\sum |y_i - \hat y_i|\) | Average miss, in the target's units. Robust to outliers. |
| MSE | \(\frac{1}{n}\sum (y_i - \hat y_i)^2\) | Punishes big errors heavily. Units are squared. |
| RMSE | \(\sqrt{\text{MSE}}\) | Back in target units; always ≥ MAE. |
| R² | \(1 - \frac{\sum (y_i - \hat y_i)^2}{\sum (y_i - \bar y)^2}\) | Share of variance explained. 0 = no better than the mean; can go negative on test data. |
| Hours X | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Score Y | 50 | 55 | 60 | 68 | 72 | 80 | 85 | 90 |
- \(n = 8\), \(\sum X = 36\), \(\sum Y = 560\), \(\sum X^2 = 204\), \(\sum XY = 2767\)
- \(b = \dfrac{8(2767) - 36(560)}{8(204) - 36^2} = \dfrac{22136 - 20160}{336} = \dfrac{1976}{336} = 5.881\)
- \(\bar X = 4.5\), \(\bar Y = 70\); \(a = 70 - 5.881(4.5) = 43.536\). So \(\hat Y = 43.54 + 5.88X\).
- \(SS_{res} = 5.40\), \(SS_{tot} = 1458\), so \(R^2 = 1 - 5.40/1458 = 0.996\).
- Prediction for 4 hours: \(43.54 + 5.88(4) = 67.06\). The actual score at 4 hours was 68, so the fit is close.
Beyond the straight line: regression algorithms
Same task, predicting a number, but each algorithm has a different notion of what shape the relationship may take.
| Algorithm | Fit looks like | Strengths | Watch for |
|---|---|---|---|
| Linear | Straight line / plane | Fast, interpretable coefficients | Misses curves; sensitive to outliers |
| Polynomial | Smooth curve (e.g. U-shape) | Captures simple curvature with linear-model tools | High degrees overfit and explode at the edges |
| SGD (stochastic gradient descent) regressor | Linear, fitted by many small noisy updates | Scales to huge datasets and streaming data | Needs feature scaling and learning-rate tuning |
| Decision tree | Step function | No scaling needed; handles interactions | Overfits alone; can't extrapolate beyond training range |
| Random forest | Averaged steps, smoother | Strong default, robust, little tuning | Larger and slower; still no extrapolation |
| XGBoost / gradient boosting | Sequential trees fixing residuals | Often best on tabular data | More hyperparameters; can overfit |
| k-nearest neighbours | Jagged local averages | Simple, no training step | Noisy with small k; slow on big data; needs scaling |
| Support vector (SVR) | Curve inside an ε-tube | Ignores errors smaller than ε; kernels allow curves | Scales poorly past ~100k rows |
| Neural network | Any smooth function | Very flexible, great with lots of data | Needs data, tuning and scaling; less interpretable |
Python example Fit and evaluate a linear regression with scikit-learn
import numpy as np from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score X = np.arange(1, 9).reshape(-1, 1) # hours (2-D: rows x features) y = np.array([50, 55, 60, 68, 72, 80, 85, 90]) # scores model = LinearRegression().fit(X, y) print(f"score = {model.intercept_:.2f} + {model.coef_[0]:.2f} * hours") pred = model.predict(X) print("MAE :", round(mean_absolute_error(y, pred), 3)) print("RMSE:", round(np.sqrt(mean_squared_error(y, pred)), 3)) print("R² :", round(r2_score(y, pred), 4)) print("predicted score for 4.5 hours:", round(model.predict([[4.5]])[0], 1))
score = 43.54 + 5.88 * hours MAE : 0.75 RMSE: 0.822 R² : 0.9963 predicted score for 4.5 hours: 70.0
Same line as the corrected worked example: ŷ = 43.54 + 5.88x.
Multivariate analysis
Real problems have many columns at once. Multiple regression predicts a house price from size, location and age together. PCA squeezes many columns into a few summary scores. Clustering groups similar customers without being told the groups. LDA finds what best separates groups you already know.
Everyday example: A shop discovering "bargain hunters", "weekend families" and "big spenders" in its sales data is clustering.
Once each column is understood, study several together. Multivariate methods find patterns invisible one variable at a time.
| Method | Goal | Supervised? | Python |
|---|---|---|---|
| Correlation matrix | Which features move together | No | df.corr() + sns.heatmap(corr, annot=True) |
| Multiple regression | Predict y from several features | Yes (numeric y) | sm.OLS(y, sm.add_constant(X)).fit() |
| PCA | Compress features into fewer uncorrelated components | No | PCA(n_components=2) |
| Factor analysis | Find hidden (latent) factors behind observed variables | No | FactorAnalysis(n_components=2) |
| Cluster analysis | Group similar rows | No | KMeans, hierarchical, DBSCAN |
| Discriminant analysis (LDA) | Find directions that best separate known classes | Yes (class y) | LinearDiscriminantAnalysis |
Multiple regression
\(y = \beta_0 + \beta_1x_1 + \dots + \beta_kx_k + \varepsilon\). Each coefficient is the change in y per unit of that feature, holding the others fixed.
- Read p-values per coefficient, and adjusted R² for the model.
- Check multicollinearity with VIF (> 5–10 is a warning).
PCA vs factor analysis
- PCA finds directions of maximum variance; components are exact combinations of the inputs. Standardise first. Check
explained_variance_ratio_. - Factor analysis models each variable as latent factors + unique noise. Used for surveys and questionnaires. Read the loadings.
Clustering tips
- Scale features first: k-means uses distances.
- Choose k with the elbow method or silhouette score.
- DBSCAN finds irregular shapes and labels noise; k-means assumes round clusters.
LDA
- Supervised: uses the labels, unlike PCA.
- At most (classes − 1) components.
- Assumes roughly normal numeric features with similar covariance per class.
Try it: watch k-means find groups
Interactive90 customers, with no labels. K-means places 3 centres (×), colours each customer by the nearest centre, moves each centre to the middle of its group, and repeats until nothing changes.
import statsmodels.api as sm from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.cluster import KMeans X = df[["age", "income", "education"]] model = sm.OLS(df["spend"], sm.add_constant(X)).fit() print(model.summary()) # coefficients, p-values, R² Xs = StandardScaler().fit_transform(df[["age", "income", "spend", "savings"]]) pca = PCA(n_components=2).fit(Xs) print(pca.explained_variance_ratio_) labels = KMeans(n_clusters=3, n_init="auto", random_state=42).fit_predict(Xs)
paborn as pd (should be pandas as pd) and says LDA "works well with categorical data". LDA needs a categorical target but numeric, roughly normal features. Encode categorical inputs or use another classifier.Python example PCA and k-means on the iris flowers
from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score, silhouette_score X, species = load_iris(return_X_y=True) # 150 flowers, 4 measurements Xs = StandardScaler().fit_transform(X) pca = PCA(n_components=2).fit(Xs) print("variance kept by 2 components:", pca.explained_variance_ratio_.round(3), "total", pca.explained_variance_ratio_.sum().round(3)) for k in [2, 3, 4]: labels = KMeans(n_clusters=k, n_init="auto", random_state=0).fit_predict(Xs) print(f"k={k}: silhouette={silhouette_score(Xs, labels):.3f}") labels = KMeans(n_clusters=3, n_init="auto", random_state=0).fit_predict(Xs) print("agreement with true species (ARI):", round(adjusted_rand_score(species, labels), 3))
variance kept by 2 components: [0.73 0.229] total 0.958 k=2: silhouette=0.582 k=3: silhouette=0.460 k=4: silhouette=0.387 agreement with true species (ARI): 0.62
Silhouette prefers k = 2 here (two iris species overlap), a reminder that cluster scores guide but don't decide.
Classic machine learning algorithms
Machine learning means the computer finds the rule from examples instead of you writing it. Supervised learning learns from examples with answers (emails already marked spam or not). Unsupervised learning finds structure with no answers (customer groups). For tables of data (rows and columns), these classic algorithms are still the first thing to try, often before deep learning.
Everyday example: A decision tree is a game of 20 questions: "Contract monthly? Yes. More than 3 support calls? Yes. → likely to cancel."
| Algorithm | How it decides | Good at | Watch for |
|---|---|---|---|
| Logistic regression | Weighted sum of features → sigmoid → probability | Fast, explainable baseline; coefficients show direction | Straight-line boundaries only (unless you add features) |
| k-nearest neighbours | Majority vote of the k most similar training rows | Simple, no training step | Slow on big data; needs scaling |
| Naive Bayes | Bayes' theorem, assuming features are independent | Text / spam, tiny data, very fast | The independence assumption is rarely true |
| Support vector machine | Widest possible margin between classes; kernels allow curves | Medium-sized, high-dimensional data | Slow past ~100k rows; needs scaling |
| Decision tree | A flowchart of yes/no questions | Easy to read and explain | Overfits when grown deep |
| Random forest | Hundreds of trees on random samples; they vote | Strong default, little tuning | Bigger, slower, less interpretable |
| Gradient boosting (XGBoost, LightGBM, CatBoost) | Trees added one at a time, each fixing the last one's errors | Usually the most accurate on tabular data | More hyperparameters; can overfit |
How to choose
- Start with a dumb baseline (always predict the majority class).
- Try logistic / linear regression: fast, explainable.
- Try random forest and gradient boosting.
- Compare with cross-validation (next module). Pick the simplest model that is close to the best.
The scikit-learn pattern
Every model uses the same three calls: model.fit(X_train, y_train), model.predict(X_new), model.predict_proba(X_new). Learn it once and you can swap algorithms in one line.
Python example Compare seven classifiers with 5-fold cross-validation
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import cross_val_score from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier X, y = load_breast_cancer(return_X_y=True) # 569 tumours, 30 measurements, benign/malignant models = { "Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), "k-NN (k=5)": make_pipeline(StandardScaler(), KNeighborsClassifier()), "Naive Bayes": GaussianNB(), "SVM (RBF)": make_pipeline(StandardScaler(), SVC()), "Decision tree": DecisionTreeClassifier(random_state=0), "Random forest": RandomForestClassifier(n_estimators=300, random_state=0), "Gradient boosting": HistGradientBoostingClassifier(random_state=0), } for name, m in models.items(): s = cross_val_score(m, X, y, cv=5, scoring="accuracy") print(f"{name:20s} {s.mean():.3f} ± {s.std():.3f}")
Logistic regression 0.981 ± 0.007 k-NN (k=5) 0.965 ± 0.010 Naive Bayes 0.939 ± 0.015 SVM (RBF) 0.974 ± 0.015 Decision tree 0.917 ± 0.016 Random forest 0.963 ± 0.022 Gradient boosting 0.967 ± 0.012
The data ships with scikit-learn, so this runs offline. On this data a well-scaled logistic regression beats fancier models.
Key formulas behind the algorithms
Linear and logistic regression
Linear: \(\hat y = w^\top x + b\)
Logistic: \(P(y{=}1) = \dfrac{1}{1+e^{-(w^\top x + b)}}\)
Random forest
Classification: majority vote of trees \(h_1(x),\dots,h_N(x)\).
Regression: \(\hat y = \frac1N\sum_{i=1}^N h_i(x)\)
k-NN and SVM
k-NN: majority class (or average) of the k nearest points.
SVM: the boundary with the widest margin; SVR fits inside an ε-tube.
k-means and PCA
k-means minimises \(\sum_{i=1}^{k}\sum_{x\in C_i}\lVert x-\mu_i\rVert^2\).
PCA: new axes of maximum variance (Module 15).
Check yourself: for X = [1, 2, 3, 4] and y = [2, 4, 5, 7], least squares gives slope 1.6 and intercept 0.5 (verified).
Training, validating and tuning models
A model must be judged on data it has never seen, just as a student is judged on a new exam, not on the practice questions they memorised. So we hide some data (the test set) and only check it at the very end. Overfitting is memorising the practice questions: perfect in practice, poor in the real exam. Underfitting is not studying enough to do well on either.
Everyday example: Cross-validation is like taking five different practice exams and averaging your score, so one lucky or unlucky exam doesn't fool you.
Train / validation / test
- Train (~60–80%): the model learns from this.
- Validation or cross-validation: compare models and settings.
- Test (~20%): look once, at the end, to report a fair score.
- Use
stratify=yto keep class proportions; split by time for time data.
k-fold cross-validation
Split training data into k parts (often 5). Train on k−1 parts, score on the remaining one, repeat k times, average. More reliable than one split, and every row is used for both training and checking.
Bias–variance trade-off
- High bias (underfit): too simple. Train and test errors both high.
- High variance (overfit): too flexible. Train error low, test error high.
- Fixes for overfitting: more data, simpler model, regularisation, fewer features, early stopping.
Hyperparameter tuning
- Parameters are learned (weights). Hyperparameters are set by you (tree depth, learning rate, k).
- Grid search tries every combination; random search samples them; Bayesian search (Optuna) learns where to look.
- Always tune with cross-validation on training data, never on the test set.
Imbalanced classes
- 1% fraud: predicting "never fraud" is 99% accurate and useless.
- Use recall, precision, F1, PR-AUC instead of accuracy.
- Try
class_weight="balanced", adjust the decision threshold, or resample (e.g. SMOTE) on training data only.
Pipelines
Bundle preprocessing and the model in one Pipeline. Cross-validation then refits the scaler and imputer inside each fold, which prevents leakage, and deployment ships one object.
Try it: find the sweet spot between underfitting and overfitting
InteractiveDark dots are training data; orange rings are test data the model never sees. Increase the model's flexibility (polynomial degree) and watch the two errors.
Python example Spot overfitting, then tune with cross-validation
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score X, y = load_breast_cancer(return_X_y=True) X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42) # Overfitting check: an unlimited tree memorises the training set from sklearn.tree import DecisionTreeClassifier for depth in [1, 3, None]: t = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_tr, y_tr) print(f"depth={str(depth):4s} train={t.score(X_tr, y_tr):.3f} test={t.score(X_te, y_te):.3f}") # Hyperparameter tuning with 5-fold cross-validation on the TRAINING set only grid = GridSearchCV( RandomForestClassifier(random_state=0), {"n_estimators": [100, 300], "max_depth": [3, 6, None], "class_weight": [None, "balanced"]}, cv=StratifiedKFold(5, shuffle=True, random_state=0), scoring="f1", n_jobs=-1) grid.fit(X_tr, y_tr) print("best params:", grid.best_params_) print("CV F1:", round(grid.best_score_, 3)) print("test accuracy (touched once, at the end):", round(accuracy_score(y_te, grid.predict(X_te)), 3))
depth=1 train=0.923 test=0.921
depth=3 train=0.976 test=0.939
depth=None train=1.000 test=0.912
best params: {'class_weight': 'balanced', 'max_depth': None, 'n_estimators': 100}
CV F1: 0.969
test accuracy (touched once, at the end): 0.947
The unlimited tree scores 1.000 on training data but only 0.912 on the test set: overfitting.
Classification metrics, ROC and PR curves
A spam filter can be right or wrong in four ways: spam caught (TP), a real email wrongly flagged (FP), spam missed (FN), a real email left alone (TN). Precision: of the emails I flagged, how many were really spam? Recall: of all the spam, how much did I catch? Which one matters more depends on which mistake hurts more.
Everyday example: A smoke alarm needs high recall (never miss a fire), even if it sometimes beeps at toast.
TP: predicted positive, actually positive. FP: predicted positive, actually negative (Type I). FN: predicted negative, actually positive (Type II). TN: predicted negative, actually negative. Note that scikit-learn's confusion_matrix puts actual on rows, so always check the orientation.
| Metric | Formula | Answers |
|---|---|---|
| Accuracy | \(\frac{TP+TN}{TP+TN+FP+FN}\) | How often am I right? Misleading on imbalanced data. |
| Precision | \(\frac{TP}{TP+FP}\) | When I say positive, how often am I right? (spam filters) |
| Recall / sensitivity / TPR | \(\frac{TP}{TP+FN}\) | Of real positives, how many did I catch? (disease screening, fraud) |
| Specificity / TNR | \(\frac{TN}{TN+FP}\) | Of real negatives, how many did I clear? |
| F1 | \(\frac{2PR}{P+R}\) | Harmonic mean of precision and recall. |
| Balanced accuracy | \(\frac{\text{Recall}+\text{Specificity}}{2}\) | Accuracy that respects class imbalance. |
| MCC | \(\frac{TP\cdot TN - FP\cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}\) | Correlation between prediction and truth, −1 to +1. Strong single number for imbalance. |
| Cohen's κ | \(\frac{p_o - p_e}{1-p_e}\) | Agreement beyond chance. |
| Log loss | \(-\frac1n\sum[y_i\log p_i + (1-y_i)\log(1-p_i)]\) | Quality of probabilities. Lower is better; confident mistakes cost the most. |
Try it: confusion-matrix calculator
InteractiveExample values show an imbalanced set: accuracy looks excellent while recall is only 0.80. Change TN to 90 and watch accuracy fall while precision and recall stay put.
ROC curve and AUC
Plots TPR (recall) against FPR (1 − specificity) across every threshold. AUC is the probability that a random positive gets a higher score than a random negative.
- 1.0 perfect · 0.9–1.0 excellent · 0.8–0.9 good · 0.7–0.8 fair · 0.5 random
- Below 0.5: worse than random; the labels are probably flipped.
Precision–Recall curve
Plots precision against recall across thresholds. Prefer it over ROC when positives are rare: ROC can look strong because the huge TN count keeps FPR small.
Average Precision (AP) summarises the area under the PR curve. A random classifier's baseline is the positive rate, not 0.5.
Python example Confusion matrix, thresholds and a classification report
from sklearn.datasets import load_breast_cancer 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, classification_report, roc_auc_score, average_precision_score X, y = load_breast_cancer(return_X_y=True) y = 1 - y # make "malignant" the positive class (1) X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0) model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr) proba = model.predict_proba(X_te)[:, 1] for thr in [0.5, 0.2]: # lower threshold -> higher recall pred = (proba >= thr).astype(int) tn, fp, fn, tp = confusion_matrix(y_te, pred).ravel() # sklearn: rows = actual print(f"threshold {thr}: TP={tp} FP={fp} FN={fn} TN={tn} recall={tp/(tp+fn):.3f} precision={tp/(tp+fp):.3f}") print("ROC-AUC:", round(roc_auc_score(y_te, proba), 3), "| PR-AUC:", round(average_precision_score(y_te, proba), 3)) print(classification_report(y_te, (proba >= 0.5).astype(int), target_names=["benign", "malignant"], digits=3))
threshold 0.5: TP=51 FP=0 FN=2 TN=90 recall=0.962 precision=1.000
threshold 0.2: TP=52 FP=9 FN=1 TN=81 recall=0.981 precision=0.852
ROC-AUC: 0.996 | PR-AUC: 0.994
precision recall f1-score support
benign 0.978 1.000 0.989 90
malignant 1.000 0.962 0.981 53
accuracy 0.986 143
macro avg 0.989 0.981 0.985 143
weighted avg 0.986 0.986 0.986 143
Lowering the threshold from 0.5 to 0.2 catches one more malignant case (recall up) at the cost of 9 false alarms (precision down).
Time series forecasting
A time series is data recorded in time order: daily sales, hourly temperature, monthly users. Most series are a mix of a trend (slowly going up or down), seasonality (repeating patterns: weekends, December) and random noise. Forecasting means projecting these patterns forward, and being honest about the uncertainty.
Everyday example: An ice-cream shop expects more sales every summer (seasonality) and a bit more each year as it grows (trend).
Rules that differ from normal ML
- Never shuffle. Train on the past, test on the most recent period.
- Cross-validate with a rolling window (
TimeSeriesSplit). - Only use features known at forecast time (no future values).
- Always compare with a naive forecast: "same as last period" or "same as last year".
Methods, simple to complex
- Naive / seasonal naive: the essential baseline.
- Moving average: smooths noise; lags behind turns.
- Exponential smoothing / Holt-Winters: level + trend + season, recent data weighted more.
- ARIMA / SARIMA: models how each value depends on recent values and errors.
- Prophet: trend + seasonality + holidays, easy to use.
- ML with lag features: gradient boosting on "sales 7 days ago", "day of week", etc.
Key terms
- Lag: a past value used as a feature (yesterday's sales).
- Stationary: mean and variance don't drift over time; ARIMA needs this (use differencing).
- Horizon: how far ahead you forecast.
Forecast error metrics
- MAE: average miss in units.
- MAPE: average % miss; breaks when actual values are near 0.
- RMSE: penalises big misses.
Try it: smooth a noisy series
InteractiveFour years of monthly sales. A moving average replaces each point with the average of the last N months. Small windows follow the noise; a 12-month window removes the seasonal wave and reveals the trend.
Python example Forecast monthly sales and beat the baselines
import numpy as np, pandas as pd from statsmodels.tsa.holtwinters import ExponentialSmoothing # 4 years of monthly sales: trend + yearly seasonality + noise rng = np.random.default_rng(3) idx = pd.date_range("2021-01-01", periods=48, freq="MS") t = np.arange(48) sales = pd.Series(200 + 3*t + 30*np.sin(2*np.pi*t/12) + rng.normal(0, 8, 48), index=idx).round(1) train, test = sales[:-12], sales[-12:] # split by TIME, never randomly mae = lambda f: np.abs(test.values - np.asarray(f)).mean() naive = np.repeat(train.iloc[-1], 12) # tomorrow = today seasonal = train.iloc[-12:].values # same month last year moving = np.repeat(train.iloc[-3:].mean(), 12) # 3-month average hw = ExponentialSmoothing(train, trend="add", seasonal="add", seasonal_periods=12).fit() holt = hw.forecast(12) for name, f in [("naive", naive), ("seasonal naive", seasonal), ("3-month average", moving), ("Holt-Winters", holt)]: print(f"{name:16s} MAE = {mae(f):.1f}") print("next 3 months:", holt.iloc[:3].round(0).to_dict())
naive MAE = 28.9
seasonal naive MAE = 31.6
3-month average MAE = 40.7
Holt-Winters MAE = 9.5
next 3 months: {Timestamp('2024-01-01 00:00:00'): 316.0, Timestamp('2024-02-01 00:00:00'): 322.0, Timestamp('2024-03-01 00:00:00'): 347.0}
Holt-Winters models both trend and season, so it cuts the error to a third of the naive forecast.
Explain, deploy and monitor models
A model in a notebook helps nobody. Deploying means putting it somewhere other systems can ask it for predictions, like a website or an app. Then you monitor it, because the world changes: customers behave differently, prices move, and a model that was accurate last year slowly gets worse (drift). You also need to explain it, so people trust it and can spot mistakes.
Everyday example: A weather app's forecast model runs on a server, answers millions of requests, and is checked every day against what actually happened.
Ways to deploy
- Batch: score all customers every night, write results to a table. Simplest.
- Real-time API: a web service returns a prediction in milliseconds (FastAPI, Flask).
- Streaming: score events as they arrive (fraud on each payment).
- On-device / edge: the model runs on the phone or machine.
MLOps toolkit
- Version everything: code (Git), data, model (MLflow registry).
- Package: Docker image with the model and its exact library versions.
- Automate: CI/CD tests and deploys; scheduled retraining.
- Roll out safely: shadow mode, canary (5% of traffic), easy rollback.
What to monitor
- System: latency, errors, uptime.
- Data drift: inputs no longer look like training data.
- Concept drift: the relationship itself changed (what predicts fraud changes).
- Performance: accuracy once true outcomes arrive; business KPI.
Explaining models
- Global: which features matter overall (permutation importance, SHAP summary).
- Local: why this one prediction (SHAP values, LIME).
- Fairness: compare error rates across groups (age, gender, region).
Communicating results
Tell a story, not a method
- Start with the answer and the decision it supports.
- Show one clear chart per point, labelled in plain words.
- Give the impact in business units (₹, customers, hours).
- State limits and confidence honestly.
- End with a recommendation and next step.
Example summary
"The churn model finds 3× more at-risk customers than our current rule. Calling its top 500 each month would keep about 60 more customers (≈ ₹9 lakh a year). It is less reliable for customers under 2 months old; we'll retrain quarterly and review fairness across regions."
Python example Save a model, explain it, and check for drift
import joblib, numpy as np from scipy import stats from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.inspection import permutation_importance data = load_breast_cancer() X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, test_size=0.25, random_state=0) model = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_tr, y_tr) # 1. Save and reload (what the API server does at start-up) joblib.dump(model, "model_v1.joblib") model = joblib.load("model_v1.joblib") # 2. Explain: which features matter? (permutation importance on test data) imp = permutation_importance(model, X_te, y_te, n_repeats=10, random_state=0) top = np.argsort(imp.importances_mean)[::-1][:3] for i in top: print(f"{data.feature_names[i]:22s} {imp.importances_mean[i]:.3f}") # 3. Monitor: has a feature's distribution drifted in production? live = X_te[:, 0] * 1.15 # pretend incoming data shifted by 15% ks = stats.ks_2samp(X_tr[:, 0], live) print(f"drift check on '{data.feature_names[0]}': KS p-value = {ks.pvalue:.4f} ->", "ALERT" if ks.pvalue < 0.01 else "ok")
worst area 0.021 worst radius 0.020 worst perimeter 0.013 drift check on 'mean radius': KS p-value = 0.0000 -> ALERT
Python example Serve the model as a web API (FastAPI)
# app.py -> run with: uvicorn app:app --reload import joblib, pandas as pd from fastapi import FastAPI from pydantic import BaseModel model = joblib.load("churn_model.joblib") # saved in the Module 01 example app = FastAPI() class Customer(BaseModel): tenure_months: int monthly_bill: float support_calls: int contract: str @app.post("/predict") def predict(c: Customer): risk = model.predict_proba(pd.DataFrame([c.model_dump()]))[0, 1] return {"churn_risk": round(float(risk), 3)} # curl -X POST localhost:8000/predict -H "Content-Type: application/json" \ # -d '{"tenure_months":3,"monthly_bill":80,"support_calls":4,"contract":"monthly"}'
Not run here (needs a web server). Package it with a Dockerfile to deploy anywhere.
Neural networks: neurons, backpropagation and architectures
A neuron is a tiny calculator: multiply each input by how important it is (a weight), add them up, and pass the total through a switch. Stack thousands of them in layers and you get a neural network. Training is: guess, measure how wrong the guess was (the loss), nudge the weights to be a bit less wrong, and repeat thousands of times.
Everyday example: Deciding whether to go out: weather matters a lot, traffic a little, add them up, then decide yes or no.
Keras 3 is a high-level API that runs on TensorFlow, JAX or PyTorch. A feed-forward network takes features in an input layer, transforms them through hidden layers with non-linear activations, and produces a prediction \(\hat y\).
Inside one neuron: forward pass, loss, backprop
- Forward: \(x_1=2, x_2=3\), \(w_1=0.5, w_2=0.2\), \(b=0.1\). \(z = 1.0 + 0.6 + 0.1 = 1.7\); ReLU gives \(a = 1.7\).
- Loss (binary cross-entropy): true \(y = 1\), predicted \(p = 0.8\). \(L = -[y\log p + (1-y)\log(1-p)] = -\ln 0.8 = 0.223\).
- Backprop: the chain rule gives \(\partial L/\partial w\) for every weight, flowing from the loss back to the input.
- Update (gradient descent): \(w_{new} = w_{old} - \eta\,\partial L/\partial w\). With \(w = 0.50\), gradient 0.20 and \(\eta = 0.10\): \(0.50 - 0.02 = 0.48\).
- Repeat over all batches for many epochs: dataset → forward → loss → backprop → update.
Try it: be a neuron
InteractiveTwo inputs, each multiplied by a weight, plus a bias, then passed through an activation. Starts at the worked example above.
The learning rate \(\eta\) sets the step size. Too large and the loss bounces or diverges; too small and training crawls.
- 1BuildStack layers with
Sequential(or the Functional API / subclassing for branching models). - 2CompileChoose an optimizer (how weights update), a loss (what to minimise) and metrics (what to report).
- 3FitTrain for some epochs in mini-batches, holding out a validation split.
- 4Evaluate & predictScore on unseen test data; sigmoid outputs are probabilities to threshold (often 0.5).
import keras from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=42) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = keras.Sequential([ keras.Input(shape=(X_train.shape[1],)), keras.layers.Dense(64, activation="relu"), keras.layers.Dense(32, activation="relu"), keras.layers.Dense(1, activation="sigmoid"), # 1 unit + sigmoid = binary ]) model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"]) history = model.fit(X_train, y_train, epochs=20, batch_size=32, validation_split=0.2) loss, acc = model.evaluate(X_test, y_test, verbose=0) probs = model.predict(X_test) # probabilities in [0, 1] labels = (probs > 0.5).astype(int)
"cacuracy", which raises an error. Use "accuracy".| Task | Output layer | Loss |
|---|---|---|
| Binary classification | Dense(1, "sigmoid") | binary_crossentropy |
| Multi-class, one-hot labels | Dense(K, "softmax") | categorical_crossentropy |
| Multi-class, integer labels | Dense(K, "softmax") | sparse_categorical_crossentropy |
| Regression | Dense(1) (linear) | mse or mae |
Vocabulary
- Epoch: one full pass over the training data.
- Batch size: samples per gradient update.
- Backpropagation: chain rule to get gradients of loss w.r.t. every weight.
- Optimizer: rule for applying gradients (SGD, Adam, RMSprop).
Fighting overfitting
- Watch training vs validation loss curves; divergence means overfitting.
- Dropout, L2 regularisation, early stopping, more data, data augmentation.
- Start small; add capacity only when the model underfits.
Python example Train one neuron from scratch with NumPy
import numpy as np # One neuron (logistic regression) trained with gradient descent, no libraries rng = np.random.default_rng(0) X = rng.normal(size=(200, 2)) y = (X[:, 0] + 2*X[:, 1] > 0).astype(float) # the rule the neuron must discover w, b, lr = np.zeros(2), 0.0, 0.5 sigmoid = lambda z: 1 / (1 + np.exp(-z)) for epoch in range(301): p = sigmoid(X @ w + b) # forward pass loss = -np.mean(y*np.log(p + 1e-9) + (1-y)*np.log(1 - p + 1e-9)) grad_w = X.T @ (p - y) / len(y) # backprop (for BCE + sigmoid) grad_b = np.mean(p - y) w -= lr * grad_w; b -= lr * grad_b # update if epoch % 100 == 0: print(f"epoch {epoch:3d} loss {loss:.3f} accuracy {((p > .5) == y).mean():.2f}") print("learned weights:", w.round(2), "(ratio ≈ 1:2, like the true rule)")
epoch 0 loss 0.693 accuracy 0.53 epoch 100 loss 0.161 accuracy 0.99 epoch 200 loss 0.128 accuracy 0.99 epoch 300 loss 0.112 accuracy 0.99 learned weights: [2.56 5.59] (ratio ≈ 1:2, like the true rule)
The true rule is x₁ + 2x₂ > 0; the learned weights keep that 1 : 2 ratio (their size just sets how confident the model is).
Backpropagation: how a network learns from its errors
After each guess, the network measures its error, then walks backwards through the layers asking every weight "how much did you contribute to this mistake?". Each weight then moves a little in the direction that shrinks the error. That backward walk, using the chain rule from calculus, is backpropagation.
- 1Forward passInputs flow through the layers to a prediction: \(x \to \hat y\).
- 2Compute lossCompare prediction with the truth: \(L(\hat y, y)\).
- 3Backward passChain rule gives each weight's gradient \(\partial L/\partial w\), from the output layer back to the first.
- 4Update weights\(w \leftarrow w - \eta\,\partial L/\partial w\); repeat for every batch and epoch.
The gradient for an early weight is a product of the local slopes along the path from that weight to the loss. If those slopes are small (e.g. saturated sigmoids, max 0.25), the product shrinks toward zero: the vanishing gradient problem that ReLU, LSTMs and residual connections were designed to ease.
Python example Backpropagation by hand: a 2-layer network learns XOR
import numpy as np # A 2-layer network learns XOR, which a single neuron cannot. Backprop by hand. X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float) y = np.array([[0], [1], [1], [0]], dtype=float) rng = np.random.default_rng(1) W1, b1 = rng.normal(size=(2, 4)), np.zeros((1, 4)) W2, b2 = rng.normal(size=(4, 1)), np.zeros((1, 1)) sig = lambda z: 1 / (1 + np.exp(-z)) lr = 1.0 for epoch in range(5001): h = sig(X @ W1 + b1) # forward: hidden layer p = sig(h @ W2 + b2) # forward: output loss = np.mean((p - y) ** 2) d_out = 2 * (p - y) / len(X) * p * (1 - p) # backward: chain rule at the output d_hid = (d_out @ W2.T) * h * (1 - h) # ...passed back to the hidden layer W2 -= lr * h.T @ d_out; b2 -= lr * d_out.sum(0, keepdims=True) W1 -= lr * X.T @ d_hid; b1 -= lr * d_hid.sum(0, keepdims=True) if epoch % 1000 == 0: print(f"epoch {epoch:4d} loss {loss:.4f}") print("predictions:", p.round(2).ravel(), "targets:", y.ravel())
epoch 0 loss 0.2749 epoch 1000 loss 0.0135 epoch 2000 loss 0.0023 epoch 3000 loss 0.0012 epoch 4000 loss 0.0008 epoch 5000 loss 0.0006 predictions: [0.02 0.98 0.98 0.03] targets: [0. 1. 1. 0.]
A single neuron can never learn XOR (no straight line separates it); one hidden layer plus backprop solves it.
Neural network architectures and when to use them
| Architecture | How it works | Best for | Keras layer |
|---|---|---|---|
| Perceptron | One neuron: weighted sum + bias + step/activation; a straight-line boundary | Simple binary problems; the building block | Dense(1) |
| MLP (feed-forward) | Stacked fully connected layers, trained with backprop | Tabular data, general classification and regression | Dense |
| CNN | Shared filters find local patterns; pooling shrinks | Images, video, object detection | Conv2D, MaxPooling2D |
| RNN | Reads a sequence step by step, carrying a hidden state (memory) | Short sequences, simple time series | SimpleRNN |
| LSTM | RNN with forget / input / output gates and a cell state; keeps long-term memory | Longer sequences, speech, older NLP | LSTM |
| GRU | Simpler gated RNN (update and reset gates); faster, fewer parameters | Sequences when LSTM is too slow | GRU |
| Autoencoder | Encoder squeezes input to a small code; decoder rebuilds it | Anomaly detection, compression, denoising | Dense encoder + decoder |
| Transformer | Self-attention relates all tokens at once, in parallel | Language (BERT, GPT), translation, vision (ViT), multimodal | MultiHeadAttention |
Choose by data type: tables → gradient boosting or an MLP; images → CNN or vision transformer; text → transformer; sequences/time series → start with gradient boosting on lag features, then LSTM/GRU or transformers.
Python example A perceptron acting as an AND gate
import numpy as np def perceptron(x, w, b): # the simplest neural network unit return 1 if np.dot(x, w) + b >= 0 else 0 w, b = np.array([1.0, 1.0]), -1.5 # weights that make an AND gate for x in [(0, 0), (0, 1), (1, 0), (1, 1)]: print(x, "->", perceptron(np.array(x), w, b))
(0, 0) -> 0 (0, 1) -> 0 (1, 0) -> 0 (1, 1) -> 1
Python example An LSTM for sequence forecasting (Keras)
import numpy as np import keras from keras import layers # Toy data: predict the next value of a sine wave from the previous 20 values t = np.arange(0, 100, 0.1) series = np.sin(t) window = 20 X = np.array([series[i:i + window] for i in range(len(series) - window)])[..., None] # (samples, 20, 1) y = series[window:] model = keras.Sequential([ keras.Input(shape=(window, 1)), # (timesteps, features) layers.LSTM(32), # swap for layers.GRU(32) or layers.SimpleRNN(32) layers.Dense(1), ]) model.compile(optimizer="adam", loss="mse") model.fit(X, y, epochs=5, batch_size=32, validation_split=0.2, verbose=0) print("next value:", model.predict(X[-1:], verbose=0)[0, 0], "| true:", y[-1])
Not run here (needs TensorFlow, JAX or PyTorch installed). The source sheet imports from tensroflow.keras, a typo; with Keras 3, import keras is simplest.
Activation functions and softmax
The activation function is the switch inside each neuron. Without it, stacking layers achieves nothing: everything collapses into one straight line. ReLU passes positive numbers and blocks negatives. Sigmoid squashes any number into 0–1, like a probability. Softmax turns scores for several options into percentages that add up to 100%.
Everyday example: Softmax turns a judge's raw scores for three dancers into "66% / 24% / 10% chance of winning".
Without a non-linear activation, any stack of layers collapses into one linear model. The derivative matters just as much: it is what backpropagation multiplies through the network.
| Function | \(f(x)\) | \(f'(x)\) | Range · notes |
|---|---|---|---|
| Linear | \(ax + c\) | \(a\) | \((-\infty,\infty)\) · regression output |
| Sigmoid | \(\frac{1}{1+e^{-x}}\) | \(f(x)(1-f(x))\) | (0, 1) · binary output; max gradient 0.25, so it vanishes in deep nets |
| Tanh | \(\frac{e^x-e^{-x}}{e^x+e^{-x}} = \frac{2}{1+e^{-2x}}-1\) | \(1-f(x)^2\) | (−1, 1) · zero-centred; still saturates |
| ReLU | \(\max(0,x)\) | 0 for \(x<0\), 1 for \(x>0\) | [0, ∞) · default for hidden layers; neurons can "die" |
| Leaky / Parametric ReLU | \(x\) if \(x\ge0\), else \(\alpha x\) | 1 or \(\alpha\) | Leaky: fixed \(\alpha=0.01\). PReLU: \(\alpha\) is learned. |
| ELU | \(x\) if \(x\ge0\), else \(\alpha(e^{x}-1)\) | 1, or \(f(x)+\alpha\) | (−α, ∞) · smooth, negative outputs |
| GELU | \(x\,\Phi(x)\) | \(\Phi(x) + x\,\phi(x)\) | Used in BERT/GPT transformers |
| Swish / SiLU | \(x\,\sigma(x)\) | \(\sigma(x) + x\sigma(x)(1-\sigma(x))\) | Smooth, non-monotonic; used in EfficientNet, LLaMA (SwiGLU) |
| Function | Output range | Typical use |
|---|---|---|
| Linear | \((-\infty, \infty)\) | Regression output layer |
| Sigmoid | (0, 1) | Binary output layer |
| Tanh | (−1, 1) | Hidden layers, RNNs |
| ReLU | [0, ∞) | Hidden layers (default) |
| Leaky ReLU | \((-\infty, \infty)\) | Hidden layers; avoids dead neurons |
| ELU | (−α, ∞); (−1, ∞) for α = 1 | Hidden layers |
| Swish / SiLU | ≈ [−0.278, ∞) | Hidden layers (EfficientNet, LLaMA) |
| GELU | ≈ [−0.17, ∞) | Transformers (BERT, GPT) |
| Softmax | (0, 1), sums to 1 | Multi-class output layer |
Try it: activation plotter
InteractiveSoftmax
Turns a vector of raw scores (logits) into probabilities that sum to 1. Scores 2.0, 1.0, 0.1 become 0.659, 0.242, 0.099 (often rounded to 0.7 / 0.2 / 0.1). Dividing logits by a temperature \(T\) first flattens (\(T>1\)) or sharpens (\(T<1\)) the distribution. This is the same temperature knob you set on an LLM.
Try it: softmax with temperature
InteractivePython example Activation functions and softmax with temperature
import numpy as np x = np.array([-2.0, -0.5, 0.0, 0.5, 2.0]) relu = np.maximum(0, x) sigmoid = 1 / (1 + np.exp(-x)) tanh = np.tanh(x) leaky = np.where(x > 0, x, 0.01 * x) print("relu ", relu) print("sigmoid", sigmoid.round(3)) print("tanh ", tanh.round(3)) print("leaky ", leaky) def softmax(z, T=1.0): z = np.asarray(z) / T e = np.exp(z - z.max()) # subtract max for numerical stability return e / e.sum() print("softmax ", softmax([2.0, 1.0, 0.1]).round(3)) print("softmax T=0.5", softmax([2.0, 1.0, 0.1], T=0.5).round(3)) print("softmax T=2 ", softmax([2.0, 1.0, 0.1], T=2).round(3))
relu [0. 0. 0. 0.5 2. ] sigmoid [0.119 0.378 0.5 0.622 0.881] tanh [-0.964 -0.462 0. 0.462 0.964] leaky [-0.02 -0.005 0. 0.5 2. ] softmax [0.659 0.242 0.099] softmax T=0.5 [0.864 0.117 0.019] softmax T=2 [0.502 0.304 0.194]
Computer vision and CNNs
To a computer, a photo is a grid of numbers, one per pixel (brightness). A CNN slides small pattern-detectors (filters) over the grid. Early layers find edges, later ones find shapes, and the last ones find whole objects like "cat ear". Pooling shrinks the picture while keeping the strongest signals.
Everyday example: Scanning a page with a magnifying glass, square by square, looking for one pattern.
Image representation
An image is an array of pixel values: grayscale is \(H\times W\) (1 channel); colour is \(H\times W\times 3\) (RGB). Values are usually 0–255, scaled to 0–1 before training.
Preprocessing
- Resize (e.g. 224×224 → 112×112)
- Normalise pixel values
- Denoise; convert to grayscale when colour doesn't matter
- Data augmentation: flips, crops, rotations, colour jitter (training only)
Convolution
A small filter (kernel) slides over the image; at each position you multiply element-wise and sum. Deep-learning libraries actually compute cross-correlation (no kernel flip), which is what's shown here. Output size with no padding, stride 1: \((n - k + 1)\), so a 5×5 image and 3×3 kernel give 3×3.
Top-middle cell: the window covers columns 2–4 of rows 1–3, i.e. (1,1,0) three times. \(1\cdot1 + 1\cdot0 + 0\cdot(-1) = 1\) per row, ×3 = 3. The strong response marks the vertical edge where 1s turn into 0s. After ReLU the −1s become 0.
Try it: slide a filter over an image
InteractiveThe left grid is a tiny 5×5 image (1 = bright, 0 = dark). Click pixels to change it. Press Next step to slide the 3×3 filter one position; each output cell is the sum of pixel × filter value.
Pooling
Pooling shrinks spatial size, cuts computation and makes the model tolerant of small shifts. Max pooling keeps the strongest activation in each window.
Padding and stride
Padding \(p\)
Adds a border of zeros so edge pixels get used and the output doesn't shrink. 4×4 input, 3×3 filter, stride 1: \(p = 0\) gives 2×2 ("valid"); \(p = 1\) gives 4×4 ("same").
Stride \(s\)
How far the filter moves each step. Stride 2 roughly halves width and height: a 224×224 input with a 3×3 filter, \(p = 1\), \(s = 2\) gives 112×112.
Max vs average pooling
Each output cell summarises one 2×2 window. Top-left window 1, 3, 4, 6: max 6, average 14/4 = 3.5.
CNN architecture and tasks
Input → [Conv + ReLU → Pool] × N → Flatten → Fully connected → Softmax. Early layers learn edges, later layers learn textures, parts and objects.
| Task | Output | Example models |
|---|---|---|
| Classification | One label per image | ResNet, EfficientNet, ViT |
| Object detection | Class + box (x, y, width, height) + confidence per object | YOLO, Faster R-CNN, DETR |
| Semantic segmentation | Class label for every pixel | U-Net, DeepLab |
| Instance segmentation | Pixel mask per separate object | Mask R-CNN, SAM |
Applications: self-driving, medical imaging, face recognition, industrial inspection, agriculture monitoring, video surveillance, visual search, retail.
Training a CNN
Same loop as any network (forward → loss → backprop → update). Image classifiers use categorical cross-entropy:
True label [1, 0, 0], predicted [0.7, 0.2, 0.1]: only the true class counts, so \(L = -\ln 0.7 = 0.357\). If the model had said 0.95 for the true class, \(L = 0.051\).
Python example A small CNN for handwritten digits (Keras)
import keras from keras import layers (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # 28x28 grey images x_train, x_test = x_train[..., None] / 255.0, x_test[..., None] / 255.0 # add channel, scale 0-1 model = keras.Sequential([ keras.Input(shape=(28, 28, 1)), layers.Conv2D(32, 3, activation="relu"), # 32 filters of 3x3 layers.MaxPooling2D(2), layers.Conv2D(64, 3, activation="relu"), layers.MaxPooling2D(2), layers.Flatten(), layers.Dropout(0.3), layers.Dense(10, activation="softmax"), # 10 digits ]) model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(x_train, y_train, epochs=3, batch_size=128, validation_split=0.1) print(model.evaluate(x_test, y_test, verbose=0)) # typically about 99% test accuracy
Not run here (downloads MNIST and needs TensorFlow, JAX or PyTorch installed). Runs in a few minutes on a laptop CPU.
How LLMs work: attention and evaluation
An LLM is a very advanced autocomplete, trained on a huge amount of text. It chops your message into tokens, turns each into a list of numbers that captures its meaning, works out how the words relate to each other (attention), and predicts the next token. It repeats that, one token at a time, until the answer is finished.
Everyday example: Your phone keyboard suggesting the next word, scaled up enormously.
- 1Prompt"How do I prepare for a PM interview?"
- 2TokenizationText is split into sub-word tokens (BPE / SentencePiece). A token is roughly ¾ of an English word.
- 3Token IDsEach token maps to an integer in the vocabulary.
- 4EmbeddingsIDs look up learned vectors (thousands of dimensions). Similar meanings sit close together.
- 5Positional encodingAdds word-order information (sinusoidal, learned, or rotary / RoPE).
- 6Self-attentionEvery token weighs every earlier token: \(\text{softmax}(QK^\top/\sqrt{d_k})V\).
- 7Transformer layersAttention + feed-forward blocks, repeated tens of times, build up context.
- 8Next-token predictionA softmax over the vocabulary gives probabilities for the next token.
- 9DecodingPick a token (greedy, or sample with temperature / top-p), append it, and repeat.
- 10ResponseStop at an end token or a length limit; detokenize to text.
Try it: see text as tokens
InteractiveA simplified tokenizer for illustration: real ones (BPE) learn their pieces from data, so the exact splits and ID numbers differ. The idea is the same: common words are one token, rare long words become several.
Why vectors?
Embeddings turn meaning into geometry. "interview", "hiring" and "career" land near each other; "pizza" lands far away. Distance is usually measured with cosine similarity:
Clarifications
- The model outputs a distribution; the decoder chooses the token. It isn't always the top one.
- Generation is autoregressive: one token per forward pass, so long outputs are slow and costly.
- The context window caps prompt + output tokens.
Python example Self-attention in a few lines of NumPy
import numpy as np # Scaled dot-product self-attention on 3 toy tokens with 4-number embeddings rng = np.random.default_rng(0) tokens = ["the", "cat", "sat"] X = rng.normal(size=(3, 4)) # embeddings (one row per token) Wq, Wk, Wv = (rng.normal(size=(4, 4)) for _ in range(3)) Q, K, V = X @ Wq, X @ Wk, X @ Wv scores = Q @ K.T / np.sqrt(K.shape[1]) mask = np.triu(np.ones((3, 3)), 1) * -1e9 # a token may only look at earlier tokens weights = np.exp(scores + mask); weights /= weights.sum(axis=1, keepdims=True) print("attention weights (row = token looking, column = token looked at):") for t, row in zip(tokens, weights): print(f" {t:4s}", row.round(2)) out = weights @ V # context-aware representations print("output shape:", out.shape)
attention weights (row = token looking, column = token looked at): the [1. 0. 0.] cat [0.61 0.39 0. ] sat [0.05 0.01 0.94] output shape: (3, 4)
Random weights here, so the numbers mean nothing. What to notice: each row sums to 1, and the first token can only attend to itself.
Python example Tokenize text with a real tokenizer
from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained("gpt2") ids = tok.encode("Data science is unbelievably useful!") print(ids) # a list of integer token IDs print(tok.convert_ids_to_tokens(ids)) # the pieces; "Ġ" marks a leading space print(len(ids), "tokens")
Not run here (downloads the tokenizer). Compare its splits with the toy tokenizer above.
Self-attention, step by step
Each word asks a question (its query), advertises what it contains (its key), and carries information to share (its value). A word compares its query with every key to decide who is relevant, turns those scores into percentages with softmax, and takes a weighted mix of the values. In "the cat sat on the mat", the word "sat" can learn to pay most attention to "cat", the one doing the sitting.
- Scores \(QK^\top\) (row = token asking): [1, 1, 0], [0, 1, 1], [1, 2, 1]. Divide by \(\sqrt{d_k} = \sqrt 2\): [0.71, 0.71, 0], [0, 0.71, 0.71], [0.71, 1.41, 0.71].
- Softmax each row: A → [0.40, 0.40, 0.20], B → [0.20, 0.40, 0.40], C → [0.25, 0.50, 0.25]. Each row sums to 1.
- Weighted sum of values: A = 0.4·[1,2] + 0.4·[2,0] + 0.2·[1,1] = [1.40, 1.00]; B = [1.40, 0.80]; C = [1.50, 0.75].
- Each output row is that token's new, context-aware representation.
Checked in NumPy (example below). With unrounded weights C's second value is 0.74; the source's 0.75 comes from rounding the weights first. The source's larger NumPy example with np.random.seed(42) also reproduces exactly.
Why divide by \(\sqrt{d_k}\)?
Dot products grow with the vector length. Without scaling, softmax gets very peaked (one weight ≈ 1, rest ≈ 0) and gradients vanish. Dividing by \(\sqrt{d_k}\) keeps scores in a workable range.
Multi-head attention
Run several attention "heads" in parallel, each with its own \(W_Q, W_K, W_V\). One head may track grammar, another who-refers-to-whom. Their outputs are concatenated and passed through a linear layer.
Causal masking (GPT-style decoders)
When generating text, a token must not peek at future tokens. A lower-triangular mask sets scores for later positions to −∞ before softmax, so their weight becomes 0. The first token can only attend to itself.
Shapes
- X: n × dmodel
- Q, K: n × dk; V: n × dv
- Scores and weights: n × n
- Output: n × dv
Python example Verify the attention example and add a causal mask
import numpy as np Q = np.array([[1, 0], [0, 1], [1, 1]], dtype=float) # tokens A, B, C K = np.array([[1, 0], [1, 1], [0, 1]], dtype=float) V = np.array([[1, 2], [2, 0], [1, 1]], dtype=float) scores = Q @ K.T / np.sqrt(K.shape[1]) # d_k = 2 weights = np.exp(scores) / np.exp(scores).sum(axis=1, keepdims=True) out = weights @ V np.set_printoptions(precision=2, suppress=True) print("scaled scores:\n", scores) print("attention weights (rows sum to 1):\n", weights) print("output:\n", out) # Causal mask: a token may not look at later tokens (used by GPT-style models) mask = np.triu(np.ones((3, 3), dtype=bool), k=1) masked = np.where(mask, -np.inf, scores) cw = np.exp(masked) / np.exp(masked).sum(axis=1, keepdims=True) print("causal weights:\n", cw)
scaled scores: [[0.71 0.71 0. ] [0. 0.71 0.71] [0.71 1.41 0.71]] attention weights (rows sum to 1): [[0.4 0.4 0.2 ] [0.2 0.4 0.4 ] [0.25 0.5 0.25]] output: [[1.4 1. ] [1.4 0.8 ] [1.5 0.74]] causal weights: [[1. 0. 0. ] [0.33 0.67 0. ] [0.25 0.5 0.25]]
Evaluating LLM output
Judging generated text is harder than judging a label, because many different answers can be right. Use several signals together.
| Metric | What it measures | Range · better | Good for |
|---|---|---|---|
| Perplexity | How surprised the model is by the true text: \(\exp\!\big(-\frac1N\sum\log P(x_i)\big)\) | ≥ 1 · lower | Comparing language models on the same data |
| Exact match | Answer identical to the reference | 0–1 · higher | Short factual answers, math, IDs |
| Token F1 | Word overlap: precision and recall of shared words | 0–1 · higher | Extractive question answering |
| ROUGE-N / ROUGE-L | Overlap of n-grams / longest common subsequence, recall-focused | 0–1 · higher | Summaries |
| BLEU | n-gram precision against references, with a brevity penalty | 0–1 · higher | Machine translation |
| METEOR | Matches exact words, stems and synonyms, and word order | 0–1 · higher | Translation, paraphrase |
| BERTScore | Similarity of contextual embeddings, so paraphrases count | ≈ 0–1 · higher | Open-ended text |
| LLM as a judge | A strong LLM grades answers against a rubric | e.g. 1–5 · higher | Helpfulness, groundedness, tone at scale |
| Human evaluation | People rate correctness, helpfulness, safety with guidelines | rubric · higher | The final word; calibrates the others |
Overlap metrics punish correct answers phrased differently. Check LLM judges against a sample of human ratings, and watch for known biases (preferring longer answers, or their own model's style).
Try it: score a model answer
InteractivePython example Exact match, token F1, ROUGE-1 and perplexity from scratch
import math from collections import Counter def exact_match(pred, ref): return int(pred.strip().lower() == ref.strip().lower()) def token_f1(pred, ref): p, r = pred.lower().split(), ref.lower().split() common = sum((Counter(p) & Counter(r)).values()) if common == 0: return 0.0 precision, recall = common / len(p), common / len(r) return 2 * precision * recall / (precision + recall) def rouge1_recall(pred, ref): # share of reference words recovered p, r = Counter(pred.lower().split()), Counter(ref.lower().split()) return sum((p & r).values()) / sum(r.values()) def perplexity(token_probs): # probabilities the model gave the true tokens return math.exp(-sum(math.log(p) for p in token_probs) / len(token_probs)) ref = "the return window for shoes is 60 days" pred = "shoes can be returned within 60 days" print("exact match:", exact_match(pred, ref)) print("token F1 :", round(token_f1(pred, ref), 3)) print("ROUGE-1 rec:", round(rouge1_recall(pred, ref), 3)) print("perplexity, confident model:", round(perplexity([0.9, 0.8, 0.95, 0.85]), 2)) print("perplexity, unsure model :", round(perplexity([0.2, 0.1, 0.3, 0.25]), 2))
exact match: 0 token F1 : 0.4 ROUGE-1 rec: 0.375 perplexity, confident model: 1.15 perplexity, unsure model : 5.08
For BLEU, METEOR and BERTScore, use the Hugging Face evaluate library: evaluate.load("bleu").
Tokens and LLM costs: how to count and estimate
LLM providers don't charge per question or per word; they charge per token, a chunk of text roughly ¾ of an English word. Everything you send (your instructions, chat history, retrieved documents) counts as input tokens. Everything the model writes back counts as output tokens, which cost several times more. Prices are quoted per 1 million tokens.
Everyday example: Like a taxi meter with two rates: a cheaper rate for the distance you bring (input) and a pricier rate for the distance the driver adds (output).
How tokens are counted
Rules of thumb for English
- 1 token ≈ 4 characters ≈ ¾ of a word.
- 100 tokens ≈ 75 words; 1,000 words ≈ 1,300–1,500 tokens.
- A full A4 page of text ≈ 600–800 tokens.
What changes the count
- The tokenizer: each model family splits text differently, so the same text has different counts on Claude, GPT and Gemini.
- Language: Hindi, Tamil, Chinese and other non-Latin scripts often use 2–4× more tokens per word than English.
- Code, numbers, rare words, emojis: split into more pieces.
- Images, PDFs, audio: converted to tokens too, often hundreds to thousands per image or page.
Hidden tokens you pay for
- The system prompt and chat history are re-sent on every turn, so long conversations get more expensive each message.
- RAG context: every retrieved chunk is input tokens.
- Tool definitions for agents.
- Reasoning / "thinking" tokens are usually billed as output even if you don't see them.
Get the exact number
- Every API response reports usage, e.g.
response.usage.input_tokensandoutput_tokens. Log these; they are your bill. - Before sending: Anthropic offers
client.messages.count_tokens(...); OpenAI'stiktokenlibrary counts GPT tokens offline; Gemini hascount_tokens.
How cost is calculated
- Each chat sends 1,500 input tokens (system prompt 1,000 + question and retrieved context 500) and gets a 300-token answer.
- On Claude Haiku 4.5 ($1 input, $5 output per million): input = 1,500 / 1,000,000 × $1 = $0.0015; output = 300 / 1,000,000 × $5 = $0.0015.
- Cost per chat = $0.0030. For 20,000 chats a month: 20,000 × $0.0030 = $60.
- With prompt caching of the 1,000-token system prompt (cache reads at $0.10 per million): per chat = 500 × $1 + 1,000 × $0.10 + 300 × $5, all ÷ 1,000,000 = $0.0021 → $42 / month.
- If replies can wait (e.g. overnight reports), the Batch API halves the price: $30 / month without caching.
Current API prices (USD per 1 million tokens)
| Model | Input | Cached input | Output | Notes |
|---|---|---|---|---|
| Claude Haiku 4.5 | $1.00 | $0.10 | $5.00 | Fast, low-cost |
| Claude Sonnet 5.5 | $2.00 | $0.20 | $10.00 | Balanced |
| Claude Opus 5.5 | $4.00 | $0.20 | $20.00 | Most capable Opus |
| GPT-6-Luna | $0.10 | $0.01 | $0.50 | OpenAI small model |
| GPT-6.1-Sol | $2.00 | $0.10 | $10.00 | OpenAI mid-tier |
| GPT-6-Astra | $10.00 | $1.00 | $50.00 | OpenAI flagship |
| Gemini 3.8 Flash | $0.75 | — | $3.75 | Promotional price to 31 Dec 2026, then $1.50 / $7.50 |
| Gemini 3.1 Pro Preview | $2.00 | — | $12.00 | Prompts ≤ 200k tokens; $4 / $18 above |
Standard (non-batch) rates from the providers' official pricing pages, checked 30 September 2026. Prices change often; always confirm on the provider's page before budgeting. Batch processing is 50% off at all three providers. Claude cache writes cost more than normal input (1.25× for a 5-minute cache).
Try it: token and cost calculator
InteractiveWays to cut the bill
Send fewer tokens
- Keep system prompts tight; trim chat history or summarise it.
- Retrieve fewer, smaller, re-ranked chunks in RAG.
- Cache long, repeated prefixes (system prompt, documents).
Pay less per token
- Route easy requests to a small model (Module 30).
- Use batch for anything that can wait.
- Cap output length (
max_tokens) and ask for concise answers. - Cache identical answers in your own app.
Python example Estimate the monthly cost of an LLM feature
# Estimate the monthly cost of an LLM feature (prices in USD per 1 million tokens) PRICES = { # (input, cached input, output) — check the provider's page before use "Claude Haiku 4.5": (1.00, 0.10, 5.00), "Claude Sonnet 5.5": (2.00, 0.20, 10.00), "Gemini 3.8 Flash": (0.75, None, 3.75), # promo rate to Dec 31, 2026; caching not modelled here "GPT-6-Luna": (0.10, 0.01, 0.50), } def cost_per_call(model, input_tokens, output_tokens, cached_tokens=0, batch=False): p_in, p_cached, p_out = PRICES[model] fresh = input_tokens - cached_tokens usd = (fresh * p_in + cached_tokens * (p_cached if p_cached is not None else p_in) + output_tokens * p_out) / 1_000_000 return usd * (0.5 if batch else 1) # Support bot: 1,500-token prompt (1,000 of it a reusable system prompt), 300-token answer, 20,000 chats a month for m in PRICES: one = cost_per_call(m, 1500, 300) cached = cost_per_call(m, 1500, 300, cached_tokens=1000) print(f"{m:18s} per chat ${one:.5f} | month ${one * 20_000:8.2f} | with caching ${cached * 20_000:8.2f}")
Claude Haiku 4.5 per chat $0.00300 | month $ 60.00 | with caching $ 42.00 Claude Sonnet 5.5 per chat $0.00600 | month $ 120.00 | with caching $ 84.00 Gemini 3.8 Flash per chat $0.00225 | month $ 45.00 | with caching $ 45.00 GPT-6-Luna per chat $0.00030 | month $ 6.00 | with caching $ 4.20
Matches the worked example: $60 a month on Claude Haiku 4.5, $42 with the system prompt cached. The simple caching maths ignores the one-time cache-write surcharge.
Python example Count tokens exactly (tiktoken and the Claude API)
# pip install tiktoken anthropic import tiktoken enc = tiktoken.get_encoding("o200k_base") # tokenizer family used by recent OpenAI models text = "Data science is unbelievably useful!" ids = enc.encode(text) print(len(ids), "tokens:", [enc.decode([i]) for i in ids]) # Claude: ask the API how many input tokens a request will use (free to call) import anthropic client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment count = client.messages.count_tokens( model="claude-haiku-4-5", system="You are a helpful support assistant.", messages=[{"role": "user", "content": "How long do I have to return my shoes?"}], ) print(count.input_tokens) # After a real call, the exact bill for that call is in response.usage # response = client.messages.create(model="claude-haiku-4-5", max_tokens=300, messages=[...]) # print(response.usage.input_tokens, response.usage.output_tokens)
Not run here: tiktoken downloads its vocabulary file on first use, and the Claude call needs an API key. Run it in your own environment.
Hugging Face Transformers
Hugging Face is like an app store for AI models. Instead of training a model from scratch, which costs a lot, you download one someone else trained and use it in three lines of code, or fine-tune it on your own data.
Everyday example: Buying a trained guide dog rather than raising and training a puppy yourself.
An open-source library that gives one API over hundreds of thousands of pretrained models for text, vision, audio and multimodal tasks. The Hub hosts the models, datasets and demo apps (Spaces).
Core classes
pipeline: one-line inference for common tasksAutoTokenizer: text → token IDs for a given modelAutoModel/AutoModelFor…: loads the right architecture with its task headTrainer+TrainingArguments: fine-tuning loop
Ecosystem
datasets: load and process datasetsevaluate: metricsaccelerate: multi-GPU / mixed precision- Hub: models, datasets, Spaces
Install: pip install "transformers[torch]" datasets evaluate accelerate
from transformers import pipeline clf = pipeline("sentiment-analysis") clf("I love this course!") # [{'label': 'POSITIVE', 'score': 0.999}] gen = pipeline("text-generation", model="gpt2") gen("The future of AI is", max_new_tokens=30, do_sample=True)[0]["generated_text"] qa = pipeline("question-answering") qa(question="What does Hugging Face build?", context="Hugging Face is a company that builds open-source tools for ML.")["answer"]
# Lower level: tokenizer + model, e.g. summarisation from transformers import AutoTokenizer, AutoModelForSeq2SeqLM tok = AutoTokenizer.from_pretrained("google/pegasus-xsum") model = AutoModelForSeq2SeqLM.from_pretrained("google/pegasus-xsum") inputs = tok(text, return_tensors="pt", truncation=True) out = model.generate(**inputs, max_new_tokens=60) print(tok.decode(out[0], skip_special_tokens=True))
| Model | Type | Good for |
|---|---|---|
| BERT, RoBERTa, DistilBERT | Encoder | Understanding: classification, NER, embeddings. DistilBERT is smaller and faster. |
| GPT-2, LLaMA | Decoder | Text generation |
| T5, BART, Pegasus | Encoder–decoder | Text-to-text: translation, summarisation |
| CLIP | Vision + text | Image–text matching, zero-shot image classification |
| Whisper | Speech | Speech recognition and translation |
Fine-tuning in outline
- Pick a base model, e.g.
distilbert-base-uncased, withAutoModelForSequenceClassification.from_pretrained(name, num_labels=2). - Tokenise your dataset with
dataset.map(tokenize, batched=True). - Set
TrainingArguments(epochs, learning rate, batch size, eval strategy). Trainer(model, args, train_dataset, eval_dataset, compute_metrics).train()
LangChain and LangGraph
LangChain is like LEGO for LLM apps: ready-made blocks for prompts, models, tools and documents that snap together into a pipeline. An agent is a block that decides by itself which tool to use next.
Everyday example: A chain is a fixed recipe; an agent is a cook who decides what to do next based on what's in the fridge.
| Component | What it does | Typical use |
|---|---|---|
| Chat models | One interface over OpenAI, Anthropic, Hugging Face and others | Generation, summarisation, chat |
| Prompt templates | Reusable prompts with variables | Few-shot, dynamic prompts |
| Chains (Runnables / LCEL) | Pipe steps together: prompt | llm | parser | Multi-step workflows |
| Tools | Wrap a function or API so a model can call it | APIs, DB queries, calculators |
| Agents | The LLM decides which tool to call next, in a loop | Research, task automation |
| Document loaders | Read PDFs, web pages, CSVs | Ingestion for RAG |
| Retrievers / vector stores | Embed and search documents (FAISS, Chroma) | RAG, Q&A over your data |
| Memory / chat history | Carry past messages into the next call | Multi-turn assistants |
from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser prompt = ChatPromptTemplate.from_template("Answer using this context:\n{context}\n\nQ: {question}") llm = ChatOpenAI(model="gpt-4o", temperature=0) chain = prompt | llm | StrOutputParser() # LCEL: each step is a Runnable docs = retriever.invoke("What is RAG?") # retriever = vector_store.as_retriever() answer = chain.invoke({"context": docs, "question": "What is RAG?"})
The RAG pipeline
- Load documents
- Chunk (e.g. 500–1000 tokens with overlap)
- Embed chunks and store in a vector DB
- At query time, embed the question and retrieve top-k chunks
- Optionally rerank
- Stuff chunks into the prompt; generate with citations
Tips
- Start with a simple chain; add agents only when steps can't be fixed in advance.
- Handle tool failures and rate limits explicitly.
- The library moves fast: agent APIs have changed across versions (
create_agentin LangChain 1.x; LangGraph for complex graphs). Check the current docs.
LangGraph: agents as graphs
A LangChain chain runs steps in a fixed line. Real agents need loops and branches: "answer, and if you're missing facts, search, then try again". LangGraph draws the workflow as a flowchart. Boxes (nodes) are Python functions or LLM calls; arrows (edges) say what runs next, and some arrows depend on a condition. A shared notebook (the state) travels through the graph so every step can read and update it.
Core pieces
- State: a typed dictionary shared by all nodes (messages, context, answer).
- Nodes: functions that take the state and return the fields they change.
- Edges: fixed transitions,
add_edge("search", "llm"). - Conditional edges: a function picks the next node.
- START / END: where execution begins and stops.
Uses
- Chatbots with memory and tools
- Research agents: search → read → summarise, looping until done
- Multi-step task automation with human approval steps
- Multi-agent systems coordinating specialists
Always cap loops (a maximum number of searches or steps) so an agent can't run forever.
Python example A LangGraph agent that loops between an LLM step and a search step
# LangGraph without an API key: the "LLM" node is a stand-in function from typing import TypedDict from langgraph.graph import StateGraph, START, END class AgentState(TypedDict): question: str context: str answer: str searches: int def llm_node(state: AgentState): if not state["context"]: # a real node would call an LLM here return {"answer": "NEED_SEARCH"} return {"answer": f"Based on: {state['context']}"} def search_node(state: AgentState): # a real node would call a search tool return {"context": "LangGraph builds stateful agent workflows as graphs.", "searches": state["searches"] + 1} def needs_search(state: AgentState) -> str: # conditional edge return "search" if state["answer"] == "NEED_SEARCH" and state["searches"] < 2 else "end" graph = StateGraph(AgentState) graph.add_node("llm", llm_node) graph.add_node("search", search_node) graph.add_edge(START, "llm") graph.add_conditional_edges("llm", needs_search, {"search": "search", "end": END}) graph.add_edge("search", "llm") # loop back after searching app = graph.compile() result = app.invoke({"question": "What is LangGraph?", "context": "", "answer": "", "searches": 0}) print(result["answer"]) print("searches used:", result["searches"])
Based on: LangGraph builds stateful agent workflows as graphs. searches used: 1
Runs offline: the LLM and search nodes are stand-in functions. Swap in a real chat model and search tool for production.
search_web node that is never defined, prints final_answer although no node ever sets it (so it prints an empty string), and has no limit on the llm ↔ search loop. The example above fixes all three and runs without an API key.RAG: chunking, embeddings and re-ranking
RAG is an open-book exam for AI. Instead of answering from memory (and sometimes making things up), the model first looks up relevant passages in your documents, then answers from them. Chunking cuts documents into passages. Embeddings let it find passages by meaning rather than exact words. Re-ranking double-checks which passages are best.
Everyday example: A company chatbot that answers from the current HR policy instead of guessing.
RAG grounds an LLM in your own documents. It reduces hallucinations, lets answers cite sources, and keeps knowledge current without retraining.
1 · Ingestion (offline)
- Load raw documents
- Split into chunks
- Embed each chunk
- Store vectors + metadata in a vector index
2 · Retrieval and generation (online)
- Embed the user query \(x \to q\) (normalised)
- Optional: filter by metadata (source, date, category)
- Similarity search → top-k chunks \(d_1 \dots d_k\)
- Optional: re-rank, keep top-n
- Build the prompt from query + context
- LLM generates the answer \(y\), grounded in the context
import faiss from sentence_transformers import SentenceTransformer from transformers import pipeline docs = ["RAG combines retrieval and generation.", "It retrieves relevant documents from a vector store.", "The LLM uses the retrieved context to generate answers."] embedder = SentenceTransformer("all-MiniLM-L6-v2") emb = embedder.encode(docs, convert_to_numpy=True).astype("float32") faiss.normalize_L2(emb) # unit vectors: inner product = cosine index = faiss.IndexFlatIP(emb.shape[1]) # exact search index.add(emb) generator = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct") def rag_answer(query, top_k=2): q = embedder.encode([query], convert_to_numpy=True).astype("float32") faiss.normalize_L2(q) scores, ids = index.search(q, top_k) context = "\n\n".join(docs[i] for i in ids[0]) prompt = f"Use only this context to answer.\n\nContext:\n{context}\n\nQuestion: {query}\nAnswer:" out = generator(prompt, max_new_tokens=200, do_sample=False, return_full_text=False) return out[0]["generated_text"].strip() print(rag_answer("What is RAG?"))
generator(...) without ever creating it. Define a text-generation pipeline first, as above (any instruction-tuned model works). return_full_text=False returns only the new text, which is cleaner than slicing off the prompt.Chunking and embeddings
Chunking strategies
- Fixed size: every N characters or tokens (e.g. 500). Simple, may cut sentences.
- Sliding window: fixed size with overlap (e.g. 500 tokens, overlap 50) to keep context across boundaries.
- Paragraph / section: split on natural boundaries such as headings.
- Semantic: split where the embedding similarity between neighbouring sentences drops.
Too small loses context; too large dilutes relevance and wastes the prompt budget.
Embeddings
- Dense vectors (hundreds to thousands of dimensions) where similar meanings sit close together.
- Use the same embedding model for indexing and querying; vectors from different models aren't comparable.
- Normalise vectors when your index uses inner product for cosine similarity.
| Embedding model | Dimensions | Good for |
|---|---|---|
| OpenAI text-embedding-3-small | 1536 | General purpose, low cost |
| OpenAI text-embedding-3-large | 3072 | Highest quality of the pair |
| BAAI/bge-m3 | 1024 | Multilingual, open weights |
| all-MiniLM-L6-v2 | 384 | Lightweight, fast, runs locally |
from langchain_text_splitters import RecursiveCharacterTextSplitter splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50) chunks = splitter.split_text(document_text) # tries paragraphs, then sentences, then words
Vector stores to try: FAISS, Chroma, Milvus, Weaviate, Pinecone, pgvector. Frameworks: LangChain, LlamaIndex.
Try it: chunk a document and search it
InteractiveA short returns policy is cut into chunks. Type a question: each chunk gets a relevance score and the top 2 would be sent to the LLM as context.
This demo scores chunks by shared words. Real RAG uses embeddings, which also match meaning ("refund" ≈ "money back") even with no shared words.
Re-ranking
A second stage after retrieval. The first-stage retriever (bi-encoder) is fast but coarse: it embeds query and documents separately. A re-ranker (cross-encoder) reads the query and each candidate together and scores relevance more accurately, but it's too slow to run over the whole corpus. So you retrieve broadly (e.g. top 20–50), re-rank, and pass the best few (top-n) to the LLM.
| Document | Retriever rank | Re-ranker score | New rank |
|---|---|---|---|
| AI applications in healthcare | 4 | 0.92 | 1 ↑ |
| History of machine learning | 2 | 0.85 | 2 |
| General AI trends in 2024 | 1 | 0.78 | 3 ↓ |
| AI in finance | 3 | 0.60 | 4 ↓ |
| Deep learning basics | 5 | 0.40 | 5 |
Query: "Latest AI trends in healthcare". The retriever ranked a generic trends article first; the re-ranker promotes the healthcare document. Re-rankers: BERT-style cross-encoders (e.g. cross-encoder/ms-marco-MiniLM-L-6-v2), BGE rerankers, Cohere Rerank.
from sentence_transformers import CrossEncoder reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2") scores = reranker.predict([(query, d) for d in candidates]) top_n = [d for _, d in sorted(zip(scores, candidates), reverse=True)[:3]]
When re-ranking pays off
- First-stage results are mixed or partly off-topic
- Large, diverse corpus; domain-specific or complex queries
- Accuracy matters more than a few extra milliseconds
Other quality levers
- Chunk size and overlap
- Hybrid search: keyword (BM25) + vector
- Approximate indexes (HNSW, IVF) once exact search gets slow
- Evaluate retrieval (recall@k) separately from answers (groundedness)
Python example Retrieve the best chunks for a question (TF-IDF version)
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity chunks = [ "Items can be returned within 30 days of delivery for a full refund.", "Shoes can be returned within 60 days if they have not been worn outside.", "Refunds go back to the original payment method within 5 to 7 business days.", "Gift cards and personalised products cannot be returned.", ] question = "How many days do I have to return my shoes?" vec = TfidfVectorizer(stop_words="english").fit(chunks + [question]) scores = cosine_similarity(vec.transform([question]), vec.transform(chunks))[0] for s, c in sorted(zip(scores, chunks), reverse=True)[:2]: print(f"{s:.2f} {c}") context = "\n".join(c for _, c in sorted(zip(scores, chunks), reverse=True)[:2]) prompt = f"Answer using only this context:\n{context}\n\nQuestion: {question}" # answer = llm.invoke(prompt) # send to any LLM
0.33 Shoes can be returned within 60 days if they have not been worn outside. 0.10 Items can be returned within 30 days of delivery for a full refund.
TF-IDF matches words; swapping in an embedding model (FAISS code above) also matches meaning.
Scaling AI in the enterprise
Making an AI demo is like cooking at home. Running AI in a company is running a restaurant: consistent recipes (prompts and tests), food safety (guardrails), rules about who can enter the kitchen (access control), inspections (governance), and coping with the dinner rush (scaling).
Everyday example: A bank's assistant must give the same correct answer to every customer, every day, safely.
A working prototype is the easy part. Twenty concepts separate a demo from a production system, grouped here by the question each answers.
Should we build it? (Strategy)
- Use cases: rank by impact, data availability and cost
- Data readiness: sources, quality, access, governance
- Model strategy: closed vs open weights, small vs large; pick the smallest model that passes your evals
What does the model see? (Context)
- Prompt engineering: instructions, examples, output format
- Context engineering: assemble the right memory, tool results and retrieved text at runtime
- RAG and vector databases: grounded answers via semantic retrieval
- Knowledge graphs: entities and relationships (person → company → product) for multi-hop questions
- Semantic layer: one agreed definition of each business metric, so the AI and the dashboards agree
How does it act? (Agents)
- AI agents: plan, then call tools, APIs and data
- Orchestration: multi-step workflows with branches (LangGraph, Temporal)
- Memory: short-term (session) and long-term (knowledge store)
Is it safe? (Trust)
- Guardrails: content filtering, policy enforcement, harm detection on inputs and outputs
- Identity & access: SSO, roles, permissions, secrets; agents act with the user's permissions
- Governance: policies, compliance, audit trails
Does it work? (Quality)
- Evaluation: accuracy, relevance, safety, factuality on a fixed test set, re-run on every change
- Observability: logs (events, errors), metrics (latency, tokens, cost), traces (end-to-end calls)
Can it run at scale? (Operations)
- Caching: reuse responses and prompt prefixes to cut latency and cost
- Scalability: load balancing, rate limits, queues across services
- Deployment: CI/CD (build → test → deploy) with versioning and rollback, for prompts too
Treat prompts, retrieval settings and model versions like code: version them, evaluate them, and roll them back when metrics drop.
Python example A minimal evaluation harness for an LLM feature
import json test_cases = [ # a fixed, versioned set of questions with checkable expectations {"q": "What is the return window for shoes?", "must_contain": "60 days"}, {"q": "Can I return a gift card?", "must_contain": "cannot"}, ] def evaluate(answer_fn): results = [] for case in test_cases: answer = answer_fn(case["q"]) # your RAG / agent pipeline results.append({**case, "answer": answer, "pass": case["must_contain"].lower() in answer.lower()}) score = sum(r["pass"] for r in results) / len(results) print(f"pass rate: {score:.0%}") return results # Run on every change to prompts, models or retrieval settings; block the release if the pass rate drops. # evaluate(my_rag_answer)
Real harnesses add LLM-as-judge scoring for groundedness, plus latency and cost tracking.
Jev and fast decision models ("System One" AI)
Many steps inside an AI app are small decisions, not essays: "Is this ticket urgent?", "Which model should answer this?", "Is this tool call risky?". A general LLM can answer them, but it is slow, costly, and returns text you must then parse. A System One model is built only for these quick judgements: you give it the situation (the state) and a typed question, and it returns a structured answer with probabilities that your code can use directly. The name borrows from psychology: "System 1" is fast, intuitive thinking; "System 2" is slow, careful reasoning.
Everyday example: A hospital receptionist sorting patients by urgency in seconds, while the doctor (the LLM) does the long diagnosis.
LLM vs System One model
- LLM (e.g. GPT, Claude): generates text; strong at reasoning, planning, coding and open-ended tasks. Overkill for one-word decisions.
- System One model (e.g. Jev from TypeSafe AI): no text generation; returns typed decisions such as a label, a score or true/false, with probabilities. Built for classification, routing, detection and verification.
- They are complementary: the LLM reasons, the fast model decides, ordinary code executes.
Jev's three question types
- Choice: pick one option from a fixed list, e.g. billing / technical / sales.
- Score: rate the state against a target, e.g. urgency low / medium / high.
- Noul: Jev's name for a true/false-style question, e.g. "is_risky".
Outputs are typed answers with probabilities (and a confidence for Choice and Score), so a threshold in your code decides the action.
Where it fits
- Model routing: send easy questions to a small cheap model, hard ones to a reasoning model.
- Tool-risk gating: check a planned tool call before an agent runs it.
- RAG: score whether a retrieved passage is relevant (a re-ranking step).
- Agent loops: "Is this request urgent?", "Should I call the search tool?"
How to think about it
- Treat it like a classifier you call as a function, not a chatbot.
- You still need an evaluation set, thresholds chosen on validation data, and monitoring (Modules 17, 18, 20).
- The same pattern can be built with a fine-tuned small model or a scikit-learn classifier; a System One model saves you training one per question.
Try it: turn a probability into an action (tool-risk gating)
InteractiveAn agent wants to run a tool. The decision model returns the probability that the call is risky. Your code, not the model, chooses what happens, using two thresholds.
Python example The same decisions as plain Python, with a conceptual Jev-style request
# Conceptual request shape (from the cheat sheet), shown as data request = { "model": "jev", "state": {"ticket_text": "I've been trying to connect my Stripe account for three days..."}, "question": {"type": "score", "target": "urgency", "levels": ["low", "medium", "high"]}, } # response = client.systemone.create(request) # conceptual; see TypeSafe docs for the real API response = {"score": 0.999, "confidence": 0.999, "probabilities": {"low": 0.001, "medium": 0.010, "high": 0.989}} # Your application code turns probabilities into actions def route_ticket(resp, threshold=0.90): return "priority queue" if resp["probabilities"]["high"] >= threshold else "normal queue" def gate_tool_call(p_risky, ask_above=0.30, block_above=0.80): if p_risky >= block_above: return "block" if p_risky >= ask_above: return "ask a human to approve" return "run the tool" print(route_ticket(response)) # priority queue print(gate_tool_call(0.97)) # block print(gate_tool_call(0.45)) # ask a human to approve print(gate_tool_call(0.05)) # run the tool
Conceptual: the request shape follows the cheat sheet, not verified SDK code. Check TypeSafe's documentation for the real client and method names before using it.
Coding interview preparation
Data science interviews usually include a coding round. The problems look endless, but most are built from about ten reusable patterns. Learn to spot the pattern ("sorted data? try binary search") and you can solve problems you've never seen. Interviewers also ask you to code ML basics from scratch (NumPy, loss functions, a training loop) and to explain how fast your code is (Big-O).
Everyday example: Finding a word in a dictionary by opening the middle, then the middle of the correct half, is binary search.
10 patterns that solve most problems
| Pattern | Idea | Spot it when | Practice problems |
|---|---|---|---|
| Two pointers | Move pointers inward from both ends | Sorted array; pairs; palindromes | Valid Palindrome, Two Sum II, 3Sum |
| Sliding window | Keep a moving window and update it incrementally | Best subarray / substring of some length | Best Time to Buy and Sell Stock, Longest Substring Without Repeating Characters |
| Fast & slow pointers | Two pointers at different speeds | Cycles, middle of a linked list | Linked List Cycle, Happy Number |
| Merge intervals | Sort by start, merge overlaps | Meetings, ranges, bookings | Merge Intervals, Insert Interval |
| DFS | Go deep along a branch, then backtrack | Trees, connected regions, all paths | Number of Islands, Flood Fill |
| BFS | Explore level by level with a queue | Shortest path in unweighted graphs | Binary Tree Level Order, Shortest Path in a Binary Matrix |
| Binary search | Halve the search range each step | Sorted data; "smallest value that works" | Search in Rotated Sorted Array, First and Last Position |
| Dynamic programming | Solve subproblems once and store results | "Number of ways", "best total", overlapping choices | Climbing Stairs, Coin Change, Longest Increasing Subsequence |
| Backtracking | Try options, undo when a path fails | All combinations / permutations, puzzles | N-Queens, Sudoku Solver, Permutations |
| Topological sort | Order tasks so dependencies come first (DAG) | Prerequisites, build order | Course Schedule, Alien Dictionary |
Try it: binary search, one step at a time
InteractiveHow fast is your code? Big-O
| Big-O | Name | Steps for 1 million items | Example |
|---|---|---|---|
| O(1) | Constant | 1 | Dictionary / set lookup |
| O(log n) | Logarithmic | ≈ 20 | Binary search |
| O(n) | Linear | 1,000,000 | One loop, two pointers, sliding window |
| O(n log n) | Linearithmic | ≈ 20 million | Sorting |
| O(n²) | Quadratic | 1 trillion | Nested loops over the same list |
A common interview upgrade: replace a nested loop (O(n²)) with a dictionary or set (O(n)). Example: checking pairs that sum to a target with a set of "numbers seen so far".
The ML coding interview checklist
NumPy & Python
Arrays and shapes, reshape / transpose, broadcasting, vectorisation, boolean and fancy indexing, concatenate / stack, where, argmax / argsort, unique, aggregates with axis, dot / @, linalg.norm, random seeds, NaN handling, list and dict comprehensions, lambdas, generators, classes.
PyTorch & deep learning
Tensors and shapes, view / reshape / permute, matmul, autograd (requires_grad, backward()), nn.Module, nn.Linear, activations, loss functions, SGD vs Adam, the optimiser loop, Dataset / DataLoader, train() vs eval(), torch.no_grad(), dropout, batch norm, embeddings, attention.
Data structures & algorithms
Arrays, strings, hash maps and sets, stacks, queues, linked lists, trees and BSTs, heaps (top-k), graphs, BFS / DFS, recursion, prefix sums, sorting and merge sort, quickselect, dynamic programming, greedy, intervals, matrix traversal, time and space complexity.
ML from scratch
Linear and logistic regression, gradient descent and mini-batch GD, MSE, binary and categorical cross-entropy, softmax, L1 / L2 regularisation, k-NN, k-means, decision trees, random forests, Naive Bayes, PCA and the covariance matrix, normalisation vs standardisation, train/test split, k-fold CV, confusion matrix, precision, recall, F1, ROC-AUC, cosine and Euclidean distance, ranking.
Most "ML from scratch" items already have runnable NumPy code in this guide: gradient descent (Module 08), one neuron (Module 21), attention (Module 24), metrics (Module 18), k-means and PCA (Module 15).
Python example Six interview patterns in Python
from collections import deque # 1. Two pointers: pair in a SORTED list that sums to target, O(n) def two_sum_sorted(nums, target): i, j = 0, len(nums) - 1 while i < j: s = nums[i] + nums[j] if s == target: return i, j if s < target: i += 1 else: j -= 1 return None # 2. Sliding window: best total of k consecutive days, O(n) def max_window_sum(a, k): cur = best = sum(a[:k]) for i in range(k, len(a)): cur += a[i] - a[i - k] best = max(best, cur) return best # 3. Binary search on sorted data, O(log n) def binary_search(a, x): lo, hi = 0, len(a) - 1 while lo <= hi: mid = (lo + hi) // 2 if a[mid] == x: return mid if a[mid] < x: lo = mid + 1 else: hi = mid - 1 return -1 # 4. BFS: fewest steps in a graph def shortest_path(graph, start, goal): q, seen = deque([(start, 0)]), {start} while q: node, d = q.popleft() if node == goal: return d for nb in graph[node]: if nb not in seen: seen.add(nb); q.append((nb, d + 1)) return -1 # 5. Dynamic programming: ways to climb n stairs taking 1 or 2 steps def climb(n): a, b = 1, 1 for _ in range(n): a, b = b, a + b return a # 6. Merge intervals def merge(iv): out = [] for s, e in sorted(iv): if out and s <= out[-1][1]: out[-1][1] = max(out[-1][1], e) else: out.append([s, e]) return out print(two_sum_sorted([1, 3, 4, 6, 8, 11], 10)) print(max_window_sum([2, 1, 5, 1, 3, 2], 3)) print(binary_search([1, 3, 5, 7, 9, 11, 13], 7)) print(shortest_path({"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["E"], "E": []}, "A", "E")) print(climb(5)) print(merge([[1, 3], [2, 6], [8, 10], [9, 12]]))
(2, 3) 9 3 2 8 [[1, 6], [8, 12]]
Outputs: indices (2, 3) since 4 + 6 = 10; best 3-day total 9; 7 at position 3; 2 steps from A to E; 8 ways to climb 5 stairs; merged intervals.
Python example The standard PyTorch training loop
import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset torch.manual_seed(0) X = torch.randn(1000, 10) y = (X[:, 0] + 2 * X[:, 1] > 0).float().unsqueeze(1) # shape (1000, 1) train = DataLoader(TensorDataset(X[:800], y[:800]), batch_size=32, shuffle=True) class Net(nn.Module): def __init__(self): super().__init__() self.layers = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Dropout(0.1), nn.Linear(32, 1)) def forward(self, x): return self.layers(x) # raw scores (logits) model = Net() loss_fn = nn.BCEWithLogitsLoss() # sigmoid + binary cross-entropy opt = torch.optim.Adam(model.parameters(), lr=1e-3) for epoch in range(10): model.train() # dropout on for xb, yb in train: opt.zero_grad() # 1. clear old gradients loss = loss_fn(model(xb), yb) # 2. forward + loss loss.backward() # 3. backprop opt.step() # 4. update weights model.eval() # dropout off with torch.no_grad(): # no gradient tracking acc = ((model(X[800:]) > 0).float() == y[800:]).float().mean() print(f"test accuracy: {acc:.3f}")
Not run here (PyTorch isn't installed in this environment). Interviewers often ask you to write exactly this loop from memory.
The AI engineering roadmap
A suggested order to learn: programming → data → classic machine learning → deep learning → LLMs → building and running AI products. You don't need all of it at once. Pick a path and go deep.
Everyday example: Learning to drive: controls first, then quiet roads, then the motorway.
A sequence of twelve stages, from foundations to production. Modules 01–31 above cover stages 1–11.
| # | Stage | Key topics |
|---|---|---|
| 1 | Intro to AI engineering | AI vs ML vs GenAI, the AI engineer role, application lifecycle |
| 2 | Python basics | Syntax, OOP, APIs & JSON, pandas & NumPy, Jupyter |
| 3 | Data & SQL | SQL, cleaning, ETL/ELT, pipelines, warehouses |
| 4 | ML fundamentals | Regression, classification, clustering, feature engineering, evaluation |
| 5 | Deep learning | Neural nets, backprop, embeddings, attention, PyTorch |
| 6 | LLM basics | Tokens, context windows, transformers, model selection, LLM APIs |
| 7 | Prompt engineering | System prompts, few-shot, structured outputs, function calling, templates |
| 8 | RAG | Chunking, embeddings, vector search, reranking, citations |
| 9 | AI agents | Tool calling, memory, planning, orchestration, human approval |
| 10 | Evaluation | Accuracy, groundedness, RAG and agent evals, latency & cost |
| 11 | MLOps & deployment | Model registry, Docker, Kubernetes, CI/CD, monitoring |
| 12 | Advanced AI | Multi-agent systems, model routing, AI security, guardrails, governance |
Tool stack
- Data: Python, pandas, NumPy, SQL, PostgreSQL, Jupyter
- ML: scikit-learn, XGBoost, LightGBM, PyTorch, TensorFlow
- RAG & agents: LangChain, LangGraph, LlamaIndex, CrewAI, Semantic Kernel
- LLM platforms: Anthropic SDK, Hugging Face, Amazon Bedrock, Microsoft Foundry
- Production: MLflow, Docker, Kubernetes, GitHub Actions, Datadog
Portfolio projects
- Enterprise RAG over a document set, with citations and an eval set
- Document extractor with structured (JSON) output
- Multi-agent workflow with a human-approval step
- Support copilot with production monitoring
Where to learn and practise
- Channels: Andrej Karpathy, DeepLearning.AI, freeCodeCamp, Hugging Face, Full Stack Deep Learning
- Data: Kaggle, Hugging Face Datasets, UCI ML Repository, OpenML, Google Dataset Search
- Reading: arXiv, Anthropic, OpenAI, Google DeepMind, Hugging Face and NVIDIA blogs
The analytics tool landscape
A common saying: analytics is 70% business understanding and 30% tools. Know one tool per layer well; the rest transfer.
| Layer | Examples |
|---|---|
| Spreadsheets | Excel, Google Sheets, Airtable |
| SQL databases | PostgreSQL, MySQL, SQL Server, Oracle, SQLite |
| Cloud warehouses | Snowflake, BigQuery, Redshift, Azure Synapse, Databricks SQL |
| Lake / lakehouse | Databricks, Delta Lake, Apache Iceberg, Amazon S3, Azure Data Lake |
| Ingestion | Fivetran, Airbyte, Stitch, Matillion, Hevo |
| Transformation | dbt, Dataform, Coalesce, SQLMesh, Alteryx |
| Languages & libraries | SQL, Python, R, Julia · pandas, NumPy, Polars, PySpark, DuckDB |
| BI & dashboards | Power BI, Tableau, Looker, Qlik, Metabase, Superset, Sigma, ThoughtSpot, Mode, Domo |
| Visualisation libraries | Matplotlib, Seaborn, Plotly, Altair, Bokeh |
| Product analytics | Mixpanel, Amplitude, PostHog, Heap, Google Analytics |
| Notebooks | Jupyter, Google Colab, Hex, Deepnote, Observable |
| Orchestration | Airflow, Dagster, Prefect, Mage |
| Data quality & observability | Great Expectations, Soda, Monte Carlo, Anomalo |
| Catalog & governance | Atlan, Alation, Collibra, Microsoft Purview, DataHub |
| Reverse ETL | Hightouch, Census, RudderStack |
| AI assistants | ChatGPT, Claude, Gemini, Power BI Copilot, ThoughtSpot Sage |
Microeconomics formulas
The economics of buying and selling. Elasticity is how much people change what they buy when the price changes. Petrol is inelastic (you buy it anyway); restaurant meals are elastic (people cut back).
Everyday example: A 10% price rise that loses you 20% of customers means demand is elastic.
Useful for pricing, demand forecasting and business-analytics work, where elasticities and margins appear as model features or outputs.
Elasticities
Price elasticity of demand: \(E_d = \dfrac{\Delta Q/Q}{\Delta P/P}\)
Price elasticity of supply: \(E_s = \dfrac{\Delta Q_s/Q_s}{\Delta P/P}\)
Income elasticity: \(E_y = \dfrac{\Delta Q/Q}{\Delta Y/Y}\)
Cross-price elasticity: \(E_{xy} = \dfrac{\Delta Q_x/Q_x}{\Delta P_y/P_y}\)
|Ed| > 1 elastic, < 1 inelastic. Exy > 0 substitutes, < 0 complements. In a log-log regression, the slope is the elasticity.
Utility
\(TU = \sum MU\) · \(MU = \dfrac{\Delta TU}{\Delta Q}\) · \(AU = \dfrac{TU}{Q}\)
Costs
\(TC = TFC + TVC\) · \(AC = \dfrac{TC}{Q}\) · \(AFC = \dfrac{TFC}{Q}\) · \(AVC = \dfrac{TVC}{Q}\) · \(MC = \dfrac{\Delta TC}{\Delta Q}\)
Revenue and profit
\(TR = P \times Q\) · \(AR = \dfrac{TR}{Q}\) · \(MR = \dfrac{\Delta TR}{\Delta Q}\)
\(\pi = TR - TC\); profit is maximised where \(MR = MC\).
Break-even units \(= \dfrac{TFC}{P - AVC}\)
Surplus and change
Consumer surplus (linear demand): \(CS = \tfrac12 (P_{max} - P)\,Q\)
Producer surplus (linear supply): \(PS = \tfrac12 (P - P_{min})\,Q\)
\(\%\,\text{change} = \dfrac{\text{New} - \text{Old}}{\text{Old}} \times 100\)
Python example Elasticity, break-even and the best price
# Price elasticity, break-even and profit-maximising price for a simple product p0, p1 = 100, 110 # price before / after q0, q1 = 1000, 820 # units sold before / after Ed = ((q1 - q0) / q0) / ((p1 - p0) / p0) print(f"elasticity = {Ed:.2f} ->", "elastic" if abs(Ed) > 1 else "inelastic") print(f"revenue before {p0*q0:,} vs after {p1*q1:,}") fixed, var_cost = 50_000, 60 print("break-even units at price 100:", fixed / (100 - var_cost)) # Linear demand Q = 2000 - 10P; find the price with the highest profit best = max(range(60, 200), key=lambda P: (P - var_cost) * (2000 - 10*P) - fixed) print("profit-maximising price:", best)
elasticity = -1.80 -> elastic revenue before 100,000 vs after 90,200 break-even units at price 100: 1250.0 profit-maximising price: 130
Main control strategies
Think of cruise control in a car. It measures your speed, compares it with the target, and adjusts the throttle. That loop of measure, compare, correct is feedback control. The strategies below differ in how cleverly they correct.
Everyday example: A thermostat switching the heating on and off to hold 21 °C.
Control theory makes a dynamic system (a plant \(G(s)\)) follow a reference \(r\) while rejecting disturbances \(d\). It links to data science through system identification, time-series forecasting, and reinforcement learning, which solves the same optimal-control problem without a known model.
| Strategy | Idea | Control law / goal |
|---|---|---|
| Open-loop | Act on the reference only; no measurement | \(u = K_r r\) |
| Feedback | Measure the output, correct the error | \(u = C(s)e\) |
| Feedforward | Act on measured commands or disturbances before they show up in y | \(u_{ff} = C_{ff}(s)r\) or \(C_d(s)d\) |
| PID | Proportional + integral (removes steady error) + derivative (damps) | \(u = K_p e + K_i\!\int e\,dt + K_d\,\dot e\) |
| Cascade | Fast inner loop rejects disturbances; slower outer loop tracks the goal | Bandwidth inner > outer |
| State feedback | Feed back the full state, estimated by an observer if unmeasured | \(u = -Kx + Nr\) |
| Optimal (LQR) | Minimise a cost trading state error vs control effort | \(\min J = \int_0^\infty (x^\top Qx + u^\top Ru)\,dt\); \(K\) from the Riccati equation |
| Robust (H∞) | Stay stable for any model error Δ in a known set | \(\lVert T_{zw}\rVert_\infty < \gamma\) |
| Adaptive | Update controller parameters online as the plant changes | \(\hat\theta\) from an adaptation law (gradient, MRAC) |
| Model predictive (MPC) | Optimise over a horizon with constraints, apply the first input, repeat | \(\min \sum_{k=0}^{N-1}\ell(x_k,u_k)\) s.t. \(x_{k+1}=f(x_k,u_k)\), \(u_k\in U\), \(x_k\in X\) |
Real systems usually combine several: feedforward + feedback, cascaded loops, observers, and MPC for constraints. Strongly nonlinear plants use feedback linearisation, sliding mode or backstepping.
Python example Simulate a PID thermostat
# PID controller holding a room at 21 °C (simple heat model, 1 step = 1 minute) Kp, Ki, Kd = 0.8, 0.05, 0.3 temp, target, outside = 15.0, 21.0, 10.0 integral, prev_err = 0.0, target - temp for minute in range(1, 61): err = target - temp integral += err deriv = err - prev_err heater = max(0.0, min(10.0, Kp*err + Ki*integral + Kd*deriv)) # heater power 0-10 prev_err = err temp += 0.1*heater - 0.05*(temp - outside) # heating minus heat loss if minute in (5, 15, 30, 60): print(f"minute {minute:2d}: temp {temp:5.2f} °C, heater {heater:4.1f}")
minute 5: temp 16.22 °C, heater 5.3 minute 15: temp 18.17 °C, heater 5.6 minute 30: temp 19.88 °C, heater 5.7 minute 60: temp 20.89 °C, heater 5.5
The heater settles the room close to 21 °C; the integral term slowly removes the remaining gap.
Built from cheat sheets by The World of Data, MLTut, m-softtech, Grow Up Economics, ChatWhole, Data Driven Insights, eeanimation and others. Worked examples recomputed with SciPy.