Level 3 · BeginnerLesson 3.1 32 min read 10 question quiz 11 marks of written practice

Everything Is Numbers: Turning the World into Data

Examples, features and labels

A model never sees a cat, a song or a sentence. It sees numbers. The first job in any AI project is turning the world into a dataset: a table of numbers a model can learn from.

A dataset of housesA table of five houses. The columns are floor area in square metres, bedrooms, garden, kilometres to the station, and price in thousands of pounds. The first four column headers are violet: they are the features, the inputs. The price column is pink: it is the label, what we predict. One row, house 2 with 112 square metres, 3 bedrooms, a garden, 3.5 km to the station and a price of 340 thousand pounds, is outlined as an example. The bedrooms column is outlined as a feature: one property of every house.A dataset: rows are examples, columns are features, one column is the labelfloor area m²bedroomsgardenkm to stationprice £k682no1.2215house 11123yes3.5340house 2953yes0.8330house 31504yes6.1425house 4541no0.4190house 5a featurethe labelwhat we predictone property, every housean exampleone house
The model's job: learn to predict the pink column from the violet ones.
  • Each row is one example (also called a sample, instance or data point).
  • Each column is a feature: one measurable property of the examples.
  • In supervised learning one extra column holds the label, the answer the model must learn to predict.

Kinds of feature

KindMeaningExamples
Numerical, continuousAny value in a rangeHeight 1.62 m, temperature 18.4 °C
Numerical, discreteCountsNumber of bedrooms, goals scored
Categorical, nominalCategories with no orderColour, country, favourite sport
Categorical, ordinalCategories with an orderSmall, medium, large; grade 1 to 9
UnstructuredNot a neat column at allImages, audio, text, video

Models only do arithmetic, so every kind must end up as numbers. Choosing and building good features is called feature engineering, and before deep learning it was most of the work.

Images are grids of numbers

A greyscale image is a grid of pixels, each a brightness from 0 (black) to 255 (white): one byte each. The famous MNIST dataset of handwritten digits uses images 28 pixels square, so each digit is 784 numbers.

A colour image stores three numbers per pixel, one each for red, green and blue. Stack the three grids and you have a block of numbers: height × width × 3 channels.

An image as red, green and blue channelsOn the left, a tiny picture of 6 by 6 pixels: blue sky, a yellow sun in the top right, a red flower and green grass along the bottom. An arrow labelled split leads to three stacked grids, the red, green and blue channels, each 6 by 6, drawn one behind the other. The front red grid shows its numbers: sky pixels are 120, the sun 250, the flower 225 and the grass 34 or 20. Together the block has shape 6 by 6 by 3, which is 108 numbers.A colour image is three grids of numbers stacked into a blockwhat you see6 × 6 pixelssplitbluegreen120120120120250250120120120120250250120120120120120120120225120120120120342034343434343434343434redwidth 6height 63 channelsshape (6, 6, 3)6 × 6 × 3 = 108 numbers
Every pixel is three numbers from 0 to 255. Each channel is a greyscale image of how much of that colour is present.
ImageShapeNumbers
MNIST digit28 × 28 × 1784
Thumbnail used to train many vision models224 × 224 × 3150,528
Full HD video frame1080 × 1920 × 36,220,800
One second of Full HD video at 30 frames a second30 × 1080 × 1920 × 3186,624,000

That last row is why video models need so much computing power, and why images are usually shrunk before training.

Sound, text and categories as numbers

Sound

A microphone measures air pressure thousands of times a second. CD quality audio takes 44,100 samples a second, each a number. Speech models often turn the sound into a spectrogram first: a picture of which frequencies are loud at each moment, which can then be treated like an image.

Text

Every character already has a number (its Unicode code point: "A" is 65). Models usually work with bigger pieces called tokens, each given an ID from a fixed vocabulary. Level 9 shows how modern models split text into tokens and turn each one into a list of meaningful numbers.

Categories: one-hot encoding

You cannot just number categories, because the numbers imply an order and a size that are not there. If red = 1, green = 2 and blue = 3, a model may conclude blue is "three times" red, or that green is the average of red and blue.

One-hot encoding gives each category its own column, with a 1 in the column that applies and 0 everywhere else:

Colouris_redis_greenis_blue
red100
green010
blue001

