Aller au contenu

Lab Session 1 - Tools and project definition⚓

Note

Before you begin, make sure you have downloaded the latest update of the course slides from here, and keep them close while doing the lab.

Note

You may use any AI assistant to help you here (and at any moment in the project). Comprehension is what is graded though, so use them as helpers, never automatically and blindly!

Objectives of the lab⚓

This is the first lab session of the Introduction to AI course. It has two very different halves:

Part A 1h15 (1st session) Set up the tools you will use for the whole semester, and get comfortable with arrays and data manipulation.
Part B 2h30 (afternoon's sessions) Form your binôme and define your own project, which will be your application for the whole course, and in particular the final evaluation.

Part A should be short, but is essential for the course. We assume that you already know how to code in Python (or vibe-code at least), so you will set up your code environment for the course. In addition, as a practicing exercise, you will familiarize yourself with vector and array manipulation using Numpy, because dataset are set of points in a space.

Part B should take as long as it needs. The project is the backbone of this course: you define it today, validate it with teachers (at least a title) before Session 2 (even better, during Session 1), you defend it in Session 2 (graded), and every lab from Session 3 onward applies its techniques to your data.

Prerequisites⚓

The following skills are strongly recommended before starting the work for the lab session. Make sure of the following:

  • You are using an IDE. We strongly recommend VSCode.
  • You have a working and recent python installation (3.10 or higher) and you know how to install new packages.
  • We recommend creating an environment specifically for this course using virtualenv or uv (uv is simpler and the new standard, but probably unknown for most of you).
  • It appears that setting up a virtual environment is often tricky for students, so don't hesitate to ask your teachers if you have any questions: this is a topic they know well!
  • For this session we will need the following python packages: numpy scipy matplotlib pandas. Install them in the newly created virtual environment.

Tip

If you need a step by step guide on python, IDE, and environments, have a look at (French) this course given at IMT Atlantique (in the 1st year) or (English) the official Python documentation about environments. Or just ask ChatGPT your teacher!

In this course, we provide code snippets as examples, and you need to build your own code to fulfill the objectives. We can provide advice on how to do so, but coding is not an objective by itself.

Table of contents of the lab⚓

Part A — Tools (1h15)

  1. Your environment for the whole semester
  2. Introduction to Numpy
  3. Exercise: synthetic data and the pairwise distance matrix
  4. Bridge: looking at a real dataset

Part B — Your project (2h30)

  1. A possible way to organise your 2h30
  2. Form your binôme
  3. Find candidate datasets
  4. If the task is not straightforward: turning a dataset into a task
  5. Teacher checkpoint
  6. Sanity-check your own data
  7. Project definition on Discord

Part A — Tools (1h15)⚓

A1. Your environment for the whole semester⚓

Target: ~25 minutes. If you are already comfortable with virtual environments, this will take you five minutes. Still, do it anyway, because you will reuse this environment in every remaining session.

Why a virtual environment?⚓

A virtual environment is a private, self-contained copy of Python and its packages, attached to one project. Without one, every pip install goes into your system Python; thus, two courses that need two different versions of the same package will fight, and "it worked last week" becomes a real problem. Using a virtual environment, the whole course lives in a single folder you can delete and rebuild in two minutes.

You will use virtual environments until the end of the course, and add packages as sessions go (scikit-learn in Session 3, torch in Session 4, and so on).

Create it⚓

Using python, if already installed⚓

Pick a folder for the whole course (e.g. intro2ai/), then:

1
2
3
4
5
6
7
# Linux / macOS
python3 -m venv .venv
source .venv/bin/activate

# Windows (PowerShell)
python -m venv .venv
.\.venv\Scripts\Activate.ps1

Your shell prompt should now be prefixed with (.venv). Then install what we need today:

1
2
pip install --upgrade pip
pip install numpy scipy matplotlib pandas

Tip

In VSCode, open your course folder, then Ctrl+Shift+P → Python: Select Interpreter → choose the one inside .venv. Do this once; afterwards every script and notebook you open in that folder uses the right environment automatically.

Alternative using uv, if python is not installed yet⚓

Alternatively, you may use uv for the management of virtual environments, notably if you don't have python installed. uv handles virtual environment, but also python versioning, and may be use to install packages directly. It is becoming more and more of a standard.

Important

By default, if you have experience with python, and if you don't plan on pursuing work with code development, we recommend that you use the previous approach (i.e. python -m venv) because it's the most native one. If you plan on pursuing in python development, or are curious about new ways of managing environments, we recommend using uv.

Defining an environment writes as:

1
2
3
4
5
6
7
8
9
# Create the environment
uv venv .venv --python 3.X

# Activate the environment
## Linux / macOS
source .venv/bin/activate

## Windows (PowerShell)
.\.venv\Scripts\Activate.ps1

Using uv, pip is not directly accessible. Instead, to install packages, you should use:

1
uv pip install numpy scipy matplotlib pandas

Checkpoint⚓

Create check_env.py, run it, and make sure it prints without error:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import sys
import numpy as np
import scipy
import matplotlib
import pandas as pd

print("python     :", sys.version.split()[0])
print("executable :", sys.executable)   # should point inside your .venv
print("numpy      :", np.__version__)
print("scipy      :", scipy.__version__)
print("matplotlib :", matplotlib.__version__)
print("pandas     :", pd.__version__)

Important

If executable does not point inside your .venv, your IDE is running the wrong Python. Fix that now, or you will encounter errors like "the package is installed but the import fails" during the rest of the course!


A2. Introduction to Numpy⚓

Target: ~15 minutes.

Machine learning involves manipulating datasets as arrays.⚓

Arrays are sets of numbers (often, floating point or integers), and can be as simple as a single number (a singleton), or a vector of length \(N\), or a \(N\times M\) matrix, or more generally a tensor (e.g. a \(N\times M\times P\) array would be called a tensor with three modes).

In this course, we will use two different python packages to manipulate arrays: numpy and pytorch. We will introduce only numpy now, as pytorch is used for deep learning models (covered in detail starting from session 4).

You will find in this section a very short introduction to what is needed to begin the course.

The shape convention we will use for datasets⚓

Throughout the course, a dataset of \(N\) samples described by \(d\) dimensions each is stored as an array of shape (N, d): one row per sample, one column per feature. Keep this convention, it is the one used by numpy, scikit-learn and pytorch alike.

Numpy concepts and functions⚓

Note

If you need more in depth explanations about numpy, the best place to start with is the official numpy website, and in particular the guide for absolute beginners (highly recommended!!).

To familiarize yourself with numpy, we give below the list of concepts and functions you will need. Check the numpy documentation using your IDE or online to have a look at detailed parameters and outputs for those functions.

Creating arrays⚓

Tip

Most useful functions: - Creating arrays with np.array(), np.zeros(), np.ones(), np.arange(). - Use the method .shape or the np.shape() function on any numpy array to know its shape

The np.array() function converts a Python list (or a list of lists) into a NumPy array. You can also create arrays filled with zeros or ones using np.zeros() and np.ones().

Try and familiarize yourself with the following functions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np

# Creating a 1D array from a list
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", array_1d)

# Creating a 2D array (list of lists)
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("2D Array:\n", array_2d)

# Creating a 1D array of zeros
zeros_1d = np.zeros(5)
print("1D Array of zeros:", zeros_1d)

# Creating a 2D array of zeros
zeros_2d = np.zeros((3, 4))  # 3 rows, 4 columns
print("2D Array of zeros:\n", zeros_2d)

# Creating a 2D array of ones
ones_2d = np.ones((2, 3))  # 2 rows, 3 columns (a 2 by 3 matrix)
print("2D Array of ones:\n", ones_2d)

# Creating a 3D array of ones
ones_3d = np.ones((4, 2, 3))  # a 4 by 2 by 3 tensor
print("3D Array of ones:\n", ones_3d)

print(ones_3d.shape)

Important

Get in the habit of printing .shape. Almost every bug you will hit this semester (both in numpy, and later in pytorch) is a shape that is not what you thought it was. Printing shapes is your first debugging tool.

Generating random arrays⚓

!!!tip Most useful functions: - Create a random generator with np.random.default_rng(), then draw with its methods .normal(), .uniform(), .integers(). - The equivalent "legacy" functions np.random.normal(), np.random.uniform(), np.random.randint() also exist, and you will see them everywhere in online code and tutorials.

Random arrays are how we will build synthetic datasets: a cloud of points is nothing more than an array of shape (N, d) whose values are drawn from a probability distribution.

Try to generate some random datasets now!

Play with the parameters, and check each time that the shape you obtain is the one you expected. Plot a cloud with matplotlib.pyplot.scatter() to see what your parameters do.

Tip

Random means non-reproducible, which is a nuisance when you are debugging or comparing results. Fixing the default_rng parameter (called the "seed") at the top of your script, as above, makes your run repeatable: run the same script twice, you get the same numbers. Change the seed, and you get another draw of the same experiment.

Note

All the available distributions are listed in the documentation of the random generator.

Mathematical operations⚓

Numpy arrays behave like mathematical objects: A + B, A - B, 2 * A, A * B (element-wise product, not the matrix product) all work directly, without writing a single loop. Reductions such as np.sum(), np.mean(), np.std(), np.min(), np.max() summarize a whole array, or a chosen axis of it.

Rather than listing them here, read the two short sections of the beginner's guide, and run their examples:

Important

Most of these functions accept an axis argument: on an array X of shape (N, d), X.mean(axis=0) is the mean of each column (one value per feature, so d values), while X.mean(axis=1) is the mean of each row (one value per sample, so N values). Make sure you can predict the shape of the result before running it.

Array manipulation and indexing⚓

Selecting a sample, a feature, or a subset of a dataset is done through indexing: simple indexing and slicing (array[0], array[1:3], X[:, 0]), and boolean masking (array[array > 5]).

The reference for this is, again, the beginner's guide: indexing and slicing. Skim it now, and come back to it whenever you need it.

Note

Indexing may not be needed much for Lab Session 1, but will be heavily uses it from Session 2 onwards.

Saving and loading arrays⚓

Arrays are saved with np.save() (a single array), np.savez() / np.savez_compressed() (several arrays in one file), and read back with np.load(). See the input/output routines of the documentation for the exact syntax.

We recommend np.savez_compressed(), so that you can put multiple arrays in the same file, with added compression to save space.


A3. Exercise: synthetic data and the pairwise distance matrix⚓

Target: ~25 minutes. This is the core exercise of Part A.

Euclidean distance⚓

Because each data point can be represented as a vector in a vector space, the difference between two points can be measured using a distance function.

The simplest and most commonly used distance is the Euclidean distance. In an \(n\)-dimensional space, the Euclidean distance between two vectors is defined as:

\[ d(p, q) = \sqrt{\sum_{i=1}^{n} (q_i - p_i)^2} \]

where \(p = (p_1, p_2, ..., p_n)\) and \(q = (q_1, q_2, ..., q_n)\) are two vectors.

Distance between many points⚓

When dealing with a large dataset, one may want to analyze the differences between all data points to identify patterns or groups within the data.

A useful tool for such applications is the pairwise distance matrix, which computes the distances between every pair of data points and displays them in a matrix format. Given n samples, there are at most n(n - 1)/2 unique pairwise distances (since distances are symmetric).

In this matrix, groups of points with relatively small distances will appear as similar groups, whereas points with high relative distances will stand out as dissimilar. The diagonal of this matrix is equal to 0, because it corresponds to the distance of each point with itself.

Your task⚓

Generate synthetic data with the following specifications:

  • Generate two clouds of points with different centers, in dimension 2.
  • Each cloud has 100 points.
  • Stack them into a single array X of shape (200, 2) (check that shape!).
  • Visualize the two clouds of points using the scatter function from matplotlib.
  • Compute the pairwise distance matrix using the Euclidean distance, using the pdist and squareform functions from scipy.
  • Visualize the distance matrix using the matshow function from matplotlib (add a colorbar()).

Tip

You already have everything you need to generate the clouds: reuse the random generator from the previous section, and array manipulators to concatenate examples.

Once you have plotted the matrix, interpret it and call the teacher to talk about it!

Questions to think about before you call us⚓

  1. What is the shape of the distance matrix? Why?
  2. Why is the diagonal black?
  3. You should see a block structure. What does each block correspond to?
  4. Now shuffle the rows of X (with rng.permutation) and recompute the matrix. What happened to the block structure, and what does that tell you about what the matrix actually measures?
  5. Move the two cloud centers closer and closer together. At what point can you no longer see the two groups? Does the scatter plot or the distance matrix lose the information first?

Important

Question 4 matters. The block structure is not a property of your data alone: it is a property of your data plus the order you happened to store it in. Recognizing what is a real pattern and what is an artefact of how you looked at the data is a real concern in AI! Keep that in mind!


A4. Bridge: looking at a real dataset⚓

Target: ~10 minutes. Short, but this is the recipe you will reuse in Part B when selecting a dataset.

Synthetic data is clean by construction: no missing values, balanced groups, exactly the shape you asked for. Real datasets are not. Before doing anything clever with a dataset, you must know what is in it.

We will use the Palmer penguins dataset (physical measurements of 344 penguins from three species). It is a plain CSV file, hosted online, and pandas can read it directly from its URL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import pandas as pd

url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
df = pd.read_csv(url)

df.to_csv("penguins.csv", index=False)   # keep a local copy, in case the network drops

print(df.shape)                      # how many samples, how many columns?
print(df.head())                     # what does a row look like?
print(df.dtypes)                     # which columns are numbers, which are text?
print(df.isna().sum())               # how many missing values, per column?
print(df["species"].value_counts())  # is the target balanced?

Note

pandas is the standard tool to load and inspect tabular data (rows and named columns). Numpy handles the numbers, pandas handles the bookkeeping around them. Once you have selected and cleaned the columns you want, df[["col1", "col2"]].to_numpy() gives you back a plain (N, d) numpy array, and you are in numpy-land again.

Then:

  1. Build a numpy array X of shape (N, 2) from two numeric columns of your choice (drop rows with missing values first, with df.dropna()).
  2. Run exactly the code from A3 on it: scatter plot, then pairwise distance matrix.
  3. Sort the rows by species before computing the matrix (df.sort_values("species")). Do you see block structure? Is it as clean as with the synthetic clouds?

Part B — Your project (2h30)⚓

Important

Read the project description first: main_project.pdf. It defines what the project is, the criteria your dataset must meet, where to look for datasets, how it is graded, and what your Session 2 presentation must contain. This page does not repeat any of it; it only helps you turn it into 2h30 of concrete work.

B0. A possible way to organise your 2h30⚓

Two and a half hours sounds like a lot. It is not, and the most common failure mode is spending two hours browsing datasets and leaving with nothing written down.

You organise yourselves as you want. The order below is only a suggestion, and the durations are deliberately left out: some binômes find a dataset in ten minutes, others need an hour.

  1. Form your binôme — and register it on Discord.
  2. Find candidate datasets — two or three of them, not only one.
  3. If the task is not straightforward: turning a dataset into a task — with a metric.
  4. Teacher checkpoint — do not leave this for the end of the session (see below).
  5. Sanity-check your own data — it loads, and you know its shape.
  6. Project definition on Discord — written down before you leave (ideally), or during next week (before Session 2).

Steps 2 to 5 may be iterated several times: you may encounter a problem with one dataset or task you planned on using; in that case, use a different one.

By default, define your own project. A list of ready-to-use projects exists as a backup on Github, not as the default. Pick something that motivates you, because it will be used throughout this course, and represent your final evaluation.

B1. Form your binôme⚓

  • Form your binôme (pair). Trinômes and monômes are accepted under the conditions described in the main_project.pdf file.
  • Choose a numbered channel in your group's Discord and write the full names of both members in it.
  • Agree on two practical things right away: where your code will live (a shared git repository is strongly recommended) and roughly when you can work together outside the sessions.

B2. Find candidate datasets⚓

It's better to start from the data than from the idea! Indeed, a dataset may be used in many different ways and fuels some ideas, while the idea won't be possible without some data at hand.

Share your ideas, motivations, curiosity about the use of AI first. Don't hesitate to split the work, and browse different dataset platforms (the list is in the main_project.pdf file), then pool your findings and keep the best two or three datasets.

Check each candidate against the dataset criteria of main_project.pdf: size, completeness, format, license, etc, before you define a task with it. Don't forget one purely practical criterion: check that you can actually download it today, and that it fits on your disk.

Important

A dataset you cannot open for preparing Session 2 is worse than a boring dataset you can. If a candidate requires signing an access agreement, or is 200 GB, or is behind a broken link, drop it now, not urgently next week.

B3. If the task is not straightforward: turning a dataset into a task⚓

Ask yourself, in front of the actual columns of the actual file: what could I predict, cluster, or extract from this data?

Write down, for each of your one or two tasks:

  1. The task, in one sentence, in the form "given \<input>, predict / group / retrieve \<output>". A simple example: "Given the 4 body measurements of a penguin, predict its species." A too vague task definition: "Analyse the penguin dataset."
  2. The input and the output, concretely: what one sample looks like going in, and what comes out.
  3. The metric: how you will know whether it worked, and why that metric is the right one for this task. The metrics may (partly) be qualitative!
  4. Existing methods: what do people usually do for this kind of task? A quick literature/web search is enough for now. You will need a short state of the art review for Session 2.

Be ambitious and creative! Go beyond a simple "input/output" task as it exists on a dataset; you will get bored and may solve the task very easily. Also, we, teachers, probably won't validate it!

Tip

Aim for a core task that you are confident you can do, plus optionally one extension that is more ambitious. This is how the backup project list is structured, and it is a good template: it guarantees you have something to show even if the ambitious part fails.

B4. Teacher checkpoint⚓

Important

This is the single most important thing you do today, and you may want to postpone; please don't! Come and see us as soon as you have a candidate task, in the start/middle of the session, not just in the last fifteen minutes. There are many binômes and few teachers: if everyone comes at the end, we will not be able to see everyone, and you will leave with a project nobody has validated. Validation is important, because it's necessary before the presentation in Session 2. Thus, we may ask you to search for another task/dataset during this validation step!

Call a teacher and discuss your project rapidly: the task, data at hand, metric or evaluation, ... This is a rehearsal for Session 2.

We will mostly be checking three things:

  • Is the task suited for the context of the class? Is it both reasonable and complex enough?
  • Is the dataset relevant for the task?
  • Will you be able to evaluate your task?

The point of coming early is that a checkpoint can send you back: if something does not hold up, you still have time today to switch to your second candidate, redefine the task, and come back for a second, shorter checkpoint. A project rejected at 4PM is ok; a project nobody looked at is a risk you carry until Session 2, where it is graded.

Note

Coming to see us with something imperfect is exactly what we expect. You do not need a finished definition sheet to call a teacher (a dataset link and a sentence starting with "given ..., predict ..." is enough to start the conversation).

B5. Sanity-check your own data⚓

Now apply A4 to your own dataset. Download it, load it, and run the same five print calls:

1
2
3
4
5
print(df.shape)
print(df.head())
print(df.dtypes)
print(df.isna().sum())
print(df[<your target column>].value_counts())

You may use the answers for your Session 2 presentation:

  • How many samples and how many features? → the "Data" slide.
  • How many missing values? → whether you have a cleaning problem to talk about.

B6. Project definition on Discord⚓

Finally, and before you leave (strongly encouraged): post your one-line project title in your binôme's Discord channel.

Important

Within a group, topics must be unique and titles are reserved on a first-come basis. Posting today will help you keep your topic.


What you should take home from this session⚓

  • A virtual environment with numpy, scipy, matplotlib, pandas, and a requirements.txt. You will reuse it all semester.
  • The habit of printing .shape, and the (N, d) convention: one row per sample, one column per feature.
  • The idea that a dataset is a set of points in a space, and that distances between those points already reveal structure — an idea we will come back to in the unsupervised learning session.
  • A registered binôme, a downloaded dataset, and a project task.

Before Session 2: your project title is posted on Discord, and you prepare the 10-minute validation presentation described in the main_project.pdf file.