Introduction to Machine Learning
Machine Learning is everywhere around us, even when we don't notice it. Every time a website suggests a video, filters a spam email or recognises a face, a machine learning system is working in the background.
Google Search
Helps rank webpages by relevance and other signals.
Face Recognition
Recognises or verifies faces in photographs.
Movie Recommendations
Netflix and others suggest movies from viewing patterns.
YouTube
Recommends videos based on your interests and behaviour.
Spam Detection
Identifies unwanted emails automatically.
Online Shopping
Recommends products customers might like.
Voice Assistants
Recognise speech and process spoken commands.
Online Advertising
Predicts which advertisements a user may like.
Self-driving Cars
Help identify vehicles, pedestrians and road conditions.
Healthcare
Assists with medical image analysis and disease risk prediction.
The key idea
Machine Learning lets computers learn patterns from data instead of requiring programmers to write every rule for every situation.
Definitions and Checkers Example
Machine Learning is the field of study that gives computers the ability to learn without being explicitly programmed.
A computer program is said to learn from experience E with respect to a task T and performance measure P, if its performance at T, as measured by P, improves with experience E.
Arthur Samuel's checkers program
Samuel wrote a program that learned to play checkers. It played many games, learned from experience, and its playing ability improved over time. It made better decisions without every move being programmed by hand.
| Symbol | Meaning | Checkers example |
|---|---|---|
| E | Experience | Games played |
| T | Task | Playing checkers |
| P | Performance | Playing strength or results |
Watch a program improve with experience
Each press plays 25 more games. As experience (E) grows, the win rate (P) climbs. This is a simulation for teaching, not Samuel's real program.
Machine Learning Algorithm Categories
Machine learning algorithms fall into a few main families. This module covers supervised and unsupervised learning in detail and introduces the others.
Supervised Learning
Learn from labelled data.
Unsupervised Learning
Discover patterns without labels.
Recommender Systems
Predict user preferences.
Reinforcement Learning
Learn from rewards and interactions.
Recommender systems can use supervised, unsupervised and other methods, so they are not strictly a separate fundamental learning category. They are listed on their own because they are such a common application.
These techniques have advanced rapidly and are widely used in real-world applications. Practical advice on applying them matters just as much as the algorithms themselves, and we return to it throughout the course.
Supervised Learning
Supervised Learning is a type of Machine Learning in which an algorithm learns from training examples that contain inputs and their corresponding correct output labels.
During training the model sees examples of both X and the correct Y. It learns the relationship between them, then uses it to make predictions on new inputs.
Where supervised learning is used
| Input (X) | Output (Y) | Application |
|---|---|---|
| Spam or not spam | Spam filtering | |
| Audio | Text transcript | Speech recognition |
| English text | Spanish text | Machine translation |
| Advertisement and user information | Click or no click | Online advertising |
| Camera images and radar data | Positions of other cars | Self-driving vehicles |
| Phone image | Defect or no defect | Visual inspection |
Two main types
Regression
Predicts a number. Examples: house price, temperature, salary, sales revenue.
Classification
Predicts a category. Examples: spam or not spam, benign or malignant, cat or dog, defective or normal.
Regression
Regression is a supervised learning technique used to predict numerical values, typically continuous quantities.
Andrew Ng explains regression with house price prediction. Each point below is one house: X is its size in square feet and Y is its selling price. The model learns the relationship between size and price.
Fit a line to house prices
Drag the sliders to fit the line by hand, then choose Best straight line to see the least-squares line, or Best curve for a curved fit. Click on the graph to add your own house and watch the fit change. Illustrative data.
Linear and nonlinear regression
Linear regression models the relationship with a straight line:
f(x) = w·x + b
- x: the input feature (house size)
- w: the weight, or slope
- b: the bias, or intercept
- f(x): the predicted output (price)
Nonlinear regression uses a curve when a straight line cannot represent the data well. A curve may fit some datasets better, but a more complex model is not automatically more accurate on new data.
Characteristics of regression
- Predicts numerical values that can take many possible values.
- Learns the relationship between features and a numerical target.
- Can use one input feature or several.
- Used for forecasting, estimation and numerical prediction.
Classification
Classification is a supervised learning technique used to predict categories or classes.
Unlike regression, classification predicts which category an input belongs to. Examples include spam detection, recognising a handwritten digit, or predicting whether a tumour is benign or malignant.
Breast cancer example
Andrew Ng uses tumour detection as his classification example. Here is a small dataset of tumour sizes and diagnoses:
| Tumour size (cm) | Diagnosis | Label |
|---|---|---|
| 1 | Benign (noncancerous) | 0 |
| 2 | Benign (noncancerous) | 0 |
| 5 | Malignant (cancerous) | 1 |
| 7 | Malignant (cancerous) | 1 |
Move the threshold and predict a new tumour
The four dots are the training data. The model predicts "malignant" for every size to the right of the dashed threshold. Move the new tumour and the threshold and watch the prediction change.
This is illustrative educational data, not a clinical diagnostic model. In real medical diagnosis, tumour size alone is not enough: clinical assessment and additional tests are necessary.
Binary and Multiclass Classification
Predicts one of two possible categories. Labels: y ∈ {0, 1}
Predicts one category from three or more. Labels: y ∈ {0, 1, 2}
See how categories become numbers
Choose a type, then an example. The computer stores each category as a number called a label. Which category gets which number is just a convention.
Andrew Ng extends the tumour example to three classes: Class 0 is benign, Class 1 is malignant type 1 and Class 2 is malignant type 2. Another multiclass example is sorting images into cat, dog or horse.
Regression vs classification
| Property | Regression | Classification |
|---|---|---|
| Output | Numerical value | Category |
| Example | House price | Spam detection |
| Target | Continuous quantity | Discrete class |
| Multiple features | Yes | Yes |
| Supervised learning | Yes | Yes |
Main rule: regression predicts numerical quantities, while classification predicts categories, even when the categories are stored as numbers.
Multiple Features and Decision Boundaries
A classification model can use more than one input feature. In Andrew Ng's example the two features are X₁: tumour size and X₂: patient age, and the output Y is benign or malignant.
A boundary that separates the regions a classification model assigns to different classes. It can be a straight line, a curve, or a more complex surface in higher dimensions.
Draw a decision boundary
Blue dots are benign, red dots are malignant (illustrative data). Move the boundary so the shaded regions match the dot colours. Points with a dark ring are misclassified. Press Auto-fit line to let logistic regression find a line.
Unsupervised Learning
Unsupervised Learning is a type of Machine Learning where an algorithm discovers patterns or structure in data without being given target output labels.
Supervised learning trains on pairs (X, Y). Unsupervised learning has only X, so the algorithm must find useful structure in the inputs by itself.
With labels, without labels, and discovered groups
The same data is shown three ways. Without labels you see only grey points. An unsupervised algorithm (K-Means with K = 2) can still discover two groups on its own.
Supervised vs unsupervised
| Supervised learning | Unsupervised learning |
|---|---|
| Labelled data | Unlabelled data |
| Correct answers available | No target answers supplied |
| Predicts outputs | Discovers patterns |
| Regression and classification | Clustering, dimensionality reduction and some anomaly detection methods |
Three important unsupervised problems
Clustering
Group similar data points together. Example: customers with similar interests.
Anomaly detection
Find unusual data points. Example: suspicious banking transactions.
Dimensionality reduction
Use fewer dimensions while keeping useful information. Example: 100 features down to 10.
Supervised or unsupervised?
Look at whether the task predicts predefined target labels or discovers structure without them.
Learn a spam filter from labelled emails.
Group news articles about the same story.
Discover customer market segments.
Classify patients using labelled diabetes diagnoses.
Clustering and Applications
Clustering is an unsupervised learning technique that groups similar data points together based on their features. A cluster is a group of points that are similar according to the chosen features and similarity measure.
K-Means
K-Means splits data into K groups. It places K cluster centres, assigns every point to its nearest centre, moves each centre to the middle of its group, and repeats until nothing changes.
- K: the number of clusters
- Centroid: the centre of a cluster
- Data point: one observation
- Distance: how far apart two observations are
Run K-Means step by step
Press Step to alternate between "assign points" and "move centroids", or press Run to watch it finish. Try different values of K.
Application 1: grouping news stories
Andrew Ng shows how news articles about the same event can be grouped. The wording differs, but all four headlines describe one event, so a clustering system can place them together.
Application 2: DNA microarray
A DNA microarray measures gene expression. Each row is a gene, each column is a person or sample, and the colour shows the expression level. Clustering finds samples with similar profiles, which helps researchers study disease subtypes and biological patterns.
Group similar samples
The samples start in a mixed order. Press Group similar samples to cluster the columns and the two profiles become visible. Illustrative data.
Application 3: customer segmentation
Customer segmentation uses clustering to discover groups of customers with similar needs. Andrew Ng's example finds three kinds of interest:
Growing skills
People who want to grow their skills and knowledge.
Developing careers
People who want to develop their careers.
Staying updated with AI
People who want to keep up with Artificial Intelligence.
A training institute could use course interests and enrolment behaviour in the same way, to see which students prefer programming, career development or AI courses.
Anomaly Detection
Anomaly Detection finds observations that differ significantly from the typical pattern.
Suppose a customer usually spends between ₹500 and ₹2,000 per transaction. One day a transaction of ₹2,00,000 appears. An anomaly detection system can flag it for review because it is far from the customer's usual spending.
Is this transaction unusual?
The grey dots are 40 past transactions. Slide the new transaction along the scale. It is flagged when it lies more than 3 standard deviations from the usual average (z-score above 3). The scale is logarithmic so you can reach very large amounts.
An unusual observation is not automatically fraudulent or wrong. Anomaly detection only flags it for a closer look.
Where it is used
- Banking fraud investigation
- Cybersecurity
- Manufacturing quality monitoring
- Healthcare monitoring
- Unusual website traffic detection
Dimensionality Reduction and PCA
Dimensionality Reduction reduces the number of variables needed to represent a dataset while trying to keep the important information.
Suppose a dataset has 100 features. A dimensionality reduction method might describe it with just 10 new features.
Benefits
- Lower computational cost and faster model training
- Easier visualisation
- Less redundancy
- Potentially less noise
PCA: Principal Component Analysis
PCA is a popular dimensionality reduction technique. It builds new variables called principal components that capture the directions in which the data varies the most. Below, two features are squashed onto one line. The best line keeps as much of the spread as possible.
Find the best direction
Rotate the line. Each point drops straight down onto it. The more spread out the dots on the line, the more information is kept. Press Find best direction to jump to the first principal component.
Jupyter Notebook Introduction
Jupyter Notebook is an interactive environment for writing, running and documenting Python code. It is widely used for machine learning, data science, data visualisation, numerical analysis and scientific experiments.
Optional labs
Andrew Ng's optional labs help you reinforce the lectures, understand working code, gain hands-on experience and prepare for graded programming exercises. You can often complete them just by running and reading the existing code cells.
Two kinds of cells
Markdown cell: headings, explanations and notes.
# Machine Learning This notebook introduces Python.
Machine Learning
This notebook introduces Python.
Code cell: runs Python. Click the cell, then press Shift + Enter or the Run button.
print("Hello, Machine Learning!")
Hello, Machine Learning!
This page shows the prepared output of each example. It does not run Python itself.
Running code
| Action | Shortcut |
|---|---|
| Run and advance | Shift + Enter |
| Run and remain | Ctrl + Enter |
| Enter edit mode | Enter |
| Enter command mode | Esc |
| Insert cell above | A in command mode |
| Insert cell below | B in command mode |
You can also run cells with the notebook toolbar.
Python and f-strings
An f-string lets you put variables and expressions inside a piece of text. Write an f before the opening quote and wrap the value in curly braces.
Type a name and watch the output
name = "Andrew"
print(f"Hello, {name}!")
Hello, Andrew!
Expressions work inside braces too
a = 7 b = 5 print(f"{a} + {b} = {a + b}")
7 + 5 = 12
1-Hour Jupyter Practical
Practical Lab 1: Python and Jupyter Notebook exploration. Duration: 60 minutes, split into four sessions.
Follow the hour
Session 1: menu discovery (10 minutes)
Explore the main menus of classic Jupyter Notebook.
| Menu | Explore |
|---|---|
| File | New, Open, Save, Download |
| Edit | Cut, Copy, Paste, Delete |
| View | Toolbar, display options |
| Insert | Cells above and below |
| Cell | Cell types and execution |
| Kernel | Restart, Interrupt, Status |
| Widgets | Interactive controls |
| Help | Documentation, shortcuts, tours |
Menu names and locations differ between classic Jupyter Notebook, JupyterLab and Google Colab.
Session 2: Python fundamentals (15 minutes)
Practise variables, data types, arithmetic, lists, functions and f-strings. Click a cell and press Run (or Shift + Enter) to see its output.
Exercise 1: variables and f-strings
name = "Machine Learning Student"
course = "Machine Learning"
hours = 1
print(f"Name: {name}")
print(f"Course: {course}")
print(f"Practice duration: {hours} hour")
Name: Machine Learning Student Course: Machine Learning Practice duration: 1 hour
Exercise 2: lists and functions
prices = [100, 200, 300, 400]
def calculate_average(values):
return sum(values) / len(values)
average = calculate_average(prices)
print(f"Average price: {average}")
Average price: 250.0
Session 3: NumPy fundamentals (15 minutes)
Practise creating arrays, indexing, mathematical operations, mean, minimum and maximum.
Exercise 3: NumPy arrays
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print("Array:", numbers)
print("Mean:", np.mean(numbers))
print("Maximum:", np.max(numbers))
print("Minimum:", np.min(numbers))
print("Doubled:", numbers * 2)
Array: [10 20 30 40 50] Mean: 30.0 Maximum: 50 Minimum: 10 Doubled: [ 20 40 60 80 100]
Session 4: experimentation (20 minutes)
Run cells, change values, watch the outputs, create and correct errors, restart the kernel and run the whole notebook again.
Exercise 4: understanding errors
number = 10
try:
result = number / 0
except ZeroDivisionError as error:
print(f"Error detected: {error}")
Error detected: division by zero
This shows how Python reports an error and how an exception can be handled instead of stopping your program.
Module 1 complete?
Tick each topic as you finish it. More modules will be added to the course soon.
Back to all modules