For ordinal categories, where the order is real (small, medium, large), plain numbers 0, 1, 2 are fine.

One-hot gets big

A vocabulary of 50,000 words one-hot encoded makes every word a list of 50,000 numbers with a single 1. Worse, every word is equally different from every other: "cat" is as far from "kitten" as from "volcano". Embeddings, in Level 9, fix both problems.

Scalars, vectors, matrices and tensors

AI engineers describe data by its shape.

Scalars, vectors, matrices and tensorsFour drawings made of cubes, each holding a number. A scalar is a single cube holding 7, shape empty brackets, one number. A vector is a row of 4 cubes, 3 1 4 1, shape (4,), a list. A matrix is a 3 by 4 grid of cubes, shape (3, 4), a table. A tensor is a solid block 3 cubes deep, 3 high and 4 wide, shape (3, 3, 4), a block such as an image. Rank is the number of dimensions: 0, 1, 2 and 3, and a batch of colour images is rank 4.Scalar, vector, matrix, tensor: the same idea with more dimensions7scalarshape ()one number3141vectorshape (4,)a list459028182718matrixshape (3, 4)a table887403391618tensorshape (3, 3, 4)a block, such as an imageRank = number of dimensions: 0, 1, 2 and 3. A batch of colour images is rank 4.
AI libraries call all of these tensors and keep track of each one's shape.
NameDimensionsExampleShape
Scalar0One temperature: 18.4()
Vector1One house: size, bedrooms, age(3,)
Matrix2A greyscale image, or a table of 100 houses(28, 28) or (100, 3)
Tensor3 or moreA colour image; a batch of 32 colour images(224, 224, 3) or (32, 224, 224, 3)

"Tensor" is the general word for all of them, which is where the name of the TensorFlow library comes from. Models process data in batches, many examples at once, so there is nearly always an extra batch dimension at the front.

The dot product: the most important sum in AI

Multiply two vectors position by position and add up the results:

Dot product

[1, 2, 3] · [4, 5, 6] = 1×4 + 2×5 + 3×6 = 32

A dot product measures how much two vectors point the same way. Large and positive: similar direction. Zero: unrelated. Negative: opposite. Every artificial neuron computes a dot product, and so does every attention score in a transformer. Graphics processors are built to do billions of them a second.

Scaling features

Features are often on wildly different scales. House size might run from 50 to 300 square metres while bedrooms run from 1 to 6. Any method that measures distance will then be dominated by the feature with the biggest numbers, and gradient descent (Level 5) trains slowly and unevenly.

Why features are scaledTwo scatter plots of nine houses by floor area and bedrooms. On the left the raw values are drawn to the same scale, so the floor area axis runs across 250 units while the 5 unit range of bedrooms is squashed into a strip 6 pixels tall. House B, with 3 more bedrooms than house A, looks nearest to A at a distance of 3.6, while house C is 30 away. On the right both features are scaled to 0 to 1 and the points spread out. Dashed lines show A to B is now 0.60 and A to C is 0.12, so C is nearest.Before scaling, bedrooms hardly count. After scaling, they do.Raw values, drawn to the same scale50100150200250300floor area (m²): range 250ABCbedrooms (range 5) is squashedinto a strip 6 pixels tallnearest to A: B (3.6 away), though B has3 more bedrooms; C is 30 awayBoth scaled to 0 to 1floor area, scaledbedrooms, scaledABCA to B: 0.60A to C: 0.12now C is nearest
Any method that measures distance needs its features on comparable scales.

Two standard fixes

MethodFormulaResult
Min-max normalisation(x − min) ÷ (max − min)Every value between 0 and 1
Standardisation (z-score)(x − mean) ÷ standard deviationMean 0, standard deviation 1; values usually between −3 and 3

Standardisation copes better with outliers, because one huge value would squash every other min-max value towards 0.

Fit on training data only

Work out the min, max, mean and standard deviation from the training data, then apply those same numbers to the validation and test data and to every future input. Computing them from all the data lets information from the test set leak into training.

Hands-on: turning things into numbers

An image is a list of lists

