2024 CS224N Python Review Session Slides.pptx
2024 CS224N Python Review Session Slides.pptx
2024 CS224N Python Review Session Slides.pptx
CS224N - Winter 25
Stanford University
1
Two entwined snakes, based on Mayan representations.
However, named after Monty Python’s Flying Circus 😅
2
Charting a Course
1 2 3
4 5 6
3
Charting a Course
1 2 3
4 5 6
4
Why Python?
“Slower”, but can run highly optimized C/C++ subroutines to make operations fast 6
Language Basics
https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language 7
Language Basics
https://medium.com/@pavel.loginov.dev/typing-in-python-strong-dynamic-implicit-c3512785b863
8
A Quick Check-In 🥳
9
A Quick Check-In 🥳
10
Charting a Course
1 2 3
4 5 6
11
Syntax Going Forward
12
Python Installation
https://www.python.org/downloads/ 🥳
13
Helpful Commands See Installed Libraries pip is Python’s
$python -m pip list package installer
Print out Version -m runs a module (ex. pip) as a script
$python --version
$python -v
Run in Different Modes
$python -vv
$python script.py
-i remains in interactive
$python -i script.py
Print out Location mode after running .py
$which python (mac, linux)
$where python (windows) $python -c “print(‘hello there!’)”
Problem
● Different versions of Python
● Countless Python packages
and their dependencies
15
Environment Management
16
Solution 1: venv
● Created on top of existing $python -m venv /path/to/new/virtual/env
installation, known as the
Creates a new directory → can activate (differs based on OS)
virtual env’s “base” Python
● Directory contains a specific
Python interpreter and
libraries, binaries which are
needed to support a project
● Isolated from software in other
virtual envs and interpreters
and libraries installed in OS
https://docs.python.org/3/library/venv.html 17
Solution 2: Anaconda (or Miniconda)
https://www.anaconda.com/download/
Choose specific
Very popular Python Basic Workflow Python version
env/package manager Create a new environment
$ conda create –n <environment_name>
● Supports Windows, $ conda create -n <environment_name> python=3.7
Linux, MacOS $ conda env create -f <environment.yml>
Activate/deactivate environment
● Can create and $ conda activate <environment_name>
<...do stuff...>
manage different Export/create
$ conda deactivate from env files!
isolated envs Export environment
$ conda activate <environment_name>
$ conda env export > environment.yml
18
Installing Packages
pip installs only Python packages, conda installs packages which may contain software written in any language
🚨 Best to first use conda to install as many packages as possible and use pip to install remaining packages after.
Install packages using pip in a conda environment (necessary when package not available through conda):
21
🎯 Matching time! A. Python package manager used to
install and manage libraries.
1 2 3
4 5 6
24
Common Operations
x = 10 # Declaring two integer variables
return None
26
Built-in Values
and # Boolean operators in Python written
as plain English, as opposed to &&,
or ||, ! in C++
not
27
Spacing: Brackets → Indents
Code blocks are created using indents and newlines, instead of brackets like in C++
28
🎯 Debugging Derby
0length = 10
float width = 5.0
message = "Completed!'
29
🎯 Debugging Derby
30
🎯 Debugging Derby
length = 10
width = 5.0
print("Beginning work...")
message = "Completed!"
31
Language Basics
1 2 3
4 5 6
32
Collections: List
Lists are mutable arrays (think std::vector).
33
List Slicing
List elements can be accessed in convenient ways.
Basic format: some_list[start_index:end_index]
numbers = [0, 1, 2, 3, 4, 5, 6]
numbers[0:3] == numbers[:3] == [0, 1, 2]
numbers[5:] == numbers[5:7] == [5, 6]
numbers[:] == numbers == [0, 1, 2, 3, 4, 5, 6]
numbers[-1] == 6 # Negative index wraps around
numbers[-3:] == [4, 5, 6]
numbers[3:-2] == [3, 4] # Can mix and match
34
Collections: Tuples
Tuples are immutable arrays.
35
Collections: Dictionary
Dictionaries are hash maps.
36
Loops
For loop syntax in Python
Instead of for (i=0; i<10; i++) syntax in languages like C++, use range()
for i in range(10):
print(i)
>> 0
1…
8
9
37
Loops
To iterate over a list
names = [‘Zach’, ‘Jay’, ‘Richard’] >> Hi Zach!
for name in names: Hi Jay!
print(‘Hi ‘ + name + ‘!’) Hi Richard!
# A different way
for i, name in enumerate(names):
print(i, name)
38
Loops
To iterate over a dictionary
phonebook = {‘Zach’: ‘12-37’, ‘Jay’: ‘34-23’}
for name in phonebook: >> Jay
print(name) Zach
Note: Whether dictionary iteration order is guaranteed depends on the version of Python. 39
Classes
class Animal(object): # Constructor `a =
def __init__(self, species, age): Animal(‘human’, 10)`
# Refer to instance with `self`
self.species = species
# Instance variables are public
self.age = age
def is_person(self):
# Invoked with `a.is_person()`
return self.species
def age_one_year(self):
self.age += 1
import torch.nn as nn
class Model(nn.Module):
def __init__():
…
def forward():
…
41
🎯 Inner Interpreter
m1 = v1[1:-1]
for n in m1:
Output?
print(f"{n} is {v2[n]} years old.")
42
🎯 Inner Interpreter
m1 = v1[1:-1]
for n in m1:
print(f"{n} is {v2[n]} years old.")
1 2 3
4 5 6
44
Prelude: Importing Package Modules
# Import ‘os’ and ‘time’ modules
import os, time
45
Now, NumPy!
48
np.ndarray Operations
Infix operators (i.e. +, -, *, **, /) are element-wise.
Dot product is: np.dot(u, v) np.dot()can also be used, but if A and B are both
2-D arrays, np.matmul() is preferred.
Matrix vector
product (1-D np.dot(x, W) Transpose is: x.T
array vectors) is:
Note: SciPy and np.linalg have many, many other advanced functions that are very useful! 🥳 49
Indexing
x = np.random.random((3, 4)) # Random (3,4) matrix
Note: Selecting with an ndarray or range will preserve the dimensions of the selection. 50
Broadcasting
x = np.random.random((3, 4)) # Random (3, 4) matrix
Note: If you’re getting an error, print the shapes of the matrices and investigate from there.
51
Broadcasting (visually)
1 2 3 4 1 1 1 1 2 3 4 5
5 6 7 8 2 2 2 2 7 8 9 10
9 10 11 12 3 3 3 3 12 13 14 15
x + y
1 2 3 4 1 2 3 4 1 4 9 16
5 6 7 8 1 2 3 4 5 12 21 32
9 10 11 12 1 2 3 4 9 30 33 48
x * z
52
Broadcasting (generalized)
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e.
rightmost) dimensions and works its way left. Two dimensions are compatible when
What do the following operations give us? What are the resulting shapes?
b + b.T
a + c If the arrays have different ranks (number of dimensions), NumPy
b + c implicitly prepends 1s to the shape of the lower-rank array.
53
Broadcasting (generalized)
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e.
rightmost) dimensions and works its way left. Two dimensions are compatible when
What do the following operations give us? What are the resulting shapes?
b + b.T → (3, 3)
a + c → Broadcast Error If the arrays have different ranks (number of dimensions), NumPy
b + c → (3, 3) implicitly prepends 1s to the shape of the lower-rank array.
54
Broadcasting Algorithm
p = max(m, n)
if m < p:
left-pad A's shape with 1s until it also has p dimensions
else if n < p:
left-pad B's shape with 1s until it also has p dimensions
x **= 2 x[np.arange(100,1000), :] += 5
56
🎯 Numpy Knowhow
57
🎯 Numpy Knowhow
58
Language Basics
1 2 3
4 5 6
59
List Comprehensions
● Similar to map() from functional programming languages (readability + succinct)
● Format: [func(x) for x in some_list]
=
squares = []
for i in range(10): squares = [i**2 for i
squares.append(i**2) in range(10)]
● Can be conditional:
61
Debugging Tips
Python has an interactive shell where you can execute arbitrary code.
● Great replacement for TI-84 (no integer overflow!)
● Can import any module (even custom ones in the current directory)
● Try out syntax you’re unsure about and small test cases (especially helpful for matrix operations)
$ python
Python 3.9.7 (default, Sep 16 2021, 08:50:36) Helpful Commands
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
>> import numpy as np Ctrl-d: Exit IPython Session
>> A = np.array([[1, 2], [3, 4]])
>> B = np.array([[3, 3], [3, 3]])
>> A * B
Ctrl-c: Interrupt current command
[[3 6]
[9 12]] Ctrl-l: Clear terminal screen
>> np.matmul(A, B)
[[9 9]
[21 21]]
62
Debugging Tools
https://docs.python.org/3/library/pdb.html 63
Common Errors
ValueError(s) are often caused by mismatch of dimensions in broadcasting or
matrix multiplication. If you get this type of error, a good first step s to print out the
shape of relevant arrays to see if they match what you expect: array.shape
[Very Active, Open-Source Community] When debugging, check Ed and forums such as
StackOverflow or GitHub Issues → likely that others have encountered the same error!
64
Other Great References
Official Python 3 documentation: https://docs.python.org/3/
Official Anaconda user guide:
https://docs.conda.io/projects/conda/en/latest/user-guide/index.html
Official NumPy documentation: https://numpy.org/doc/stable/
Python tutorial from CS231N: https://cs231n.github.io/python-numpy-tutorial/
Stanford Python course (CS41): https://stanfordpython.com/#/
Several Python and library-specific (ex. NumPy) “Cheat Sheet” guides online as well!
65
Yayy, we did it! 🥳
Thanks for listening!
66