Python for Machine Learning II
SciPy, scikit-learn, pandas, PyTorch, and how a class is written.
The second half of the Python refresher. The only part that touches the exam directly is the object-oriented section, because the PyTorch notebooks define models as classes.
Library map
| Library | What it is for | Import |
|---|---|---|
| NumPy | arrays, vectorized maths | import numpy as np |
| Matplotlib | 2-D plotting | import matplotlib.pyplot as plt |
| SciPy | interpolation, image processing, statistics, integration, optimisation | import scipy |
| scikit-learn | ML models + metrics + model selection | import sklearn |
| pandas | labelled / relational data, CSV | import pandas as pd |
| PyTorch | tensors with GPU, autograd | import torch |
SciPy's sub-modules come up in the notebooks:
import scipy.io as sio
data = sio.loadmat('filename.mat') # load a .mat file
sio.savemat('out.mat', {'k': data}) # save one
from scipy.linalg import solve
x = solve(A, b) # solve Ax = b
from scipy.interpolate import interp1d
new_y = interp1d(x, y, kind='linear')(new_x)

Pandas is used for exactly one thing in the course: pd.read_csv, then .shape, .head(), .isna().sum().
Object-oriented Python
The reason this matters: every neural network in the course is written like this.
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(64, 20)
self.fc2 = nn.Linear(20, 10)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x

Anatomy, in the language the slides use:
- Class names start with an uppercase letter; the file is
classname.pyin lowercase. __init__is the constructor;self.x = valuecreates an instance variable.- A function defined inside a class is a method and always takes
selffirst. Calculator(10, 5)creates an object (an instance) of the class.
class Calculator:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return self.num1 + self.num2
calculator = Calculator(10, 5)
calculator.add() # 15
Likely coding-question phrasing: "This notebook defines class Net(nn.Module). What does super().__init__() do, and why must forward be named exactly forward?" Answer: super().__init__() runs nn.Module's constructor so the object registers its parameters and buffers (without it, PyTorch cannot track or train them). forward is the method PyTorch calls when you write net(x); it is invoked by __call__, which also handles the autograd bookkeeping you would otherwise have to wire yourself.
Importing your own module in Colab
- Save it as
calculator.py - Put it in the current directory (where the notebook lives), otherwise
%cd /path %pwdto check where you are- Mount Drive if the file is there:
from google.colab import drive
drive.mount('/content/drive')





