Python
# A 7 by 7 greyscale image: 0 is black, 255 is white
image = [
    [  0,   0, 255, 255, 255,   0,   0],
    [  0, 255,   0,   0,   0, 255,   0],
    [255,   0, 255,   0, 255,   0, 255],
    [255,   0,   0,   0,   0,   0, 255],
    [255,   0, 255, 255, 255,   0, 255],
    [  0, 255,   0,   0,   0, 255,   0],
    [  0,   0, 255, 255, 255,   0,   0],
]

def show(img):
    for row in img:
        print("".join("##" if p > 127 else ". " for p in row))

show(image)
flat = [p for row in image for p in row]      # what a simple network sees
print("Shape 7 x 7 becomes a vector of", len(flat), "numbers:", flat[:10], "...")
print("Scaled to 0..1:", [p / 255 for p in flat[:10]], "...")
inverted = [[255 - p for p in row] for row in image]
show(inverted)

One-hot encoding, scaling and distance

Python
import math

def one_hot(value, categories):
    return [1 if c == value else 0 for c in categories]

colours = ["red", "green", "blue"]
for c in colours:
    print(f"{c:6} -> {one_hot(c, colours)}")

# Three houses: (size in square metres, bedrooms)
A, B, C = (100, 2), (102, 5), (130, 2)
print("Unscaled: A to B", round(math.dist(A, B), 2), " A to C", round(math.dist(A, C), 2))

# Min-max scale each feature using ranges from the training data
size_lo, size_hi, bed_lo, bed_hi = 50, 300, 1, 6
def scale(h):
    return ((h[0] - size_lo) / (size_hi - size_lo), (h[1] - bed_lo) / (bed_hi - bed_lo))

sA, sB, sC = scale(A), scale(B), scale(C)
print("Scaled:   A to B", round(math.dist(sA, sB), 2), " A to C", round(math.dist(sA, sC), 2))

def dot(u, v):
    return sum(a * b for a, b in zip(u, v))
print("Dot product [1, 2, 3] . [4, 5, 6] =", dot([1, 2, 3], [4, 5, 6]))

Unscaled, house B looks almost identical to A, because a 2 square metre difference is tiny next to the 30 square metre gap to C, and the 3 extra bedrooms barely register. Once scaled, the extra bedrooms count properly and C becomes the nearest. A nearest neighbour model would give different answers before and after scaling.

Activity: design the features

A school wants to predict whether a student will be late tomorrow. In a group, list ten features you could collect, say what kind each one is, how you would turn it into numbers, and which ones it would be unfair or intrusive to use. Then do the same for predicting whether someone will skip a song.

Level check

  • Describe a dataset in terms of examples, features and labels
  • Explain how a colour image is stored as numbers, and work out its size from its shape
  • Explain why categories need one-hot encoding, and when plain numbers are fine
  • Name and give the shape of a scalar, vector, matrix and tensor
  • Calculate a dot product and say what it measures
  • Explain why features are scaled and the difference between min-max and standardisation

Key terms you must be able to define

Dataset
A collection of examples, usually a table with one row per example and one column per feature.
Example
One row of a dataset: one house, one image, one email. Also called a sample or data point.
Feature
One measurable property of the examples, used as an input to the model.
Feature engineering
Choosing, building and transforming features so a model can learn from them.
Pixel
One point in an image, stored as a brightness or as red, green and blue values from 0 to 255.
Channel
One layer of an image's values, such as its red, green or blue values.
One-hot encoding
Turning a category into a vector with a 1 in its own position and 0 everywhere else.
Tensor
A block of numbers with any number of dimensions; scalars, vectors and matrices are tensors of rank 0, 1 and 2.
Dot product
The sum of the products of two vectors' matching entries, measuring how much they point the same way.
Normalisation
Rescaling a feature into a fixed range, usually 0 to 1, with (x − min) ÷ (max − min).
Standardisation
Rescaling a feature to mean 0 and standard deviation 1 with (x − mean) ÷ standard deviation.

Flashcards

DefineDataset
AnswerA collection of examples, usually a table with one row per example and one column per feature.
DefineExample
AnswerOne row of a dataset: one house, one image, one email. Also called a sample or data point.
DefineFeature
AnswerOne measurable property of the examples, used as an input to the model.
DefineFeature engineering
AnswerChoosing, building and transforming features so a model can learn from them.
DefinePixel
AnswerOne point in an image, stored as a brightness or as red, green and blue values from 0 to 255.
DefineChannel
AnswerOne layer of an image's values, such as its red, green or blue values.
DefineOne-hot encoding
AnswerTurning a category into a vector with a 1 in its own position and 0 everywhere else.
DefineTensor
AnswerA block of numbers with any number of dimensions; scalars, vectors and matrices are tensors of rank 0, 1 and 2.

