Applied AI Engineering

Reading progress
0 of 3 sections read
2 / 3

Guide 1 · Mathematics of Artificial Intelligence

Starter unit: The tools

2 min read2 of 3

0-1 Preparing and describing data

Before you start on any mathematics, the data arrives in a table. It rarely turns up clean; you will find missing cells, outliers, and columns measured in different units. The Pandas library reads and cleans the table, and the NumPy library runs fast calculations on it.

The very first thing you do with a new table is describe it. The mean tells you where the values are centred, the median sits right in the middle once you put them in order, and the standard deviation tells you how far the values spread out from the mean. When you come across an outlier, trust the median more than you trust the mean.

An outlier shifts the mean without moving the median
An outlier shifts the mean without moving the median

Try it

You have a small table of eight students across two groups, with one missing cell. We fill the missing cell with the median, describe the table, and then compare the two groups.

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "group": ["A", "A", "A", "B", "B", "B", "B", "A"],
    "hours": [2, 4, np.nan, 1, 3, 5, 2, 6],
    "score": [55, 68, 61, 50, 64, 80, 58, 83],
})

print(df["hours"].isna().sum())                              # 1
df["hours"] = df["hours"].fillna(df["hours"].median())

print(round(df["score"].mean(), 1), df["score"].median())    # 64.9 62.5
print(df.groupby("group")["score"].mean().round(1).to_dict())  # {'A': 66.8, 'B': 63.0}
print(round(df["hours"].corr(df["score"]), 2))               # 0.99

times = np.array([2, 3, 3, 4, 4, 5, 30])
print(round(times.mean(), 2), np.median(times))              # 7.29 4.0

We found one missing cell and filled it with the median. The mean score came out at 64.9, and the median at 62.5. Group A averaged 66.8, while group B averaged 63. The correlation between hours and scores reached 0.99, meaning they rise together. In the final line, we have seven response times, one of which is an outlier; the mean was 7.29, whereas the median was 4.

Where you meet it

A large share of the time spent on any machine learning project goes into this step. A model trained on data that nobody has cleaned will simply learn its mistakes.

Exercises

  1. Why did we fill the missing cell with the median rather than the mean?
  2. Remove the value 30 from the response times and recalculate. What is the new mean?
  3. The correlation came out at 0.99 from just eight students. Would you trust it?

Solutions

  1. Because the median is unaffected by outliers.
  2. It becomes 3.5, which is close to the median.
  3. Do not put too much trust in it, as the sample is small. In the statistics unit, we will see how to measure that confidence.

Tip: use ← → to move between sections.