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

Python for Machine Learning I

Colab, NumPy, Matplotlib — the tooling layer under every notebook.

toolingcoding Q

Low exam-yield on its own, but every coding question is written in this dialect. Skim it, then use it as a reference when a notebook cell does something you do not recognise.

Colab and the notebook contract

A notebook is a list of cells: text and executable code/output. Submission is the .ipynb plus a PDF. Markdown cells hold the prose and LaTeX equations; code cells hold everything else.

Colab — what a notebook is
Colab — what a notebook is · slide 5

NumPy

The fundamental array package. The properties you will actually use in the notebooks:

arr = np.array([1, 2, 3, 4])
arr.shape    # (4,)
arr.ndim     # 1
arr.size     # 4
arr.dtype    # int64
NumPy arrays — creation and properties
NumPy arrays — creation and properties · slide 27

Key claims from the slide worth remembering: elements are all the same data type, arrays can be 1-D, 2-D or higher, storage is more compact than a Python list, and operations run over the whole array through vectorization (no Python loop).

The in-class exercise list is a decent self-test:

  1. Create an array of 5 numbers
  2. Check size, shape, dimension, dtype
  3. Reverse it
  4. Swap the first and third element
  5. Check whether a specified number is present
  6. Get the unique numbers
  7. Find the numbers greater than 1
  8. Sum, mean, max, min, std
  9. Replace zeros with a non-zero number
  10. 100 random integers and their histogram (np.histogram)

Matplotlib

import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y = [3, 2, 1, 5, 0]
plt.plot(x, y)        # straight line through the points
plt.show()            # render at any point in the code

Formatting calls used constantly in the course notebooks:

CallEffect
plt.axis('off')turn axes off
plt.grid()grid on
plt.xlabel() / plt.ylabel()axis labels
plt.title()title
plt.legend()legend from label= arguments
plt.savefig('f.png', bbox_inches='tight')save
Matplotlib formatting calls
Matplotlib formatting calls · slide 31

Every notebook in this course plots plt.hist(labels) before modelling. That is the label distribution check, and it is graded in Assignment 1. Doing it on X instead of Y was an actual deduction — the histogram must be of the target, not a feature.

Packaging

  • pip install numpy, conda install numpy
  • import numpy, import numpy as np, from numpy import random, from numpy.random import normal
  • A module is a single .py file; a package is a directory of modules with __init__.py.
conda create -n cs460g python
conda env export > cs460g.yml     # at source
conda env create -f cs460g.yml    # at target

That export/import pair is the reproducibility answer if you are asked how to make a project reproducible across machines.