Loading...
Machine Learning  /  Module 1

Machine Learning Foundations

Fifteen short topics with interactive graphs you can play with. Based on Andrew Ng's Machine Learning Specialization (Stanford Online and DeepLearning.AI).

0 of 15 topics understood
1

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.

Traditional programmingRules + Data
AnswersA person writes every rule
Machine LearningData + Answers
RulesThe computer finds the pattern
2

Definitions and Checkers Example

Arthur Samuel

Machine Learning is the field of study that gives computers the ability to learn without being explicitly programmed.

Tom Mitchell (formal definition)

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.

SymbolMeaningCheckers example
EExperienceGames played
TTaskPlaying checkers
PPerformancePlaying strength or results
Try it yourself

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.

E: games played 0 T: playing checkers P: recent win rate –
3

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.

4

Supervised Learning

Definition

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.

XInput
ML ModelLearns patterns
YOutput

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
EmailSpam or not spamSpam filtering
AudioText transcriptSpeech recognition
English textSpanish textMachine translation
Advertisement and user informationClick or no clickOnline advertising
Camera images and radar dataPositions of other carsSelf-driving vehicles
Phone imageDefect or no defectVisual 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.

5

Regression

Definition

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.

Try it yourself

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.

f(x) = Prediction Average error

Linear and nonlinear regression

Linear regression models the relationship with a straight line:

Simple linear model

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.
6

Classification

Definition

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)DiagnosisLabel
1Benign (noncancerous)0
2Benign (noncancerous)0
5Malignant (cancerous)1
7Malignant (cancerous)1
Try it yourself

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.

Prediction

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.

7

Binary and Multiclass Classification

Binary classification

Predicts one of two possible categories. Labels: y ∈ {0, 1}

Multiclass classification

Predicts one category from three or more. Labels: y ∈ {0, 1, 2}

Try it yourself

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

PropertyRegressionClassification
OutputNumerical valueCategory
ExampleHouse priceSpam detection
TargetContinuous quantityDiscrete class
Multiple featuresYesYes
Supervised learningYesYes

Main rule: regression predicts numerical quantities, while classification predicts categories, even when the categories are stored as numbers.

8

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.

Decision boundary

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.

Try it yourself

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.

AccuracyMisclassified
9

Unsupervised Learning

Definition

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.

Try it yourself

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 learningUnsupervised learning
Labelled dataUnlabelled data
Correct answers availableNo target answers supplied
Predicts outputsDiscovers patterns
Regression and classificationClustering, 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.

Check yourself

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.

Score: 0 / 4
10

Clustering and Applications

Definition

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
Try it yourself

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.

Rounds: 0Average squared distance: –

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.

Giant panda gives birth to twin cubs
Twin panda cubs born in Tokyo
Japan's zoo welcomes rare panda twins
Rare twin pandas attract attention

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.

Try it yourself

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.

Low High expression

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.

11

Anomaly Detection

Definition

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.

Try it yourself

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.

z-scoreStatus

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
12

Dimensionality Reduction and PCA

Definition

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.

Original: 100 dimensions
Reduced: 10 dimensions

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.

Try it yourself

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.

Variance kept: –Information lost: –
13

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.

Markdown source
# Machine Learning
This notebook introduces Python.
How it looks when run

Machine Learning

This notebook introduces Python.

Code cell: runs Python. Click the cell, then press Shift + Enter or the Run button.

In [ ]:
print("Hello, Machine Learning!")

This page shows the prepared output of each example. It does not run Python itself.

Running code

ActionShortcut
Run and advanceShift + Enter
Run and remainCtrl + Enter
Enter edit modeEnter
Enter command modeEsc
Insert cell aboveA in command mode
Insert cell belowB in command mode

You can also run cells with the notebook toolbar.

14

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.

Try it yourself

Type a name and watch the output

Code
name = "Andrew"
print(f"Hello, {name}!")
Hello, Andrew!

Expressions work inside braces too

Code
a = 7
b = 5
print(f"{a} + {b} = {a + b}")
7 + 5 = 12
15

1-Hour Jupyter Practical

Practical Lab 1: Python and Jupyter Notebook exploration. Duration: 60 minutes, split into four sessions.

Practice timer

Follow the hour

Session 1Menu discovery · 10 min
Session 2Python · 15 min
Session 3NumPy · 15 min
Session 4Experiment · 20 min
60:00
Press Start when you open your notebook.

Session 1: menu discovery (10 minutes)

Explore the main menus of classic Jupyter Notebook.

MenuExplore
FileNew, Open, Save, Download
EditCut, Copy, Paste, Delete
ViewToolbar, display options
InsertCells above and below
CellCell types and execution
KernelRestart, Interrupt, Status
WidgetsInteractive controls
HelpDocumentation, 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

In [ ]:
name = "Machine Learning Student"
course = "Machine Learning"
hours = 1

print(f"Name: {name}")
print(f"Course: {course}")
print(f"Practice duration: {hours} hour")

Exercise 2: lists and functions

In [ ]:
prices = [100, 200, 300, 400]

def calculate_average(values):
    return sum(values) / len(values)

average = calculate_average(prices)
print(f"Average price: {average}")

Session 3: NumPy fundamentals (15 minutes)

Practise creating arrays, indexing, mathematical operations, mean, minimum and maximum.

Exercise 3: NumPy arrays

In [ ]:
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)

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

In [ ]:
number = 10

try:
    result = number / 0
except ZeroDivisionError as error:
    print(f"Error detected: {error}")

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

What Students Say

Here are our students...

Phone

Contact Us

Empower your tech dreams with us. Get in touch!

  • Partner brand
  • Partner brand
  • Partner brand
  • Partner brand
  • Partner brand