Go further: notes for future AI engineers

The curse of dimensionality

Every feature adds a dimension. With 784 pixel features, each MNIST digit is a point in 784-dimensional space, and high-dimensional spaces behave strangely. The volume grows so fast that data becomes sparse: to keep the same density of examples, doubling the number of features can require squaring the amount of data. Distances also become less meaningful, because most points end up roughly the same distance apart.

This is why engineers reduce dimensions (Level 4 mentions principal component analysis), choose features carefully, and why deep learning's ability to learn compact features from raw data was such a breakthrough. A network's hidden layers are, in effect, automatic feature engineering.

Misconceptions to avoid

Avoid these
  • Numbering categories 1, 2, 3 when they have no order, which tells the model an order and sizes that do not exist.
  • Forgetting the channels when working out the size of a colour image: height times width times 3.
  • Scaling with statistics from the whole dataset instead of the training data alone, which leaks the test set into training.
  • Thinking a model sees an image the way we do. It receives a long list of numbers with no idea that neighbouring pixels belong together, unless the architecture builds that in.
  • Assuming more features is always better. Irrelevant or duplicated features add noise and make overfitting more likely.
Fun fact

A single photo from a 12 megapixel phone camera is about 36 million numbers: 12 million pixels, each with a red, a green and a blue value. To a neural network, your holiday snap is a very long list of numbers between 0 and 255.

Knowledge check

0 of 10 answered
1In a dataset table, what does each row usually represent?
2How many numbers does a 224 × 224 colour image contain?
3Why is one-hot encoding used for a feature such as 'favourite sport'?
4Which of these is a matrix?
5What is [2, 0, 1] · [3, 5, 4]?
6A dot product of two vectors is large and positive. What does that suggest?
7What does min-max normalisation do?
8Why should scaling statistics be calculated from the training data only?
9Which feature is ordinal?
10CD quality audio has 44,100 samples per second. Roughly how many numbers is a 3 minute mono recording?
Score 0 / 10

Check you could explain this

11 marks
1Explain how a colour photograph is represented so that a machine learning model can use it.4 marks
Explain

Mark scheme0 / 4
  • LThe image is a grid of pixels
  • LEach pixel has red, green and blue values / three channels
  • LEach value is a number, usually 0 to 255
  • LStored as a tensor of height × width × 3, often scaled to 0 to 1
Model answer

The photograph is divided into a grid of pixels. Each pixel is stored as three numbers, one for each of the red, green and blue channels, usually from 0 to 255. Together the values form a tensor with the shape height × width × 3, which is normally scaled to the range 0 to 1 before being given to the model.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2A model predicts house prices using floor area in square metres and number of bedrooms. Explain why the features should be scaled, and describe one way to scale them.4 marks
Explain

Mark scheme0 / 4
  • LThe features are on very different scales / ranges
  • LThe larger feature dominates distances or slows training
  • LMin-max: (x − min) ÷ (max − min), or standardise: (x − mean) ÷ standard deviation
  • LUsing statistics from the training data only
Model answer

Floor area runs to hundreds while bedrooms run from 1 to about 6, so without scaling the floor area would dominate any distance calculation and gradient descent would train slowly and unevenly. Min-max normalisation fixes this by replacing each value with (x − min) ÷ (max − min), putting both features between 0 and 1. The min and max must be taken from the training data only and then applied unchanged to test data and new inputs.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Calculate the dot product of [3, −1, 2] and [1, 4, 2], showing your working, and state what the sign of the answer tells you.3 marks
Calculate

Mark scheme0 / 3
  • L3×1 + (−1)×4 + 2×2
  • L= 3
  • LPositive, so the vectors point in a broadly similar direction
Model answer

3 × 1 + (−1) × 4 + 2 × 2 = 3 − 4 + 4 = 3. The answer is positive, so the two vectors point in a broadly similar direction, though not strongly.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 11