CS 460G Midterm Hub / Lectures / Week 1 Lecture 3
Week 1 · Lecture 3

Python for Machine Learning II

SciPy, scikit-learn, pandas, PyTorch, and how a class is written.

toolingcoding Q

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

LibraryWhat it is forImport
NumPyarrays, vectorized mathsimport numpy as np
Matplotlib2-D plottingimport matplotlib.pyplot as plt
SciPyinterpolation, image processing, statistics, integration, optimisationimport scipy
scikit-learnML models + metrics + model selectionimport sklearn
pandaslabelled / relational data, CSVimport pandas as pd
PyTorchtensors with GPU, autogradimport 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)
SciPy — I/O, linear algebra, interpolation
SciPy — I/O, linear algebra, interpolation · slide 9

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
The general form for writing a class
The general form for writing a class · slide 22

Anatomy, in the language the slides use:

  • Class names start with an uppercase letter; the file is classname.py in lowercase.
  • __init__ is the constructor; self.x = value creates an instance variable.
  • A function defined inside a class is a method and always takes self first.
  • 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

  1. Save it as calculator.py
  2. Put it in the current directory (where the notebook lives), otherwise %cd /path
  3. %pwd to check where you are
  4. Mount Drive if the file is there:
from google.colab import drive
drive.mount('/content/drive')