100% found this document useful (1 vote)
25 views

@Codeprogrammer Scientific Python Lectures

The document is a comprehensive guide to scientific computing using Python, covering essential libraries such as NumPy, Matplotlib, and SciPy. It includes topics ranging from basic Python programming to advanced constructs and debugging techniques. The content is structured into sections that facilitate learning for both beginners and advanced users in the scientific Python ecosystem.

Uploaded by

fallenalways89
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
25 views

@Codeprogrammer Scientific Python Lectures

The document is a comprehensive guide to scientific computing using Python, covering essential libraries such as NumPy, Matplotlib, and SciPy. It includes topics ranging from basic Python programming to advanced constructs and debugging techniques. The content is structured into sections that facilitate learning for both beginners and advanced users in the scientific Python ecosystem.

Uploaded by

fallenalways89
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1049

SciKits Numpy Matplotlib

2024
SciPy Python EDITION

IP[y]:

Cython IPython
Edited by

Scien�fic Python Gaël Varoquaux


Emmanuelle Gouillart
Olaf Vahtras

Lectures
Pierre de Buyl
K. Jarrod Millman
Stéfan van der Walt

lectures.scientific-python.org

Gaël Varoquaux • Emmanuelle Gouillart • Olav Vahtras


Pierre de Buyl • K. Jarrod Millman • Stéfan van der Walt
Christopher Burns • Adrian Chauve • Robert Cimrman • Christophe Combelles
Ralf Gommers • André Espaze • Zbigniew Jędrzejewski-Szmek
Valen� n Haenel • Michael Hartmann • Gert-Ludwig Ingold • Fabian Pedregosa
Didrik Pinte • Nicolas P. Rougier • Joris Van den Bossche • Pauli Virtanen
and many others...
Contents

I Getting started with Python for science 2


1 Python scientific computing ecosystem 4
1.1 Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 The scientific Python ecosystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Before starting: Installing a working environment . . . . . . . . . . . . . . . . . . . . . . 7
1.4 The workflow: interactive environments and text editors . . . . . . . . . . . . . . . . . . 8

2 The Python language 12


2.1 First steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Basic types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.5 Reusing code: scripts and modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.6 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.7 Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.8 Exception handling in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.9 Object-oriented programming (OOP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

3 NumPy: creating and manipulating numerical data 53


3.1 The NumPy array object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.2 Numerical operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3.3 More elaborate arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.4 Advanced operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.5 Some exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
3.6 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

4 Matplotlib: plotting 106


4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.2 Simple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.3 Figures, Subplots, Axes and Ticks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
4.4 Other Types of Plots: examples and exercises . . . . . . . . . . . . . . . . . . . . . . . . . 118
4.5 Beyond this tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
4.6 Quick references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
4.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

5 SciPy : high-level scientific computing 210


5.1 File input/output: scipy.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
5.2 Special functions: scipy.special . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

i
5.3 Linear algebra operations: scipy.linalg . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
5.4 Interpolation: scipy.interpolate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
5.5 Optimization and fit: scipy.optimize . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
5.6 Statistics and random numbers: scipy.stats . . . . . . . . . . . . . . . . . . . . . . . . 222
5.7 Numerical integration: scipy.integrate . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
5.8 Fast Fourier transforms: scipy.fft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
5.9 Signal processing: scipy.signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
5.10 Image manipulation: scipy.ndimage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
5.11 Summary exercises on scientific computing . . . . . . . . . . . . . . . . . . . . . . . . . . 236
5.12 Full code examples for the SciPy chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

6 Getting help and finding documentation 292

II Advanced topics 295


7 Advanced Python Constructs 297
7.1 Iterators, generator expressions and generators . . . . . . . . . . . . . . . . . . . . . . . . 298
7.2 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
7.3 Context managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311

8 Advanced NumPy 315


8.1 Life of ndarray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
8.2 Universal functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
8.3 Interoperability features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
8.4 Array siblings: chararray, maskedarray . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
8.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
8.6 Contributing to NumPy/SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

9 Debugging code 349


9.1 Avoiding bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
9.2 Debugging workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
9.3 Using the Python debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
9.4 Debugging segmentation faults using gdb . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

10 Optimizing code 361


10.1 Optimization workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
10.2 Profiling Python code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
10.3 Making code go faster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
10.4 Writing faster numerical code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366

11 Sparse Arrays in SciPy 369


11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
11.2 Storage Schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
11.3 Linear System Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
11.4 Other Interesting Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390

12 Image manipulation and processing using NumPy and SciPy 391


12.1 Opening and writing to image files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
12.2 Displaying images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
12.3 Basic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
12.4 Image filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
12.5 Feature extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
12.6 Measuring objects properties: scipy.ndimage.measurements . . . . . . . . . . . . . . . . 406
12.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
12.8 Examples for the image processing chapter . . . . . . . . . . . . . . . . . . . . . . . . . . 409

13 Mathematical optimization: finding minima of functions 436


13.1 Knowing your problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
13.2 A review of the different optimizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440

ii
13.3 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
13.4 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . 446
13.5 Practical guide to optimization with SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . 486
13.6 Special case: non-linear least-squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
13.7 Optimization with constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
13.8 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
13.9 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . 491

14 Interfacing with C 492


14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
14.2 Python-C-Api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
14.3 Ctypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
14.4 SWIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
14.5 Cython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
14.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
14.7 Further Reading and References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
14.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

III Packages and applications 517


15 Statistics in Python 519
15.1 Data representation and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
15.2 Hypothesis testing: comparing two groups . . . . . . . . . . . . . . . . . . . . . . . . . . 525
15.3 Linear models, multiple factors, and analysis of variance . . . . . . . . . . . . . . . . . . . 528
15.4 More visualization: seaborn for statistical exploration . . . . . . . . . . . . . . . . . . . . 534
15.5 Testing for interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
15.6 Full code for the figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
15.7 Solutions to this chapter’s exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566

16 Sympy : Symbolic Mathematics in Python 569


16.1 First Steps with SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
16.2 Algebraic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
16.3 Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
16.4 Equation solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
16.5 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576

17 scikit-image: image processing 578


17.1 Introduction and concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
17.2 Importing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
17.3 Example data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
17.4 Input/output, data types and colorspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
17.5 Image preprocessing / enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
17.6 Image segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
17.7 Measuring regions’ properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
17.8 Data visualization and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
17.9 Feature extraction for computer vision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
17.10 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
17.11 Examples for the scikit-image chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593

18 scikit-learn: machine learning in Python 605


18.1 Introduction: problem settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
18.2 Basic principles of machine learning with scikit-learn . . . . . . . . . . . . . . . . . . . . 610
18.3 Supervised Learning: Classification of Handwritten Digits . . . . . . . . . . . . . . . . . . 616
18.4 Supervised Learning: Regression of Housing Data . . . . . . . . . . . . . . . . . . . . . . 620
18.5 Measuring prediction performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
18.6 Unsupervised Learning: Dimensionality Reduction and Visualization . . . . . . . . . . . . 631
18.7 Parameter selection, Validation, and Testing . . . . . . . . . . . . . . . . . . . . . . . . . 634
18.8 Examples for the scikit-learn chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642

iii
IV About the Scientific Python Lectures 690
19 About the Scientific Python Lectures 691
19.1 Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

Index 694

iv
Scientific Python Lectures, Edition 2024.2rc0.dev0

Contents 1
Part I

Getting started with Python for


science

2
Scientific Python Lectures, Edition 2024.2rc0.dev0

This part of the Scientific Python Lectures is a self-contained introduction to everything that is needed
to use Python for science, from the language itself, to numerical computing or plotting.

3
CHAPTER 1
Python scientific computing ecosystem

Authors: Fernando Perez, Emmanuelle Gouillart, Gaël Varoquaux, Valentin Haenel

1.1 Why Python?

1.1.1 The scientist’s needs

• Get data (simulation, experiment control),


• Manipulate and process data,
• Visualize results, quickly to understand, but also with high quality figures, for reports or publica-
tions.

1.1.2 Python’s strengths

• Batteries included Rich collection of already existing bricks of classic numerical methods, plot-
ting or data processing tools. We don’t want to re-program the plotting of a curve, a Fourier
transform or a fitting algorithm. Don’t reinvent the wheel!
• Easy to learn Most scientists are not paid as programmers, neither have they been trained so.
They need to be able to draw a curve, smooth a signal, do a Fourier transform in a few minutes.
• Easy communication To keep code alive within a lab or a company it should be as readable
as a book by collaborators, students, or maybe customers. Python syntax is simple, avoiding
strange symbols or lengthy routine specifications that would divert the reader from mathematical
or scientific understanding of the code.

4
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Efficient code Python numerical modules are computationally efficient. But needless to say that
a very fast code becomes useless if too much time is spent writing it. Python aims for quick
development times and quick execution times.
• Universal Python is a language used for many different problems. Learning Python avoids learning
a new software for each new problem.

1.1.3 How does Python compare to other solutions?

Compiled languages: C, C++, Fortran. . .

Pros
• Very fast. For heavy computations, it’s difficult to outperform these languages.
Cons
• Painful usage: no interactivity during development, mandatory compilation steps,
verbose syntax, manual memory management. These are difficult languages for
non programmers.

Matlab scripting language

Pros
• Very rich collection of libraries with numerous algorithms, for many different do-
mains. Fast execution because these libraries are often written in a compiled lan-
guage.
• Pleasant development environment: comprehensive and help, integrated editor, etc.
• Commercial support is available.
Cons
• Base language is quite poor and can become restrictive for advanced users.
• Not free and not everything is open sourced.

Julia

Pros
• Fast code, yet interactive and simple.
• Easily connects to Python or C.
Cons
• Ecosystem limited to numerical computing.
• Still young.

1.1. Why Python? 5


Scientific Python Lectures, Edition 2024.2rc0.dev0

Other scripting languages: Scilab, Octave, R, IDL, etc.

Pros
• Open-source, free, or at least cheaper than Matlab.
• Some features can be very advanced (statistics in R, etc.)
Cons
• Fewer available algorithms than in Matlab, and the language is not more advanced.
• Some software are dedicated to one domain. Ex: Gnuplot to draw curves. These
programs are very powerful, but they are restricted to a single type of usage, such
as plotting.

Python

Pros
• Very rich scientific computing libraries
• Well thought out language, allowing to write very readable and well structured code:
we “code what we think”.
• Many libraries beyond scientific computing (web server, serial port access, etc.)
• Free and open-source software, widely spread, with a vibrant community.
• A variety of powerful environments to work in, such as IPython, Spyder, Jupyter
notebooks, Pycharm, Visual Studio Code
Cons
• Not all the algorithms that can be found in more specialized software or toolboxes.

1.2 The scientific Python ecosystem

Unlike Matlab, or R, Python does not come with a pre-bundled set of modules for scientific computing.
Below are the basic building blocks that can be combined to obtain a scientific computing environment:

Python, a generic and modern computing language


• The language: flow control, data types (string, int), data collections (lists, dictionaries), etc.
• Modules of the standard library: string processing, file management, simple network protocols.
• A large number of specialized modules or applications written in Python: web framework, etc. . . .
and scientific computing.
• Development tools (automatic testing, documentation generation)
See also:
chapter on Python language
Core numeric libraries

1.2. The scientific Python ecosystem 6


Scientific Python Lectures, Edition 2024.2rc0.dev0

• NumPy: numerical computing with powerful numerical arrays objects, and routines to manip-
ulate them. https://numpy.org/
See also:
chapter on numpy
• SciPy : high-level numerical routines. Optimization, regression, interpolation, etc https://scipy.
org/
See also:
chapter on SciPy
• Matplotlib : 2-D visualization, “publication-ready” plots https://matplotlib.org/
See also:
chapter on matplotlib
Advanced interactive environments:
• IPython, an advanced Python console https://ipython.org/
• Jupyter, notebooks in the browser https://jupyter.org/
Domain-specific packages,
• pandas, statsmodels, seaborn for statistics
• sympy for symbolic computing
• scikit-image for image processing
• scikit-learn for machine learning
and many more packages not documented in the Scientific Python Lectures.
See also:
chapters on advanced topics
chapters on packages and applications

1.3 Before starting: Installing a working environment

Python comes in many flavors, and there are many ways to install it. However, we recommend to install
a scientific-computing distribution, that comes readily with optimized versions of scientific modules.
Under Linux
If you have a recent distribution, most of the tools are probably packaged, and it is recommended to use
your package manager.
Other systems
There are several fully-featured scientific Python distributions:
• Anaconda
• WinPython

1.3. Before starting: Installing a working environment 7


Scientific Python Lectures, Edition 2024.2rc0.dev0

1.4 The workflow: interactive environments and text editors

Interactive work to test and understand algorithms: In this section, we describe a workflow
combining interactive work and consolidation.
Python is a general-purpose language. As such, there is not one blessed environment to work in, and
not only one way of using it. Although this makes it harder for beginners to find their way, it makes it
possible for Python to be used for programs, in web servers, or embedded devices.

1.4.1 Interactive work

We recommend an interactive work with the IPython console, or its offspring, the Jupyter notebook.
They are handy to explore and understand algorithms.

Under the notebook

To execute code, press “shift enter”

Start ipython:

In [1]: print('Hello world')


Hello world

Getting help by using the ? operator after an object:

In [2]: print?
Signature: print(*args, sep=' ', end='\n', file=None, flush=False)
Docstring:
Prints the values to a stream, or to sys.stdout by default.

sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Type: builtin_function_or_method

See also:
• IPython user manual: https://ipython.readthedocs.io/en/stable/
• Jupyter Notebook QuickStart: https://docs.jupyter.org/en/latest/start/index.html

1.4.2 Elaboration of the work in an editor

As you move forward, it will be important to not only work interactively, but also to create and reuse
Python files. For this, a powerful code editor will get you far. Here are several good easy-to-use editors:
• Spyder: integrates an IPython console, a debugger, a profiler. . .
• PyCharm: integrates an IPython console, notebooks, a debugger. . . (freely available, but commer-
cial)
• Visual Studio Code: integrates a Python console, notebooks, a debugger, . . .

1.4. The workflow: interactive environments and text editors 8


Scientific Python Lectures, Edition 2024.2rc0.dev0

Some of these are shipped by the various scientific Python distributions, and you can find them in the
menus.
As an exercise, create a file my_file.py in a code editor, and add the following lines:

s = 'Hello world'
print(s)

Now, you can run it in IPython console or a notebook and explore the resulting variables:

In [3]: %run my_file.py


Hello world

In [4]: s
Out[4]: 'Hello world'

In [5]: %whos
Variable Type Data/Info
----------------------------
s str Hello world

From a script to functions

While it is tempting to work only with scripts, that is a file full of instructions following each other,
do plan to progressively evolve the script to a set of functions:
• A script is not reusable, functions are.
• Thinking in terms of functions helps breaking the problem in small blocks.

1.4.3 IPython and Jupyter Tips and Tricks

The user manuals contain a wealth of information. Here we give a quick introduction to four useful
features: history, tab completion, magic functions, and aliases.

Command history Like a UNIX shell, the IPython console supports command history. Type up and
down to navigate previously typed commands:

In [6]: x = 10

In [7]: <UP>

In [8]: x = 10

Tab completion Tab completion, is a convenient way to explore the structure of any object you’re
dealing with. Simply type object_name.<TAB> to view the object’s attributes. Besides Python objects
and keywords, tab completion also works on file and directory names.*

1.4. The workflow: interactive environments and text editors 9


Scientific Python Lectures, Edition 2024.2rc0.dev0

In [9]: x = 10

In [10]: x.<TAB>
as_integer_ratio() conjugate() imag to_bytes()
bit_count() denominator numerator
bit_length() from_bytes() real

Magic functions The console and the notebooks support so-called magic functions by prefixing a
command with the % character. For example, the run and whos functions from the previous section are
magic functions. Note that, the setting automagic, which is enabled by default, allows you to omit the
preceding % sign. Thus, you can just type the magic function and it will work.
Other useful magic functions are:
• %cd to change the current directory.

In [11]: cd /tmp
/tmp

• %cpaste allows you to paste code, especially code from websites which has been prefixed with the
standard Python prompt (e.g. >>>) or with an ipython prompt, (e.g. in [3]):

In [12]: %cpaste

• %timeit allows you to time the execution of short snippets using the timeit module from the
standard library:

In [12]: %timeit x = 10
11.6 ns +- 0.818 ns per loop (mean +- std. dev. of 7 runs, 100,000,000 loops␣
˓→each)

See also:
Chapter on optimizing code
• %debug allows you to enter post-mortem debugging. That is to say, if the code you try to execute,
raises an exception, using %debug will enter the debugger at the point where the exception was
thrown.

In [13]: x === 10
Cell In[13], line 1
x === 10
^
SyntaxError: invalid syntax

In [14]: %debug
> /home/jarrod/.venv/lectures/lib64/python3.11/site-packages/IPython/core/
˓→compilerop.py(86)ast_parse()

84 Arguments are exactly the same as ast.parse (in the standard␣


˓→library),

85 and are passed to the built-in compile function."""


---> 86 return compile(source, filename, symbol, self.flags | PyCF_ONLY_
˓→AST, 1)

87
(continues on next page)

1.4. The workflow: interactive environments and text editors 10


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


88 def reset_compiler_flags(self):
ipdb> locals()
{'self': <IPython.core.compilerop.CachingCompiler object at 0x7f30d02efc10>,
˓→'source': 'x === 10\n', 'filename': '<ipython-input-1-8e8bc565444b>', 'symbol

˓→': 'exec'}

ipdb>

See also:
Chapter on debugging

Aliases Furthermore IPython ships with various aliases which emulate common UNIX command line
tools such as ls to list files, cp to copy files and rm to remove files (a full list of aliases is shown when
typing alias).

Getting help

• The built-in cheat-sheet is accessible via the %quickref magic function.


• A list of all available magic functions is shown when typing %magic.

1.4. The workflow: interactive environments and text editors 11


CHAPTER 2
The Python language

Authors: Chris Burns, Christophe Combelles, Emmanuelle Gouillart, Gaël Varoquaux

Python for scientific computing

We introduce here the Python language. Only the bare minimum necessary for getting started with
NumPy and SciPy is addressed here. To learn more about the language, consider going through the
excellent tutorial https://docs.python.org/3/tutorial. Dedicated books are also available, such as Dive
into Python 3.

Tip: Python is a programming language, as are C, Fortran, BASIC, PHP, etc. Some specific
features of Python are as follows:
• an interpreted (as opposed to compiled) language. Contrary to e.g. C or Fortran, one does not
compile Python code before executing it. In addition, Python can be used interactively: many
Python interpreters are available, from which commands and scripts can be executed.
• a free software released under an open-source license: Python can be used and distributed free
of charge, even for building commercial software.
• multi-platform: Python is available for all major operating systems, Windows, Linux/Unix,
MacOS X, most likely your mobile phone OS, etc.
• a very readable language with clear non-verbose syntax

12
Scientific Python Lectures, Edition 2024.2rc0.dev0

• a language for which a large variety of high-quality packages are available for various applications,
from web frameworks to scientific computing.
• a language very easy to interface with other languages, in particular C and C++.
• Some other features of the language are illustrated just below. For example, Python is an object-
oriented language, with dynamic typing (the same variable can contain objects of different types
during the course of a program).
See https://www.python.org/about/ for more information about distinguishing features of Python.

2.1 First steps

Start the Ipython shell (an enhanced interactive Python shell):


• by typing “ipython” from a Linux/Mac terminal, or from the Windows cmd shell,
• or by starting the program from a menu, e.g. the Anaconda Navigator, the Python(x,y) menu if
you have installed one of these scientific-Python suites.

Tip: If you don’t have Ipython installed on your computer, other Python shells are available, such
as the plain Python shell started by typing “python” in a terminal, or the Idle interpreter. However,
we advise to use the Ipython shell because of its enhanced features, especially for interactive scientific
computing.

Once you have started the interpreter, type

>>> print("Hello, world!")


Hello, world!

Tip: The message “Hello, world!” is then displayed. You just executed your first Python instruction,
congratulations!

To get yourself started, type the following stack of instructions

>>> a = 3
>>> b = 2*a
>>> type(b)
<class 'int'>
>>> print(b)
6
>>> a*b
18
>>> b = 'hello'
>>> type(b)
<class 'str'>
>>> b + b
'hellohello'
>>> 2*b
'hellohello'

Tip: Two variables a and b have been defined above. Note that one does not declare the type of a
variable before assigning its value. In C, conversely, one should write:

2.1. First steps 13


Scientific Python Lectures, Edition 2024.2rc0.dev0

int a = 3;

In addition, the type of a variable may change, in the sense that at one point in time it can be equal
to a value of a certain type, and a second point in time, it can be equal to a value of a different type.
b was first equal to an integer, but it became equal to a string when it was assigned the value ‘hello’.
Operations on integers (b=2*a) are coded natively in Python, and so are some operations on strings such
as additions and multiplications, which amount respectively to concatenation and repetition.

2.2 Basic types

2.2.1 Numerical types

Tip: Python supports the following numerical, scalar types:

Integer

>>> 1 + 1
2
>>> a = 4
>>> type(a)
<class 'int'>

Floats

>>> c = 2.1
>>> type(c)
<class 'float'>

Complex

>>> a = 1.5 + 0.5j


>>> a.real
1.5
>>> a.imag
0.5
>>> type(1. + 0j)
<class 'complex'>

Booleans

>>> 3 > 4
False
>>> test = (3 > 4)
>>> test
False
>>> type(test)
<class 'bool'>

Tip: A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations
+, -, *, /, % (modulo) natively implemented

2.2. Basic types 14


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> 7 * 3.
21.0
>>> 2**10
1024
>>> 8 % 3
2

Type conversion (casting):

>>> float(1)
1.0

2.2.2 Containers

Tip: Python provides many efficient types of containers, in which collections of objects can be stored.

Lists

Tip: A list is an ordered collection of objects, that may have different types. For example:

>>> colors = ['red', 'blue', 'green', 'black', 'white']


>>> type(colors)
<class 'list'>

Indexing: accessing individual objects contained in the list:

>>> colors[2]
'green'

Counting from the end with negative indices:

>>> colors[-1]
'white'
>>> colors[-2]
'black'

Warning: Indexing starts at 0 (as in C), not at 1 (as in Fortran or Matlab)!

Slicing: obtaining sublists of regularly-spaced elements:

>>> colors
['red', 'blue', 'green', 'black', 'white']
>>> colors[2:4]
['green', 'black']

Warning: Note that colors[start:stop] contains the elements with indices i such as start<=
i < stop (i ranging from start to stop-1). Therefore, colors[start:stop] has (stop - start)
elements.

2.2. Basic types 15


Scientific Python Lectures, Edition 2024.2rc0.dev0

Slicing syntax: colors[start:stop:stride]

Tip: All slicing parameters are optional:


>>> colors
['red', 'blue', 'green', 'black', 'white']
>>> colors[3:]
['black', 'white']
>>> colors[:3]
['red', 'blue', 'green']
>>> colors[::2]
['red', 'green', 'white']

Lists are mutable objects and can be modified:


>>> colors[0] = 'yellow'
>>> colors
['yellow', 'blue', 'green', 'black', 'white']
>>> colors[2:4] = ['gray', 'purple']
>>> colors
['yellow', 'blue', 'gray', 'purple', 'white']

Note: The elements of a list may have different types:


>>> colors = [3, -200, 'hello']
>>> colors
[3, -200, 'hello']
>>> colors[1], colors[2]
(-200, 'hello')

Tip: For collections of numerical data that all have the same type, it is often more efficient to use the
array type provided by the numpy module. A NumPy array is a chunk of memory containing fixed-sized
items. With NumPy arrays, operations on elements can be faster because elements are regularly spaced
in memory and more operations are performed through specialized C functions instead of Python loops.

Tip: Python offers a large panel of functions to modify lists, or query them. Here are a few examples;
for more details, see https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

Add and remove elements:

>>> colors = ['red', 'blue', 'green', 'black', 'white']


>>> colors.append('pink')
>>> colors
['red', 'blue', 'green', 'black', 'white', 'pink']
>>> colors.pop() # removes and returns the last item
'pink'
>>> colors
['red', 'blue', 'green', 'black', 'white']
>>> colors.extend(['pink', 'purple']) # extend colors, in-place
>>> colors
['red', 'blue', 'green', 'black', 'white', 'pink', 'purple']
>>> colors = colors[:-2]
(continues on next page)

2.2. Basic types 16


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> colors
['red', 'blue', 'green', 'black', 'white']

Reverse:

>>> rcolors = colors[::-1]


>>> rcolors
['white', 'black', 'green', 'blue', 'red']
>>> rcolors2 = list(colors) # new object that is a copy of colors in a different␣
˓→memory area

>>> rcolors2
['red', 'blue', 'green', 'black', 'white']
>>> rcolors2.reverse() # in-place; reversing rcolors2 does not affect colors
>>> rcolors2
['white', 'black', 'green', 'blue', 'red']

Concatenate and repeat lists:

>>> rcolors + colors


['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white']
>>> rcolors * 2
['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red']

Tip: Sort:

>>> sorted(rcolors) # new object


['black', 'blue', 'green', 'red', 'white']
>>> rcolors
['white', 'black', 'green', 'blue', 'red']
>>> rcolors.sort() # in-place
>>> rcolors
['black', 'blue', 'green', 'red', 'white']

Methods and Object-Oriented Programming

The notation rcolors.method() (e.g. rcolors.append(3) and colors.pop()) is our first example
of object-oriented programming (OOP). Being a list, the object rcolors owns the method function
that is called using the notation .. No further knowledge of OOP than understanding the notation .
is necessary for going through this tutorial.

Discovering methods:

Reminder: in Ipython: tab-completion (press tab)


In [1]: rcolors.<TAB>
append() count() insert() reverse()
clear() extend() pop() sort()
copy() index() remove()

2.2. Basic types 17


Scientific Python Lectures, Edition 2024.2rc0.dev0

Strings

Different string syntaxes (simple, double or triple quotes):

s = 'Hello, how are you?'


s = "Hi, what's up"
s = '''Hello,
how are you''' # tripling the quotes allows the
# string to span more than one line
s = """Hi,
what's up?"""

In [2]: 'Hi, what's up?'


Cell In[2], line 1
'Hi, what's up?'
^
SyntaxError: unterminated string literal (detected at line 1)

This syntax error can be avoided by enclosing the string in double quotes instead of single quotes.
Alternatively, one can prepend a backslash to the second single quote. Other uses of the backslash are,
e.g., the newline character \n and the tab character \t.

Tip: Strings are collections like lists. Hence they can be indexed and sliced, using the same syntax and
rules.

Indexing:

>>> a = "hello"
>>> a[0]
'h'
>>> a[1]
'e'
>>> a[-1]
'o'

Tip: (Remember that negative indices correspond to counting from the right end.)

Slicing:

>>> a = "hello, world!"


>>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5
'lo,'
>>> a[2:10:2] # Syntax: a[start:stop:step]
'lo o'
>>> a[::3] # every three characters, from beginning to end
'hl r!'

Tip: Accents and special characters can also be handled as in Python 3 strings consist of Unicode
characters.

A string is an immutable object and it is not possible to modify its contents. One may however create
new strings from the original one.

2.2. Basic types 18


Scientific Python Lectures, Edition 2024.2rc0.dev0

In [3]: a = "hello, world!"

In [4]: a.replace('l', 'z', 1)


Out[4]: 'hezlo, world!'

Tip: Strings have many useful methods, such as a.replace as seen above. Remember the a. object-
oriented notation and use tab completion or help(str) to search for new methods.

See also:
Python offers advanced possibilities for manipulating strings, looking for patterns or formatting. The
interested reader is referred to https://docs.python.org/3/library/stdtypes.html#string-methods and
https://docs.python.org/3/library/string.html#format-string-syntax
String formatting:

>>> 'An integer: %i ; a float: %f ; another string: %s ' % (1, 0.1, 'string') # with␣
˓→more values use tuple after %

'An integer: 1; a float: 0.100000; another string: string'

>>> i = 102
>>> filename = 'processing_of_dataset_%d .txt' % i # no need for tuples with just␣
˓→one value after %

>>> filename
'processing_of_dataset_102.txt'

Dictionaries

Tip: A dictionary is basically an efficient table that maps keys to values.

>>> tel = {'emmanuelle': 5752, 'sebastian': 5578}


>>> tel['francis'] = 5915
>>> tel
{'emmanuelle': 5752, 'sebastian': 5578, 'francis': 5915}
>>> tel['sebastian']
5578
>>> tel.keys()
dict_keys(['emmanuelle', 'sebastian', 'francis'])
>>> tel.values()
dict_values([5752, 5578, 5915])
>>> 'francis' in tel
True

Tip: It can be used to conveniently store and retrieve values associated with a name (a string for a
date, a name, etc.). See https://docs.python.org/3/tutorial/datastructures.html#dictionaries for more
information.
A dictionary can have keys (resp. values) with different types:

>>> d = {'a':1, 'b':2, 3:'hello'}


>>> d
{'a': 1, 'b': 2, 3: 'hello'}

2.2. Basic types 19


Scientific Python Lectures, Edition 2024.2rc0.dev0

More container types

Tuples
Tuples are basically immutable lists. The elements of a tuple are written between parentheses, or just
separated by commas:

>>> t = 12345, 54321, 'hello!'


>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> u = (0, 2)

Sets: unordered, unique items:

>>> s = set(('a', 'b', 'c', 'a'))


>>> s
{'a', 'b', 'c'}
>>> s.difference(('a', 'b'))
{'c'}

2.2.3 Assignment operator

Tip: Python library reference says:


Assignment statements are used to (re)bind names to values and to modify attributes or
items of mutable objects.
In short, it works as follows (simple assignment):
1. an expression on the right hand side is evaluated, the corresponding object is created/obtained
2. a name on the left hand side is assigned, or bound, to the r.h.s. object

Things to note:
• a single object can have several names bound to it:

In [5]: a = [1, 2, 3]

• to change a list in place, use indexing/slices:

In [6]: a = [1, 2, 3]

• the key concept here is mutable vs. immutable


– mutable objects can be changed in place
– immutable objects cannot be modified once created
See also:
A very good and detailed explanation of the above issues can be found in David M. Beazley’s article
Types and Objects in Python.

2.2. Basic types 20


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.3 Control Flow

Controls the order in which the code is executed.

2.3.1 if/elif/else

>>> if 2**2 == 4:
... print("Obvious!")
...
Obvious!

Blocks are delimited by indentation

Tip: Type the following lines in your Python interpreter, and be careful to respect the indentation
depth. The Ipython shell automatically increases the indentation depth after a colon : sign; to decrease
the indentation depth, go four spaces to the left with the Backspace key. Press the Enter key twice to
leave the logical block.

>>> a = 10

>>> if a == 1:
... print(1)
... elif a == 2:
... print(2)
... else:
... print("A lot")
...
A lot

Indentation is compulsory in scripts as well. As an exercise, re-type the previous lines with the same
indentation in a script condition.py, and execute the script with run condition.py in Ipython.

2.3.2 for/range

Iterating with an index:

>>> for i in range(4):


... print(i)
0
1
2
3

But most often, it is more readable to iterate over values:

>>> for word in ('cool', 'powerful', 'readable'):


... print('Python is %s ' % word)
Python is cool
Python is powerful
Python is readable

2.3. Control Flow 21


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.3.3 while/break/continue

Typical C-style while loop (Mandelbrot problem):

>>> z = 1 + 1j
>>> while abs(z) < 100:
... z = z**2 + 1
>>> z
(-134+352j)

More advanced features


break out of enclosing for/while loop:

>>> z = 1 + 1j

>>> while abs(z) < 100:


... if z.imag == 0:
... break
... z = z**2 + 1

continue the next iteration of a loop.:

>>> a = [1, 0, 2, 4]
>>> for element in a:
... if element == 0:
... continue
... print(1. / element)
1.0
0.5
0.25

2.3.4 Conditional Expressions

if <OBJECT>
Evaluates to False:
• any number equal to zero (0, 0.0, 0+0j)
• an empty container (list, tuple, set, dictionary, . . . )
• False, None
Evaluates to True:
• everything else
a == b
Tests equality, with logics:

>>> 1 == 1.
True

a is b
Tests identity: both sides are the same object:

>>> a = 1
>>> b = 1.
>>> a == b
True
(continues on next page)

2.3. Control Flow 22


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> a is b
False

>>> a = 1
>>> b = 1
>>> a is b
True

a in b
For any collection b: b contains a

>>> b = [1, 2, 3]
>>> 2 in b
True
>>> 5 in b
False

If b is a dictionary, this tests that a is a key of b.

2.3.5 Advanced iteration

Iterate over any sequence

You can iterate over any sequence (string, list, keys in a dictionary, lines in a file, . . . ):

>>> vowels = 'aeiouy'

>>> for i in 'powerful':


... if i in vowels:
... print(i)
o
e
u

>>> message = "Hello how are you?"


>>> message.split() # returns a list
['Hello', 'how', 'are', 'you?']
>>> for word in message.split():
... print(word)
...
Hello
how
are
you?

Tip: Few languages (in particular, languages for scientific computing) allow to loop over anything but
integers/indices. With Python it is possible to loop exactly over the objects of interest without bothering
with indices you often don’t care about. This feature can often be used to make code more readable.

Warning: Not safe to modify the sequence you are iterating over.

2.3. Control Flow 23


Scientific Python Lectures, Edition 2024.2rc0.dev0

Keeping track of enumeration number

Common task is to iterate over a sequence while keeping track of the item number.
• Could use while loop with a counter as above. Or a for loop:

>>> words = ('cool', 'powerful', 'readable')


>>> for i in range(0, len(words)):
... print((i, words[i]))
(0, 'cool')
(1, 'powerful')
(2, 'readable')

• But, Python provides a built-in function - enumerate - for this:

>>> for index, item in enumerate(words):


... print((index, item))
(0, 'cool')
(1, 'powerful')
(2, 'readable')

Looping over a dictionary

Use items:

>>> d = {'a': 1, 'b':1.2, 'c':1j}

>>> for key, val in sorted(d.items()):


... print('Key: %s has value: %s ' % (key, val))
Key: a has value: 1
Key: b has value: 1.2
Key: c has value: 1j

Note: The ordering of a dictionary is random, thus we use sorted() which will sort on the keys.

2.3.6 List Comprehensions

Instead of creating a list by means of a loop, one can make use of a list comprehension with a rather
self-explaining syntax.

>>> [i**2 for i in range(4)]


[0, 1, 4, 9]

Exercise

Compute the decimals of Pi using the Wallis formula:



∏︁ 4𝑖2
𝜋=2
𝑖=1
4𝑖2 − 1

2.3. Control Flow 24


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.4 Defining functions

2.4.1 Function definition

In [1]: def test():


...: print('in test function')
...:
...:

In [2]: test()
in test function

Warning: Function blocks must be indented as other control-flow blocks.

2.4.2 Return statement

Functions can optionally return values.

In [3]: def disk_area(radius):


...: return 3.14 * radius * radius
...:

In [4]: disk_area(1.5)
Out[4]: 7.0649999999999995

Note: By default, functions return None.

Note: Note the syntax to define a function:


• the def keyword;
• is followed by the function’s name, then
• the arguments of the function are given between parentheses followed by a colon.
• the function body;
• and return object for optionally returning values.

2.4.3 Parameters

Mandatory parameters (positional arguments)

In [5]: def double_it(x):


...: return x * 2
...:

In [6]: double_it(3)
Out[6]: 6

In [7]: double_it()
---------------------------------------------------------------------------
(continues on next page)

2.4. Defining functions 25


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


TypeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 double_it()

TypeError: double_it() missing 1 required positional argument: 'x'

Optional parameters (keyword or named arguments)

In [8]: def double_it(x=2):


...: return x * 2
...:

In [9]: double_it()
Out[9]: 4

In [10]: double_it(3)
Out[10]: 6

Keyword arguments allow you to specify default values.

Warning: Default values are evaluated when the function is defined, not when it is called. This
can be problematic when using mutable types (e.g. dictionary or list) and modifying them in the
function body, since the modifications will be persistent across invocations of the function.
Using an immutable type in a keyword argument:
In [11]: bigx = 10

In [12]: def double_it(x=bigx):


....: return x * 2
....:

In [13]: bigx = 1e9 # Now really big

In [14]: double_it()
Out[14]: 20

Using an mutable type in a keyword argument (and modifying it inside the function body):
In [15]: def add_to_dict(args={'a': 1, 'b': 2}):
....: for i in args.keys():
....: args[i] += 1
....: print(args)
....:

In [16]: add_to_dict
Out[16]: <function __main__.add_to_dict(args={'a': 1, 'b': 2})>

In [17]: add_to_dict()
{'a': 2, 'b': 3}

In [18]: add_to_dict()
{'a': 3, 'b': 4}

In [19]: add_to_dict()
{'a': 4, 'b': 5}

2.4. Defining functions 26


Scientific Python Lectures, Edition 2024.2rc0.dev0

Tip: More involved example implementing python’s slicing:


In [20]: def slicer(seq, start=None, stop=None, step=None):
....: """Implement basic python slicing."""
....: return seq[start:stop:step]
....:

In [21]: rhyme = 'one fish, two fish, red fish, blue fish'.split()

In [22]: rhyme
Out[22]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [23]: slicer(rhyme)
Out[23]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [24]: slicer(rhyme, step=2)


Out[24]: ['one', 'two', 'red', 'blue']

In [25]: slicer(rhyme, 1, step=2)


Out[25]: ['fish,', 'fish,', 'fish,', 'fish']

In [26]: slicer(rhyme, start=1, stop=4, step=2)


Out[26]: ['fish,', 'fish,']

The order of the keyword arguments does not matter:

In [27]: slicer(rhyme, step=2, start=1, stop=4)


Out[27]: ['fish,', 'fish,']

but it is good practice to use the same ordering as the function’s definition.

Keyword arguments are a very convenient feature for defining functions with a variable number of argu-
ments, especially when default values are to be used in most calls to the function.

2.4.4 Passing by value

Tip: Can you modify the value of a variable inside a function? Most languages (C, Java, . . . ) distinguish
“passing by value” and “passing by reference”. In Python, such a distinction is somewhat artificial, and
it is a bit subtle whether your variables are going to be modified or not. Fortunately, there exist clear
rules.
Parameters to functions are references to objects, which are passed by value. When you pass a variable
to a function, python passes the reference to the object to which the variable refers (the value). Not the
variable itself.

If the value passed in a function is immutable, the function does not modify the caller’s variable. If the
value is mutable, the function may modify the caller’s variable in-place:
>>> def try_to_modify(x, y, z):
... x = 23
... y.append(42)
... z = [99] # new reference
... print(x)
... print(y)
... print(z)
(continues on next page)

2.4. Defining functions 27


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


...
>>> a = 77 # immutable variable
>>> b = [99] # mutable variable
>>> c = [28]
>>> try_to_modify(a, b, c)
23
[99, 42]
[99]
>>> print(a)
77
>>> print(b)
[99, 42]
>>> print(c)
[28]

Functions have a local variable table called a local namespace.


The variable x only exists within the function try_to_modify.

2.4.5 Global variables

Variables declared outside the function can be referenced within the function:

In [28]: x = 5

In [29]: def addx(y):


....: return x + y
....:

In [30]: addx(10)
Out[30]: 15

But these “global” variables cannot be modified within the function, unless declared global in the
function.
This doesn’t work:

In [31]: def setx(y):


....: x = y
....: print('x is %d ' % x)
....:
....:

In [32]: setx(10)
x is 10

In [33]: x
Out[33]: 5

This works:

In [34]: def setx(y):


....: global x
....: x = y
....: print('x is %d ' % x)
....:
....:
(continues on next page)

2.4. Defining functions 28


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

In [35]: setx(10)
x is 10

In [36]: x
Out[36]: 10

2.4.6 Variable number of parameters

Special forms of parameters:


• *args: any number of positional arguments packed into a tuple
• **kwargs: any number of keyword arguments packed into a dictionary

In [37]: def variable_args(*args, **kwargs):


....: print('args is', args)
....: print('kwargs is', kwargs)
....:

In [38]: variable_args('one', 'two', x=1, y=2, z=3)


args is ('one', 'two')
kwargs is {'x': 1, 'y': 2, 'z': 3}

2.4.7 Docstrings

Documentation about what the function does and its parameters. General convention:

In [39]: def funcname(params):


....: """Concise one-line sentence describing the function.
....:
....: Extended summary which can contain multiple paragraphs.
....: """
....: # function body
....: pass
....:

In [40]: funcname?
Signature: funcname(params)
Docstring:
Concise one-line sentence describing the function.
Extended summary which can contain multiple paragraphs.
File: ~/src/scientific-python-lectures/<ipython-input-13-64e466df6d64>
Type: function

Note: Docstring guidelines


For the sake of standardization, the Docstring Conventions webpage documents the semantics and con-
ventions associated with Python docstrings.
Also, the NumPy and SciPy modules have defined a precise standard for documenting scientific functions,
that you may want to follow for your own functions, with a Parameters section, an Examples section,
etc. See https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard

2.4. Defining functions 29


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.4.8 Functions are objects

Functions are first-class objects, which means they can be:


• assigned to a variable
• an item in a list (or any collection)
• passed as an argument to another function.

In [41]: va = variable_args

In [42]: va('three', x=1, y=2)


args is ('three',)
kwargs is {'x': 1, 'y': 2}

2.4.9 Methods

Methods are functions attached to objects. You’ve seen these in our examples on lists, dictionaries,
strings, etc. . .

2.4.10 Exercises

Exercise: Fibonacci sequence

Write a function that displays the n first terms of the Fibonacci sequence, defined by:

⎨ 𝑈0 = 0
𝑈1 = 1
𝑈𝑛+2 = 𝑈𝑛+1 + 𝑈𝑛

Exercise: Quicksort

Implement the quicksort algorithm, as defined by wikipedia

function quicksort(array)
var list less, greater
if length(array) < 2
return array
select and remove a pivot value pivot from array
for each x in array
if x < pivot + 1 then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))

2.4. Defining functions 30


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.5 Reusing code: scripts and modules

For now, we have typed all instructions in the interpreter. For longer sets of instructions we need to
change track and write the code in text files (using a text editor), that we will call either scripts or
modules. Use your favorite text editor (provided it offers syntax highlighting for Python), or the editor
that comes with the Scientific Python Suite you may be using.

2.5.1 Scripts

Tip: Let us first write a script, that is a file with a sequence of instructions that are executed each
time the script is called. Instructions may be e.g. copied-and-pasted from the interpreter (but take care
to respect indentation rules!).

The extension for Python files is .py. Write or copy-and-paste the following lines in a file called test.py

message = "Hello how are you?"


for word in message.split():
print(word)

Tip: Let us now execute the script interactively, that is inside the Ipython interpreter. This is maybe
the most common use of scripts in scientific computing.

Note: in Ipython, the syntax to execute a script is %run script.py. For example,

In [1]: %run test.py


Hello
how
are
you?

In [2]: message
Out[2]: 'Hello how are you?'

The script has been executed. Moreover the variables defined in the script (such as message) are now
available inside the interpreter’s namespace.

Tip: Other interpreters also offer the possibility to execute scripts (e.g., execfile in the plain Python
interpreter, etc.).

It is also possible In order to execute this script as a standalone program, by executing the script inside
a shell terminal (Linux/Mac console or cmd Windows console). For example, if we are in the same
directory as the test.py file, we can execute this in a console:

$ python test.py
Hello
how
are
you?

Tip: Standalone scripts may also take command-line arguments

2.5. Reusing code: scripts and modules 31


Scientific Python Lectures, Edition 2024.2rc0.dev0

In file.py:
import sys
print(sys.argv)

$ python file.py test arguments


['file.py', 'test', 'arguments']

Warning: Don’t implement option parsing yourself. Use a dedicated module such as argparse.

2.5.2 Importing objects from modules

In [3]: import os

In [4]: os
Out[4]: <module 'os' (frozen)>

In [5]: os.listdir('.')
Out[5]:
['profile_ksttxb2h',
'.XIM-unix',
'profile_8jyd3wt0',
'systemd-private-547c90d23384455997d6600060dd5355-chrony.service-Cs0azH',
'profile_i8ku8_ln',
'profile_6c5_7yvi',
'clr-debug-pipe-589-869-in',
'profile_n4tf0uy4',
'profile_7crnvcpm',
'profile_ecjb1ld9',
'profile_m13gl1fv',
'profile_1_590dye',
'profile_v_p76c0x',
'clr-debug-pipe-1621-15129-out',
'profile_lvwe1o1z',
'profile_orrts951',
'profile_bziy8mt_',
'profile_0u5120_y',
'profile_tav_998d',
'.font-unix',
'dotnet-diagnostic-589-869-socket',
'clr-debug-pipe-589-869-out',
'profile_ujz8liq0',
'profile_rqn3apk7',
'profile_f3qz57ee',
'profile_v5h87_cl',
'profile_g8aplujp',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-resolved.service-qwjgaC',
'.Test-unix',
'profile_orda1vei',
'profile_zwgjajcz',
'clr-debug-pipe-1604-14840-in',
'profile_rd6ks_2m',
'profile_hsd6fbf4',
(continues on next page)

2.5. Reusing code: scripts and modules 32


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'.ICE-unix',
'profile_d2w42edv',
'profile_4_zbphdf',
'profile_5ph4s0ch',
'profile_b9bs2_r8',
'profile_ymfgkezo',
'profile_ylf1yz9m',
'profile_ve9ftzec',
'snap-private-tmp',
'profile_b0ttd81w',
'profile_t7xwqh0e',
'profile_vr_ay610',
'profile_559rgua5',
'profile_rhdgkmkd',
'clr-debug-pipe-1604-14840-out',
'profile_7oh0cama',
'profile_m3uuj28r',
'profile_4ks_neaw',
'profile_7j1ejay_',
'profile_boh6o1ne',
'profile_zu2iczx7',
'dotnet-diagnostic-1604-14840-socket',
'profile_xk8a882k',
'www-data-temp-aspnet-0',
'profile_lmfhc2sg',
'profile_ub0d3066',
'profile_hqwvn7hn',
'profile_wie_xyqb',
'profile_akajxynt',
'profile_c91t6jqc',
'dotnet-diagnostic-1621-15129-socket',
'profile_wihes686',
'profile_tpdh8hx5',
'.X11-unix',
'profile_3kvs0c7h',
'profile_jk9kmxtf',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-logind.service-w050a8',
'systemd-private-547c90d23384455997d6600060dd5355-haveged.service-YT5gfq',
'profile_b1nj99y9',
'profile_owlfwm6o',
'profile__5ntcpq1',
'profile_xtdrih3r',
'clr-debug-pipe-1621-15129-in',
'profile_7klgdeg6',
'profile_dckcrseq',
'profile_yrvcipb_']

And also:

In [6]: from os import listdir

Importing shorthands:

In [7]: import numpy as np

2.5. Reusing code: scripts and modules 33


Scientific Python Lectures, Edition 2024.2rc0.dev0

Warning:
from os import *

This is called the star import and please, Do not use it


• Makes the code harder to read and understand: where do symbols come from?
• Makes it impossible to guess the functionality by the context and the name (hint: os.name is
the name of the OS), and to profit usefully from tab completion.
• Restricts the variable names you can use: os.name might override name, or vise-versa.
• Creates possible name clashes between modules.
• Makes the code impossible to statically check for undefined symbols.

Tip: Modules are thus a good way to organize code in a hierarchical way. Actually, all the scientific
computing tools we are going to use are modules:

>>> import numpy as np # data arrays


>>> np.linspace(0, 10, 6)
array([ 0., 2., 4., 6., 8., 10.])
>>> import scipy as sp # scientific computing

2.5.3 Creating modules

Tip: If we want to write larger and better organized programs (compared to simple scripts), where
some objects are defined, (variables, functions, classes) and that we want to reuse several times, we have
to create our own modules.

Let us create a module demo contained in the file demo.py:

"A demo module."

def print_b():
"Prints b."
print("b")

def print_a():
"Prints a."
print("a")

c = 2
d = 2

Tip: In this file, we defined two functions print_a and print_b. Suppose we want to call the print_a
function from the interpreter. We could execute the file as a script, but since we just want to have access
to the function print_a, we are rather going to import it as a module. The syntax is as follows.

2.5. Reusing code: scripts and modules 34


Scientific Python Lectures, Edition 2024.2rc0.dev0

In [8]: import demo

In [9]: demo.print_a()
a

In [10]: demo.print_b()
b

Importing the module gives access to its objects, using the module.object syntax. Don’t forget to put
the module’s name before the object’s name, otherwise Python won’t recognize the instruction.
Introspection
In [11]: demo?
Type: module
Base Class: <type 'module'>
String Form: <module 'demo' from 'demo.py'>
Namespace: Interactive
File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/
˓→demo.py

Docstring:
A demo module.

In [12]: who
demo

In [13]: whos
Variable Type Data/Info
------------------------------
demo module <module 'demo' from 'demo.py'>

In [14]: dir(demo)
Out[14]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'c',
'd',
'print_a',
'print_b']

In [15]: demo.<TAB>
demo.c demo.print_a demo.py
demo.d demo.print_b demo.pyc

Importing objects from modules into the main namespace


In [16]: from demo import print_a, print_b

In [17]: whos
Variable Type Data/Info
--------------------------------
demo module <module 'demo' from 'demo.py'>
print_a function <function print_a at 0xb7421534>
print_b function <function print_b at 0xb74214c4>

(continues on next page)

2.5. Reusing code: scripts and modules 35


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


In [18]: print_a()
a

Warning: Module caching


Modules are cached: if you modify demo.py and re-import it in the old session, you will
get the old one.
Solution:
In [10]: importlib.reload(demo)

2.5.4 ‘__main__’ and module loading

Tip: Sometimes we want code to be executed when a module is run directly, but not when it is imported
by another module. if __name__ == '__main__' allows us to check whether the module is being run
directly.

File demo2.py:

def print_b():
"Prints b."
print("b")

def print_a():
"Prints a."
print("a")

# print_b() runs on import


print_b()

if __name__ == "__main__":
# print_a() is only executed when the module is run directly.
print_a()

Importing it:

In [19]: import demo2


b

In [20]: import demo2

Running it:

In [21]: %run demo2


b
a

2.5. Reusing code: scripts and modules 36


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.5.5 Scripts or modules? How to organize your code

Note: Rule of thumb


• Sets of instructions that are called several times should be written inside functions for better code
reusability.
• Functions (or other bits of code) that are called from several scripts should be written inside a
module, so that only the module is imported in the different scripts (do not copy-and-paste your
functions in the different scripts!).

How modules are found and imported

When the import mymodule statement is executed, the module mymodule is searched in a given list of
directories. This list includes a list of installation-dependent default path (e.g., /usr/lib64/python3.
11) as well as the list of directories specified by the environment variable PYTHONPATH.
The list of directories searched by Python is given by the sys.path variable

In [22]: import sys

In [23]: sys.path
Out[23]:
['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python311.zip',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/lib-dynload',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages']

Modules must be located in the search path, therefore you can:


• write your own modules within directories already defined in the search path (e.g. $HOME/.venv/
lectures/lib64/python3.11/site-packages). You may use symbolic links (on Linux) to keep
the code somewhere else.
• modify the environment variable PYTHONPATH to include the directories containing the user-defined
modules.

Tip: On Linux/Unix, add the following line to a file read by the shell at startup (e.g. /etc/profile,
.profile)

export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules

On Windows, https://support.microsoft.com/kb/310519 explains how to handle environment vari-


ables.

• or modify the sys.path variable itself within a Python script.

Tip:

import sys
new_path = '/home/emma/user_defined_modules'
if new_path not in sys.path:
sys.path.append(new_path)

2.5. Reusing code: scripts and modules 37


Scientific Python Lectures, Edition 2024.2rc0.dev0

This method is not very robust, however, because it makes the code less portable (user-dependent
path) and because you have to add the directory to your sys.path each time you want to import
from a module in this directory.

See also:
See https://docs.python.org/3/tutorial/modules.html for more information about modules.

2.5.6 Packages

A directory that contains many modules is called a package. A package is a module with submodules
(which can have submodules themselves, etc.). A special file called __init__.py (which may be empty)
tells Python that the directory is a Python package, from which modules can be imported.

$ ls
_build_utils/ fft/ _lib/ odr/ spatial/
cluster/ fftpack/ linalg/ optimize/ special/
conftest.py __init__.py linalg.pxd optimize.pxd special.pxd
constants/ integrate/ meson.build setup.py stats/
datasets/ interpolate/ misc/ signal/
_distributor_init.py io/ ndimage/ sparse/
$ cd ndimage
$ ls
_filters.py __init__.py _measurements.py morphology.py src/
filters.py _interpolation.py measurements.py _ni_docstrings.py tests/
_fourier.py interpolation.py meson.build _ni_support.py utils/
fourier.py LICENSE.txt _morphology.py setup.py

From Ipython:

In [24]: import scipy as sp

In [25]: sp.__file__
Out[25]: '/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/scipy/__
˓→init__.py'

In [26]: sp.version.version
Out[26]: '1.13.1'

In [27]: sp.ndimage.morphology.binary_dilation?
Signature:
sp.ndimage.morphology.binary_dilation(
input,
structure=None,
iterations=1,
mask=None,
output=None,
border_value=0,
origin=0,
brute_force=False,
)
Docstring:
Multidimensional binary dilation with the given structuring element.
...

2.5. Reusing code: scripts and modules 38


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.5.7 Good practices

• Use meaningful object names


• Indentation: no choice!

Tip: Indenting is compulsory in Python! Every command block following a colon bears an
additional indentation level with respect to the previous line with a colon. One must therefore
indent after def f(): or while:. At the end of such logical blocks, one decreases the indentation
depth (and re-increases it if a new block is entered, etc.)
Strict respect of indentation is the price to pay for getting rid of { or ; characters that delineate
logical blocks in other languages. Improper indentation leads to errors such as

------------------------------------------------------------
IndentationError: unexpected indent (test.py, line 2)

All this indentation business can be a bit confusing in the beginning. However, with the clear
indentation, and in the absence of extra characters, the resulting code is very nice to read compared
to other languages.

• Indentation depth: Inside your text editor, you may choose to indent with any positive number
of spaces (1, 2, 3, 4, . . . ). However, it is considered good practice to indent with 4 spaces. You
may configure your editor to map the Tab key to a 4-space indentation.
• Style guidelines
Long lines: you should not write very long lines that span over more than (e.g.) 80 characters.
Long lines can be broken with the \ character

>>> long_line = "Here is a very very long line \


... that we break in two parts."

Spaces
Write well-spaced code: put whitespaces after commas, around arithmetic operators, etc.:

>>> a = 1 # yes
>>> a=1 # too cramped

A certain number of rules for writing “beautiful” code (and more importantly using the same
conventions as anybody else!) are given in the Style Guide for Python Code.

Quick read

If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you
can directly skip to the next chapter: NumPy: creating and manipulating numerical data.
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
come back and finish this chapter later.

2.5. Reusing code: scripts and modules 39


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.6 Input and Output

To be exhaustive, here are some information about input and output in Python. Since we will use the
NumPy methods to read and write files, you may skip this chapter at first reading.
We write or read strings to/from files (other types must be converted to strings). To write in a file:

>>> f = open('workfile', 'w') # opens the workfile file


>>> type(f)
<class '_io.TextIOWrapper'>
>>> f.write('This is a test \nand another test')
>>> f.close()

To read from a file

In [1]: f = open('workfile', 'r')

In [2]: s = f.read()

In [3]: print(s)
This is a test
and another test

In [4]: f.close()

See also:
For more details: https://docs.python.org/3/tutorial/inputoutput.html

2.6.1 Iterating over a file

In [5]: f = open('workfile', 'r')

In [6]: for line in f:


...: print(line)
...:
This is a test
and another test

In [7]: f.close()

File modes

• Read-only: r
• Write-only: w
– Note: Create a new file or overwrite existing file.
• Append a file: a
• Read and Write: r+
• Binary mode: b
– Note: Use for binary files, especially on Windows.

2.6. Input and Output 40


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.7 Standard Library

Note: Reference document for this section:


• The Python Standard Library documentation: https://docs.python.org/3/library/index.html
• Python Essential Reference, David Beazley, Addison-Wesley Professional

2.7.1 os module: operating system functionality

“A portable way of using operating system dependent functionality.”

Directory and file manipulation

Current directory:

In [1]: import os

In [2]: os.getcwd()
Out[2]: '/tmp'

List a directory:
In [3]: os.listdir(os.curdir)
Out[3]:
['profile_ksttxb2h',
'profile_crwqcy2d',
'.XIM-unix',
'profile_8jyd3wt0',
'systemd-private-547c90d23384455997d6600060dd5355-chrony.service-Cs0azH',
'profile_i8ku8_ln',
'profile_6c5_7yvi',
'clr-debug-pipe-589-869-in',
'profile_n4tf0uy4',
'profile_rwsw_k2b',
'profile_7crnvcpm',
'profile_ecjb1ld9',
'profile_m13gl1fv',
'profile_1_590dye',
'profile_v_p76c0x',
'clr-debug-pipe-1621-15129-out',
'profile_lvwe1o1z',
'profile_orrts951',
'profile_bziy8mt_',
'profile_0u5120_y',
'profile_tav_998d',
'.font-unix',
'dotnet-diagnostic-589-869-socket',
'clr-debug-pipe-589-869-out',
'profile_ujz8liq0',
'profile_rqn3apk7',
'profile_f3qz57ee',
'profile_v5h87_cl',
'profile_g8aplujp',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-resolved.service-qwjgaC',
(continues on next page)

2.7. Standard Library 41


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'profile_1fx2p0i0',
'.Test-unix',
'profile_orda1vei',
'profile_63ekqtw4',
'profile_zwgjajcz',
'clr-debug-pipe-1604-14840-in',
'profile_rd6ks_2m',
'profile_hsd6fbf4',
'.ICE-unix',
'profile_peh59e70',
'profile_d2w42edv',
'profile_4_zbphdf',
'profile_s35fv1zi',
'profile_5ph4s0ch',
'profile_b9bs2_r8',
'profile_ymfgkezo',
'profile_ylf1yz9m',
'profile_ve9ftzec',
'snap-private-tmp',
'profile_b0ttd81w',
'profile_t7xwqh0e',
'profile_vr_ay610',
'profile_559rgua5',
'profile_rhdgkmkd',
'clr-debug-pipe-1604-14840-out',
'profile_7oh0cama',
'profile_m3uuj28r',
'profile_4ks_neaw',
'profile_2yyxi31b',
'profile_7j1ejay_',
'profile_boh6o1ne',
'profile_nz20vb7_',
'profile_zu2iczx7',
'dotnet-diagnostic-1604-14840-socket',
'profile_xk8a882k',
'profile_l6786qpx',
'www-data-temp-aspnet-0',
'profile_lmfhc2sg',
'profile_ub0d3066',
'profile_hqwvn7hn',
'profile_wie_xyqb',
'profile_akajxynt',
'profile_c91t6jqc',
'dotnet-diagnostic-1621-15129-socket',
'profile_wihes686',
'profile_j7p1hjid',
'profile_tpdh8hx5',
'.X11-unix',
'profile_3kvs0c7h',
'profile_jk9kmxtf',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-logind.service-w050a8',
'systemd-private-547c90d23384455997d6600060dd5355-haveged.service-YT5gfq',
'profile_b1nj99y9',
'profile_owlfwm6o',
'profile__5ntcpq1',
'profile_xtdrih3r',
(continues on next page)

2.7. Standard Library 42


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'clr-debug-pipe-1621-15129-in',
'profile_7klgdeg6',
'profile_dckcrseq',
'profile_yrvcipb_',
'profile_ho2189dy']

Make a directory:

In [4]: os.mkdir('junkdir')

In [5]: 'junkdir' in os.listdir(os.curdir)


Out[5]: True

Rename the directory:


In [6]: os.rename('junkdir', 'foodir')

In [7]: 'junkdir' in os.listdir(os.curdir)


Out[7]: False

In [8]: 'foodir' in os.listdir(os.curdir)


Out[8]: True

In [9]: os.rmdir('foodir')

In [10]: 'foodir' in os.listdir(os.curdir)


Out[10]: False

Delete a file:

In [11]: fp = open('junk.txt', 'w')

In [12]: fp.close()

In [13]: 'junk.txt' in os.listdir(os.curdir)


Out[13]: True

In [14]: os.remove('junk.txt')

In [15]: 'junk.txt' in os.listdir(os.curdir)


Out[15]: False

os.path: path manipulations

os.path provides common operations on pathnames.


In [16]: fp = open('junk.txt', 'w')

In [17]: fp.close()

In [18]: a = os.path.abspath('junk.txt')

In [19]: a
Out[19]: '/tmp/junk.txt'

In [20]: os.path.split(a)
(continues on next page)

2.7. Standard Library 43


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Out[20]: ('/tmp', 'junk.txt')

In [21]: os.path.dirname(a)
Out[21]: '/tmp'

In [22]: os.path.basename(a)
Out[22]: 'junk.txt'

In [23]: os.path.splitext(os.path.basename(a))
Out[23]: ('junk', '.txt')

In [24]: os.path.exists('junk.txt')
Out[24]: True

In [25]: os.path.isfile('junk.txt')
Out[25]: True

In [26]: os.path.isdir('junk.txt')
Out[26]: False

In [27]: os.path.expanduser('~/local')
Out[27]: '/home/runner/local'

In [28]: os.path.join(os.path.expanduser('~'), 'local', 'bin')


Out[28]: '/home/runner/local/bin'

Running an external command

In [29]: os.system('ls')
Out[29]: 0

Note: Alternative to os.system


A noteworthy alternative to os.system is the sh module. Which provides much more convenient ways
to obtain the output, error stream and exit code of the external command.

In [30]: import sh
In [31]: com = sh.ls()

In [31]: print(com)
basic_types.rst exceptions.rst oop.rst standard_library.rst
control_flow.rst first_steps.rst python_language.rst
demo2.py functions.rst python-logo.png
demo.py io.rst reusing_code.rst

In [32]: type(com)
Out[32]: str

2.7. Standard Library 44


Scientific Python Lectures, Edition 2024.2rc0.dev0

Walking a directory

os.path.walk generates a list of filenames in a directory tree.

In [33]: for dirpath, dirnames, filenames in os.walk(os.curdir):


....: for fp in filenames:
....: print(os.path.abspath(fp))
....:
....:
/tmp/clr-debug-pipe-589-869-in
/tmp/junk.txt
/tmp/clr-debug-pipe-1621-15129-out
/tmp/dotnet-diagnostic-589-869-socket
/tmp/clr-debug-pipe-589-869-out
/tmp/clr-debug-pipe-1604-14840-in
/tmp/clr-debug-pipe-1604-14840-out
/tmp/dotnet-diagnostic-1604-14840-socket
/tmp/dotnet-diagnostic-1621-15129-socket
/tmp/clr-debug-pipe-1621-15129-in
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
(continues on next page)

2.7. Standard Library 45


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/dhist
/tmp/bookmarks
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README

Environment variables:

In [34]: os.environ.keys()
Out[34]: KeysView(environ({'SHELL': '/bin/bash', 'COLORTERM': 'truecolor', ...}))

In [35]: os.environ['SHELL']
Out[35]: '/bin/bash'

2.7. Standard Library 46


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.7.2 shutil: high-level file operations

The shutil provides useful file operations:


• shutil.rmtree: Recursively delete a directory tree.
• shutil.move: Recursively move a file or directory to another location.
• shutil.copy: Copy files or directories.

2.7.3 glob: Pattern matching on files

The glob module provides convenient file pattern matching.


Find all files ending in .txt:

In [36]: import glob

In [37]: glob.glob('*.txt')
Out[37]: ['junk.txt']

2.7.4 sys module: system-specific information

System-specific information related to the Python interpreter.


• Which version of python are you running and where is it installed:

In [38]: import sys

In [39]: sys.platform
Out[39]: 'linux'

In [40]: sys.version
Out[40]: '3.11.9 (main, May 9 2024, 14:13:20) [GCC 11.4.0]'

In [41]: sys.prefix
Out[41]: '/opt/hostedtoolcache/Python/3.11.9/x64'

• List of command line arguments passed to a Python script:

In [42]: sys.argv
Out[42]:
['/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sphinx/__main__.
˓→py',

'-b',
'latex',
'-d',
'build/doctrees',
'.',
'build/latex']

sys.path is a list of strings that specifies the search path for modules. Initialized from PYTHONPATH:

In [43]: sys.path
Out[43]:
['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python311.zip',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11',
(continues on next page)

2.7. Standard Library 47


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/lib-dynload',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages']

2.7.5 pickle: easy persistence

Useful to store arbitrary objects to a file. Not safe or fast!

In [44]: import pickle

In [45]: l = [1, None, 'Stan']

In [46]: with open('test.pkl', 'wb') as file:


....: pickle.dump(l, file)
....:

In [47]: with open('test.pkl', 'rb') as file:


....: out = pickle.load(file)
....:

In [48]: out
Out[48]: [1, None, 'Stan']

Exercise

Write a program to search your PYTHONPATH for the module site.py.

path_site

2.8 Exception handling in Python

It is likely that you have raised Exceptions if you have typed all the previous commands of the tutorial.
For example, you may have raised an exception if you entered a command with a typo.
Exceptions are raised by different kinds of errors arising when executing Python code. In your own code,
you may also catch errors, or define custom error types. You may want to look at the descriptions of the
the built-in Exceptions when looking for the right exception type.

2.8.1 Exceptions

Exceptions are raised by errors in Python:

In [1]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[1], line 1
----> 1 1/0

ZeroDivisionError: division by zero

In [2]: 1 + 'e'
(continues on next page)

2.8. Exception handling in Python 48


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[2], line 1
----> 1 1 + 'e'

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In [3]: d = {1:1, 2:2}

In [4]: d[3]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[4], line 1
----> 1 d[3]

KeyError: 3

In [5]: l = [1, 2, 3]

In [6]: l[4]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[6], line 1
----> 1 l[4]

IndexError: list index out of range

In [7]: l.foobar
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 l.foobar

AttributeError: 'list' object has no attribute 'foobar'

As you can see, there are different types of exceptions for different errors.

2.8.2 Catching exceptions

try/except

In [8]: while True:


...: try:
...: x = int(input('Please enter a number: '))
...: break
...: except ValueError:
...: print('That was no valid number. Try again...')
...:
Please enter a number: a
That was no valid number. Try again...
Please enter a number: 1

In [9]: x
Out[9]: 1

2.8. Exception handling in Python 49


Scientific Python Lectures, Edition 2024.2rc0.dev0

try/finally

In [10]: try:
....: x = int(input('Please enter a number: '))
....: finally:
....: print('Thank you for your input')
....:
Please enter a number: a
Thank you for your input
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[10], line 2
1 try:
----> 2 x = int(input('Please enter a number: '))
3 finally:
4 print('Thank you for your input')
ValueError: invalid literal for int() with base 10: 'a'

Important for resource management (e.g. closing a file)

Easier to ask for forgiveness than for permission

In [11]: def print_sorted(collection):


....: try:
....: collection.sort()
....: except AttributeError:
....: pass # The pass statement does nothing
....: print(collection)
....:

In [12]: print_sorted([1, 3, 2])


[1, 2, 3]

In [13]: print_sorted(set((1, 3, 2)))


{1, 2, 3}

In [14]: print_sorted('132')
132

2.8.3 Raising exceptions

• Capturing and reraising an exception:

In [15]: def filter_name(name):


....: try:
....: name = name.encode('ascii')
....: except UnicodeError as e:
....: if name == 'Gaël':
....: print('OK, Gaël')
....: else:
....: raise e
....: return name
....:

In [16]: filter_name('Gaël')
(continues on next page)

2.8. Exception handling in Python 50


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


OK, Gaël
Out[16]: 'Gaël'

In [17]: filter_name('Stéfan')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
Cell In[17], line 1
----> 1 filter_name('Stéfan')

Cell In[15], line 8, in filter_name(name)


6 print('OK, Gaël')
7 else:
----> 8 raise e
9 return name

Cell In[15], line 3, in filter_name(name)


1 def filter_name(name):
2 try:
----> 3 name = name.encode('ascii')
4 except UnicodeError as e:
5 if name == 'Gaël':

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 2:␣


˓→ordinal not in range(128)

• Exceptions to pass messages between parts of the code:

In [18]: def achilles_arrow(x):


....: if abs(x - 1) < 1e-3:
....: raise StopIteration
....: x = 1 - (1-x)/2.
....: return x
....:

In [19]: x = 0

In [20]: while True:


....: try:
....: x = achilles_arrow(x)
....: except StopIteration:
....: break
....:
....:

In [21]: x
Out[21]: 0.9990234375

Use exceptions to notify certain conditions are met (e.g. StopIteration) or not (e.g. custom error raising)

2.8. Exception handling in Python 51


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.9 Object-oriented programming (OOP)

Python supports object-oriented programming (OOP). The goals of OOP are:


• to organize the code, and
• to reuse code in similar contexts.
Here is a small example: we create a Student class, which is an object gathering several custom functions
(methods) and variables (attributes), we will be able to use:

>>> class Student(object):


... def __init__(self, name):
... self.name = name
... def set_age(self, age):
... self.age = age
... def set_major(self, major):
... self.major = major
...
>>> anna = Student('anna')
>>> anna.set_age(21)
>>> anna.set_major('physics')

In the previous example, the Student class has __init__, set_age and set_major methods. Its at-
tributes are name, age and major. We can call these methods and attributes with the following notation:
classinstance.method or classinstance.attribute. The __init__ constructor is a special method
we call with: MyClass(init parameters if any).
Now, suppose we want to create a new class MasterStudent with the same methods and attributes as
the previous one, but with an additional internship attribute. We won’t copy the previous class, but
inherit from it:

>>> class MasterStudent(Student):


... internship = 'mandatory, from March to June'
...
>>> james = MasterStudent('james')
>>> james.internship
'mandatory, from March to June'
>>> james.set_age(23)
>>> james.age
23

The MasterStudent class inherited from the Student attributes and methods.
Thanks to classes and object-oriented programming, we can organize code with different classes corre-
sponding to different objects we encounter (an Experiment class, an Image class, a Flow class, etc.), with
their own methods and attributes. Then we can use inheritance to consider variations around a base
class and reuse code. Ex : from a Flow base class, we can create derived StokesFlow, TurbulentFlow,
PotentialFlow, etc.

2.9. Object-oriented programming (OOP) 52


CHAPTER 3
NumPy: creating and manipulating
numerical data

Authors: Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen
This chapter gives an overview of NumPy, the core tool for performant numerical computing with Python.

3.1 The NumPy array object

Section contents

• What are NumPy and NumPy arrays?


• Creating arrays
• Basic data types
• Basic visualization
• Indexing and slicing
• Copies and views
• Fancy indexing

53
Scientific Python Lectures, Edition 2024.2rc0.dev0

3.1.1 What are NumPy and NumPy arrays?

NumPy arrays

Python objects
• high-level number objects: integers, floating point
• containers: lists (costless insertion and append), dictionaries (fast lookup)
NumPy provides
• extension package to Python for multi-dimensional arrays
• closer to hardware (efficiency)
• designed for scientific computation (convenience)
• Also known as array oriented computing

>>> import numpy as np


>>> a = np.array([0, 1, 2, 3])
>>> a
array([0, 1, 2, 3])

Tip: For example, An array containing:


• values of an experiment/simulation at discrete time steps
• signal recorded by a measurement device, e.g. sound wave
• pixels of an image, grey-level or colour
• 3-D data measured at different X-Y-Z positions, e.g. MRI scan
• ...

Why it is useful: Memory-efficient container that provides fast numerical operations.

In [1]: L = range(1000)

In [2]: %timeit [i**2 for i in L]


43.6 us +- 592 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each)

In [3]: a = np.arange(1000)

In [4]: %timeit a**2


892 ns +- 1.46 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)

3.1. The NumPy array object 54


Scientific Python Lectures, Edition 2024.2rc0.dev0

NumPy Reference documentation

• On the web: https://numpy.org/doc/


• Interactive help:

In [5]: np.array?
Docstring:
array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
like=None)

Create an array.

Parameters
----------
object : array_like
An array, any object exposing the array interface, an object whose
``__array__`` method returns an array, or any (nested) sequence.
If object is a scalar, a 0-dimensional array containing object is
returned.
dtype : data-type, optional
The desired data-type for the array. If not given, NumPy will try to use
a default ``dtype`` that can represent the values (by applying promotion
rules when necessary.)
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy will
only be made if ``__array__`` returns a copy, if obj is a nested
sequence, or if a copy is needed to satisfy any of the other
requirements (``dtype``, ``order``, etc.).
order : {'K', 'A', 'C', 'F'}, optional
Specify the memory layout of the array. If object is not an array, the
newly created array will be in C order (row major) unless 'F' is
specified, in which case it will be in Fortran order (column major).
If object is an array the following holds.

===== ========= ===================================================


order no copy copy=True
===== ========= ===================================================
'K' unchanged F & C order preserved, otherwise most similar order
'A' unchanged F order if input is F and not C, otherwise C order
'C' C order C order
'F' F order F order
===== ========= ===================================================

When ``copy=False`` and a copy is made for other reasons, the result is
the same as if ``copy=True``, with some exceptions for 'A', see the
Notes section. The default order is 'K'.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be prepended to the shape as
needed to meet this requirement.
like : array_like, optional
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
(continues on next page)

3.1. The NumPy array object 55


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


by it. In this case, it ensures the creation of an array object
compatible with that passed in via this argument.

.. versionadded:: 1.20.0

Returns
-------
out : ndarray
An array object satisfying the specified requirements.

See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.

Notes
-----
When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,
and a copy is forced by a change in dtype, then the order of the result is
not necessarily 'C' as expected. This is likely a bug.

Examples
--------
>>> np.array([1, 2, 3])
array([1, 2, 3])

Upcasting:

>>> np.array([1, 2, 3.0])


array([ 1., 2., 3.])

More than one dimension:

>>> np.array([[1, 2], [3, 4]])


array([[1, 2],
[3, 4]])

Minimum dimensions 2:

>>> np.array([1, 2, 3], ndmin=2)


array([[1, 2, 3]])

Type provided:

>>> np.array([1, 2, 3], dtype=complex)


array([ 1.+0.j, 2.+0.j, 3.+0.j])

Data-type consisting of more than one element:

(continues on next page)

3.1. The NumPy array object 56


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))


array([[1, 2],
[3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)


matrix([[1, 2],
[3, 4]])
Type: builtin_function_or_method

• Looking for something:

>>> np.lookfor('create array')


Search results for 'create array'
---------------------------------
numpy.array
Create an array.
numpy.memmap
Create a memory-map to an array stored in a *binary* file on disk.

In [6]: np.con*?
np.concatenate
np.conj
np.conjugate
np.convolve

Import conventions

The recommended convention to import NumPy is:

>>> import numpy as np

3.1.2 Creating arrays

Manual construction of arrays

• 1-D:

>>> a = np.array([0, 1, 2, 3])


>>> a
array([0, 1, 2, 3])
>>> a.ndim
1
>>> a.shape
(4,)
>>> len(a)
4

• 2-D, 3-D, . . . :

3.1. The NumPy array object 57


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array


>>> b
array([[0, 1, 2],
[3, 4, 5]])
>>> b.ndim
2
>>> b.shape
(2, 3)
>>> len(b) # returns the size of the first dimension
2

>>> c = np.array([[[1], [2]], [[3], [4]]])


>>> c
array([[[1],
[2]],

[[3],
[4]]])
>>> c.shape
(2, 2, 1)

Exercise: Simple arrays

• Create a simple two dimensional array. First, redo the examples from above. And then create
your own: how about odd numbers counting backwards on the first row, and even numbers on
the second?
• Use the functions len(), numpy.shape() on these arrays. How do they relate to each other?
And to the ndim attribute of the arrays?

Functions for creating arrays

Tip: In practice, we rarely enter items one by one. . .

• Evenly spaced:

>>> a = np.arange(10) # 0 .. n-1 (!)


>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.arange(1, 9, 2) # start, end (exclusive), step
>>> b
array([1, 3, 5, 7])

• or by number of points:

>>> c = np.linspace(0, 1, 6) # start, end, num-points


>>> c
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
>>> d = np.linspace(0, 1, 5, endpoint=False)
>>> d
array([0. , 0.2, 0.4, 0.6, 0.8])

• Common arrays:

3.1. The NumPy array object 58


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple


>>> a
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
>>> b = np.zeros((2, 2))
>>> b
array([[0., 0.],
[0., 0.]])
>>> c = np.eye(3)
>>> c
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> d = np.diag(np.array([1, 2, 3, 4]))
>>> d
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])

• np.random: random numbers (Mersenne Twister PRNG):

>>> rng = np.random.default_rng(27446968)


>>> a = rng.random(4) # uniform in [0, 1]
>>> a
array([0.64613018, 0.48984931, 0.50851229, 0.22563948])

>>> b = rng.standard_normal(4) # Gaussian


>>> b
array([-0.38250769, -0.61536465, 0.98131732, 0.59353096])

Exercise: Creating arrays using functions

• Experiment with arange, linspace, ones, zeros, eye and diag.


• Create different kinds of arrays with random numbers.
• Try setting the seed before creating an array with random values.
• Look at the function np.empty. What does it do? When might this be useful?

3.1.3 Basic data types

You may have noticed that, in some instances, array elements are displayed with a trailing dot (e.g. 2.
vs 2). This is due to a difference in the data-type used:

>>> a = np.array([1, 2, 3])


>>> a.dtype
dtype('int64')

>>> b = np.array([1., 2., 3.])


>>> b.dtype
dtype('float64')

Tip: Different data-types allow us to store data more compactly in memory, but most of the time we

3.1. The NumPy array object 59


Scientific Python Lectures, Edition 2024.2rc0.dev0

simply work with floating point numbers. Note that, in the example above, NumPy auto-detects the
data-type from the input.

You can explicitly specify which data-type you want:

>>> c = np.array([1, 2, 3], dtype=float)


>>> c.dtype
dtype('float64')

The default data type is floating point:

>>> a = np.ones((3, 3))


>>> a.dtype
dtype('float64')

There are also other types:


Complex

>>> d = np.array([1+2j, 3+4j, 5+6*1j])


>>> d.dtype
dtype('complex128')

Bool

>>> e = np.array([True, False, False, True])


>>> e.dtype
dtype('bool')

Strings

>>> f = np.array(['Bonjour', 'Hello', 'Hallo'])


>>> f.dtype # <--- strings containing max. 7 letters
dtype('<U7')

Much more
• int32
• int64
• uint32
• uint64

3.1.4 Basic visualization

Now that we have our first data arrays, we are going to visualize them.
Start by launching IPython:

$ ipython # or ipython3 depending on your install

Or the notebook:

$ jupyter notebook

Once IPython has started, enable interactive plots:

3.1. The NumPy array object 60


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> %matplotlib

Or, from the notebook, enable plots in the notebook:

>>> %matplotlib inline

The inline is important for the notebook, so that plots are displayed in the notebook and not in a new
window.
Matplotlib is a 2D plotting package. We can import its functions as below:

>>> import matplotlib.pyplot as plt # the tidy way

And then use (note that you have to use show explicitly if you have not enabled interactive plots with
%matplotlib):

>>> plt.plot(x, y) # line plot


>>> plt.show() # <-- shows the plot (not needed with interactive plots)

Or, if you have enabled interactive plots with %matplotlib:

>>> plt.plot(x, y) # line plot

• 1D plotting:

>>> x = np.linspace(0, 3, 20)


>>> y = np.linspace(0, 9, 20)
>>> plt.plot(x, y) # line plot
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(x, y, 'o') # dot plot
[<matplotlib.lines.Line2D object at ...>]

• 2D arrays (such as images):

>>> rng = np.random.default_rng(27446968)


>>> image = rng.random((30, 30))
>>> plt.imshow(image, cmap=plt.cm.hot)
<matplotlib.image.AxesImage object at ...>
>>> plt.colorbar()
<matplotlib.colorbar.Colorbar object at ...>

3.1. The NumPy array object 61


Scientific Python Lectures, Edition 2024.2rc0.dev0

See also:
More in the: matplotlib chapter

Exercise: Simple visualizations

• Plot some simple arrays: a cosine as a function of time and a 2D matrix.


• Try using the gray colormap on the 2D matrix.

3.1.5 Indexing and slicing

The items of an array can be accessed and assigned to the same way as other Python sequences (e.g.
lists):

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[0], a[2], a[-1]
(0, 2, 9)

Warning: Indices begin at 0, like other Python sequences (and C/C++). In contrast, in Fortran
or Matlab, indices begin at 1.

The usual python idiom for reversing a sequence is supported:

>>> a[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

For multidimensional arrays, indices are tuples of integers:

>>> a = np.diag(np.arange(3))
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 2]])
>>> a[1, 1]
1
>>> a[2, 1] = 10 # third line, second column
>>> a
(continues on next page)

3.1. The NumPy array object 62


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


array([[ 0, 0, 0],
[ 0, 1, 0],
[ 0, 10, 2]])
>>> a[1]
array([0, 1, 0])

Note:
• In 2D, the first dimension corresponds to rows, the second to columns.
• for multidimensional a, a[0] is interpreted by taking all elements in the unspecified dimensions.

Slicing: Arrays, like other Python sequences can also be sliced:


>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[2:9:3] # [start:end:step]
array([2, 5, 8])

Note that the last index is not included! :

>>> a[:4]
array([0, 1, 2, 3])

All three slice components are not required: by default, start is 0, end is the last and step is 1:
>>> a[1:3]
array([1, 2])
>>> a[::2]
array([0, 2, 4, 6, 8])
>>> a[3:]
array([3, 4, 5, 6, 7, 8, 9])

A small illustrated summary of NumPy indexing and slicing. . .


>>> a[0, 3:5]
array([3, 4]) 0 1 2 3 4 5
>>> a[4:, 4:]
10 11 12 13 14 15
array([[44, 55],
[54, 55]]) 20 21 22 23 24 25
>>> a[:, 2]
30 31 32 33 34 35
a([2, 12, 22, 32, 42, 52])

>>> a[2::2, ::2] 40 41 42 43 44 45


array([[20, 22, 24],
50 51 52 53 54 55
[40, 42, 44]])

You can also combine assignment and slicing:


>>> a = np.arange(10)
>>> a[5:] = 10
>>> a
(continues on next page)

3.1. The NumPy array object 63


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10])
>>> b = np.arange(5)
>>> a[5:] = b[::-1]
>>> a
array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0])

Exercise: Indexing and slicing

• Try the different flavours of slicing, using start, end and step: starting from a linspace, try to
obtain odd numbers counting backwards, and even numbers counting forwards.
• Reproduce the slices in the diagram above. You may use the following expression to create the
array:
>>> np.arange(6) + np.arange(0, 51, 10)[:, np.newaxis]
array([[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55]])

Exercise: Array creation

Create the following arrays (with correct data types):


[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 2],
[1, 6, 1, 1]]

[[0., 0., 0., 0., 0.],


[2., 0., 0., 0., 0.],
[0., 3., 0., 0., 0.],
[0., 0., 4., 0., 0.],
[0., 0., 0., 5., 0.],
[0., 0., 0., 0., 6.]]

Par on course: 3 statements for each


Hint: Individual array elements can be accessed similarly to a list, e.g. a[1] or a[1, 2].
Hint: Examine the docstring for diag.

Exercise: Tiling for array creation

Skim through the documentation for np.tile, and use this function to construct the array:
[[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1],
[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1]]

3.1. The NumPy array object 64


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.1.6 Copies and views

A slicing operation creates a view on the original array, which is just a way of accessing array data.
Thus the original array is not copied in memory. You can use np.may_share_memory() to check if two
arrays share the same memory block. Note however, that this uses heuristics and may give you false
positives.
When modifying the view, the original array is modified as well:
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = a[::2]
>>> b
array([0, 2, 4, 6, 8])
>>> np.may_share_memory(a, b)
True
>>> b[0] = 12
>>> b
array([12, 2, 4, 6, 8])
>>> a # (!)
array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a = np.arange(10)
>>> c = a[::2].copy() # force a copy
>>> c[0] = 12
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> np.may_share_memory(a, c)
False

This behavior can be surprising at first sight. . . but it allows to save both memory and time.

Worked example: Prime number sieve

Compute prime numbers in 0–99, with a sieve


• Construct a shape (100,) boolean array is_prime, filled with True in the beginning:
>>> is_prime = np.ones((100,), dtype=bool)

3.1. The NumPy array object 65


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Cross out 0 and 1 which are not primes:


>>> is_prime[:2] = 0

• For each integer j starting from 2, cross out its higher multiples:
>>> N_max = int(np.sqrt(len(is_prime) - 1))
>>> for j in range(2, N_max + 1):
... is_prime[2*j::j] = False

• Skim through help(np.nonzero), and print the prime numbers


• Follow-up:
– Move the above code into a script file named prime_sieve.py
– Run it to check it works
– Use the optimization suggested in the sieve of Eratosthenes:
1. Skip j which are already known to not be primes
2. The first number to cross out is 𝑗 2

3.1.7 Fancy indexing

Tip: NumPy arrays can be indexed with slices, but also with boolean or integer arrays (masks). This
method is called fancy indexing. It creates copies not views.

Using boolean masks

>>> rng = np.random.default_rng(27446968)


>>> a = rng.integers(0, 21, 15)
>>> a
array([ 3, 13, 12, 10, 10, 10, 18, 4, 8, 5, 6, 11, 12, 17, 3])
>>> (a % 3 == 0)
array([ True, False, True, False, False, False, True, False, False,
False, True, False, True, False, True])
>>> mask = (a % 3 == 0)
>>> extract_from_a = a[mask] # or, a[a%3==0]
>>> extract_from_a # extract a sub-array with the mask
array([ 3, 12, 18, 6, 12, 3])

Indexing with a mask can be very useful to assign a new value to a sub-array:

>>> a[a % 3 == 0] = -1
>>> a
array([-1, 13, -1, 10, 10, 10, -1, 4, 8, 5, -1, 11, -1, 17, -1])

3.1. The NumPy array object 66


Scientific Python Lectures, Edition 2024.2rc0.dev0

Indexing with an array of integers

>>> a = np.arange(0, 100, 10)


>>> a
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

Indexing can be done with an array of integers, where the same index is repeated several time:

>>> a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list


array([20, 30, 20, 40, 20])

New values can be assigned with this kind of indexing:

>>> a[[9, 7]] = -100


>>> a
array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100])

Tip: When a new array is created by indexing with an array of integers, the new array has the same
shape as the array of integers:

>>> a = np.arange(10)
>>> idx = np.array([[3, 4], [9, 7]])
>>> idx.shape
(2, 2)
>>> a[idx]
array([[3, 4],
[9, 7]])

The image below illustrates various fancy indexing applications

>>> a[(0,1,2,3,4), (1,2,3,4,5)]


0 1 2 3 4 5
array([1, 12, 23, 34, 45])

>>> a[3:, [0,2,5]] 10 11 12 13 14 15


array([[30, 32, 35],
20 21 22 23 24 25
[40, 42, 45],
[50, 52, 55]])
30 31 32 33 34 35
>>> mask = np.array([1,0,1,0,0,1], dtype=bool)
>>> a[mask, 2] 40 41 42 43 44 45
array([2, 22, 52])
50 51 52 53 54 55

Exercise: Fancy indexing

• Again, reproduce the fancy indexing shown in the diagram above.


• Use fancy indexing on the left and array creation on the right to assign values into an array, for
instance by setting parts of the array in the diagram above to zero.

3.1. The NumPy array object 67


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.2 Numerical operations on arrays

Section contents

• Elementwise operations
• Basic reductions
• Broadcasting
• Array shape manipulation
• Sorting data
• Summary

3.2.1 Elementwise operations

Basic operations

With scalars:

>>> a = np.array([1, 2, 3, 4])


>>> a + 1
array([2, 3, 4, 5])
>>> 2**a
array([ 2, 4, 8, 16])

All arithmetic operates elementwise:

>>> b = np.ones(4) + 1
>>> a - b
array([-1., 0., 1., 2.])
>>> a * b
array([2., 4., 6., 8.])

>>> j = np.arange(5)
>>> 2**(j + 1) - j
array([ 2, 3, 6, 13, 28])

These operations are of course much faster than if you did them in pure python:

>>> a = np.arange(10000)
>>> %timeit a + 1
10000 loops, best of 3: 24.3 us per loop
>>> l = range(10000)
>>> %timeit [i+1 for i in l]
1000 loops, best of 3: 861 us per loop

Warning: Array multiplication is not matrix multiplication:


>>> c = np.ones((3, 3))
>>> c * c # NOT matrix multiplication!
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

3.2. Numerical operations on arrays 68


Scientific Python Lectures, Edition 2024.2rc0.dev0

Note: Matrix multiplication:

>>> c @ c
array([[3., 3., 3.],
[3., 3., 3.],
[3., 3., 3.]])

Exercise: Elementwise operations

• Try simple arithmetic elementwise operations: add even elements with odd elements
• Time them against their pure python counterparts using %timeit.
• Generate:
– [2**0, 2**1, 2**2, 2**3, 2**4]
– a_j = 2^(3*j) - j

Other operations

Comparisons:

>>> a = np.array([1, 2, 3, 4])


>>> b = np.array([4, 2, 2, 4])
>>> a == b
array([False, True, False, True])
>>> a > b
array([False, False, True, False])

Tip: Array-wise comparisons:

>>> a = np.array([1, 2, 3, 4])


>>> b = np.array([4, 2, 2, 4])
>>> c = np.array([1, 2, 3, 4])
>>> np.array_equal(a, b)
False
>>> np.array_equal(a, c)
True

Logical operations:

>>> a = np.array([1, 1, 0, 0], dtype=bool)


>>> b = np.array([1, 0, 1, 0], dtype=bool)
>>> np.logical_or(a, b)
array([ True, True, True, False])
>>> np.logical_and(a, b)
array([ True, False, False, False])

Transcendental functions:

>>> a = np.arange(5)
>>> np.sin(a)
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])
(continues on next page)

3.2. Numerical operations on arrays 69


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> np.exp(a)
array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003])
>>> np.log(np.exp(a))
array([0., 1., 2., 3., 4.])

Shape mismatches

>>> a = np.arange(4)
>>> a + np.array([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (2,)

Broadcasting? We’ll return to that later.


Transposition:

>>> a = np.triu(np.ones((3, 3)), 1) # see help(np.triu)


>>> a
array([[0., 1., 1.],
[0., 0., 1.],
[0., 0., 0.]])
>>> a.T
array([[0., 0., 0.],
[1., 0., 0.],
[1., 1., 0.]])

Note: The transposition is a view


The transpose returns a view of the original array:

>>> a = np.arange(9).reshape(3, 3)
>>> a.T[0, 2] = 999
>>> a.T
array([[ 0, 3, 999],
[ 1, 4, 7],
[ 2, 5, 8]])
>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[999, 7, 8]])

Note: Linear algebra


The sub-module numpy.linalg implements basic linear algebra, such as solving linear systems, singular
value decomposition, etc. However, it is not guaranteed to be compiled using efficient routines, and thus
we recommend the use of scipy.linalg, as detailed in section Linear algebra operations: scipy.linalg

Exercise other operations

• Look at the help for np.allclose. When might this be useful?


• Look at the help for np.triu and np.tril.

3.2. Numerical operations on arrays 70


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.2.2 Basic reductions

Computing sums

>>> x = np.array([1, 2, 3, 4])


>>> np.sum(x)
10
>>> x.sum()
10

Sum by rows and by columns:

>>> x = np.array([[1, 1], [2, 2]])


>>> x
array([[1, 1],
[2, 2]])
>>> x.sum(axis=0) # columns (first dimension)
array([3, 3])
>>> x[:, 0].sum(), x[:, 1].sum()
(3, 3)
>>> x.sum(axis=1) # rows (second dimension)
array([2, 4])
>>> x[0, :].sum(), x[1, :].sum()
(2, 4)

Tip: Same idea in higher dimensions:

>>> rng = np.random.default_rng(27446968)


>>> x = rng.random((2, 2, 2))
>>> x.sum(axis=2)[0, 1]
0.73415...
>>> x[0, 1, :].sum()
0.73415...

3.2. Numerical operations on arrays 71


Scientific Python Lectures, Edition 2024.2rc0.dev0

Other reductions

— works the same way (and take axis=)


Extrema:

>>> x = np.array([1, 3, 2])


>>> x.min()
1
>>> x.max()
3

>>> x.argmin() # index of minimum


0
>>> x.argmax() # index of maximum
1

Logical operations:

>>> np.all([True, True, False])


False
>>> np.any([True, True, False])
True

Note: Can be used for array comparisons:

>>> a = np.zeros((100, 100))


>>> np.any(a != 0)
False
>>> np.all(a == a)
True

>>> a = np.array([1, 2, 3, 2])


>>> b = np.array([2, 2, 3, 2])
>>> c = np.array([6, 4, 4, 5])
>>> ((a <= b) & (b <= c)).all()
True

Statistics:

>>> x = np.array([1, 2, 3, 1])


>>> y = np.array([[1, 2, 3], [5, 6, 1]])
>>> x.mean()
1.75
>>> np.median(x)
1.5
>>> np.median(y, axis=-1) # last axis
array([2., 5.])

>>> x.std() # full population standard dev.


0.82915619758884995

. . . and many more (best to learn as you go).

Exercise: Reductions

3.2. Numerical operations on arrays 72


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Given there is a sum, what other function might you expect to see?
• What is the difference between sum and cumsum?

Worked Example: diffusion using a random walk algorithm

Tip: Let us consider a simple 1D random walk process: at each time step a walker jumps right or
left with equal probability.
We are interested in finding the typical distance from the origin of a random walker after t left or
right jumps? We are going to simulate many “walkers” to find this law, and we are going to do so
using array computing tricks: we are going to create a 2D array with the “stories” (each walker has a
story) in one direction, and the time in the other:

>>> n_stories = 1000 # number of walkers


>>> t_max = 200 # time during which we follow the walker

We randomly choose all the steps 1 or -1 of the walk:


>>> t = np.arange(t_max)
>>> rng = np.random.default_rng()
>>> steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 # +1 because the␣
˓→high value is exclusive

>>> np.unique(steps) # Verification: all steps are 1 or -1


array([-1, 1])

We build the walks by summing steps along the time:


>>> positions = np.cumsum(steps, axis=1) # axis = 1: dimension of time
>>> sq_distance = positions**2

We get the mean in the axis of the stories:


>>> mean_sq_distance = np.mean(sq_distance, axis=0)

Plot the results:


>>> plt.figure(figsize=(4, 3))
<Figure size ... with 0 Axes>
>>> plt.plot(t, np.sqrt(mean_sq_distance), 'g.', t, np.sqrt(t), 'y-')
[<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel(r"$t$")
Text(...'$t$')
>>> plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$")
Text(...'$\\sqrt{\\langle (\\delta x)^2 \\rangle}$')
>>> Numerical
3.2. plt.tight_layout()
operations #onprovide
arrays sufficient space for labels 73
Scientific Python Lectures, Edition 2024.2rc0.dev0

We find a well-known result in physics: the RMS distance grows as the square root of the time!

3.2.3 Broadcasting

• Basic operations on numpy arrays (addition, etc.) are elementwise


• This works on arrays of the same size.
Nevertheless, It’s also possible to do operations on arrays of different
sizes if NumPy can transform these arrays so that they all have
the same size: this conversion is called broadcasting.
The image below gives an example of broadcasting:

Let’s verify:

3.2. Numerical operations on arrays 74


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T


>>> a
array([[ 0, 0, 0],
[10, 10, 10],
[20, 20, 20],
[30, 30, 30]])
>>> b = np.array([0, 1, 2])
>>> a + b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])

We have already used broadcasting without knowing it!:


>>> a = np.ones((4, 5))
>>> a[0] = 2 # we assign an array of dimension 0 to an array of dimension 1
>>> a
array([[2., 2., 2., 2., 2.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])

A useful trick:
>>> a = np.arange(0, 40, 10)
>>> a.shape
(4,)
>>> a = a[:, np.newaxis] # adds a new axis -> 2D array
>>> a.shape
(4, 1)
>>> a
array([[ 0],
[10],
[20],
[30]])
>>> a + b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])

Tip: Broadcasting seems a bit magical, but it is actually quite natural to use it when we want to solve
a problem whose output data is an array with more dimensions than input data.

Worked Example: Broadcasting

Let’s construct an array of distances (in miles) between cities of Route 66: Chicago, Springfield,
Saint-Louis, Tulsa, Oklahoma City, Amarillo, Santa Fe, Albuquerque, Flagstaff and Los Angeles.
>>> mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544,
... 1913, 2448])
>>> distance_array = np.abs(mileposts - mileposts[:, np.newaxis])
>>> distance_array
array([[ 0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448],
[ 198, 0, 105, 538, 673, 977, 1277, 1346, 1715, 2250],

3.2. Numerical operations on arrays 75


Scientific Python Lectures, Edition 2024.2rc0.dev0

[ 303, 105, 0, 433, 568, 872, 1172, 1241, 1610, 2145],


[ 736, 538, 433, 0, 135, 439, 739, 808, 1177, 1712],
[ 871, 673, 568, 135, 0, 304, 604, 673, 1042, 1577],
[1175, 977, 872, 439, 304, 0, 300, 369, 738, 1273],
[1475, 1277, 1172, 739, 604, 300, 0, 69, 438, 973],
[1544, 1346, 1241, 808, 673, 369, 69, 0, 369, 904],
[1913, 1715, 1610, 1177, 1042, 738, 438, 369, 0, 535],
[2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535, 0]])

A lot of grid-based or network-based problems can also use broadcasting. For instance, if we want to
compute the distance from the origin of points on a 5x5 grid, we can do

>>> x, y = np.arange(5), np.arange(5)[:, np.newaxis]


>>> distance = np.sqrt(x ** 2 + y ** 2)
>>> distance
array([[0. , 1. , 2. , 3. , 4. ],
[1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563],
[2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595],
[3. , 3.16227766, 3.60555128, 4.24264069, 5. ],
[4. , 4.12310563, 4.47213595, 5. , 5.65685425]])

Or in color:

>>> plt.pcolor(distance)
<matplotlib.collections.PolyQuadMesh object at ...>
>>> plt.colorbar()
<matplotlib.colorbar.Colorbar object at ...>

3.2. Numerical operations on arrays 76


Scientific Python Lectures, Edition 2024.2rc0.dev0

Remark : the numpy.ogrid() function allows to directly create vectors x and y of the previous example,
with two “significant dimensions”:

>>> x, y = np.ogrid[0:5, 0:5]


>>> x, y
(array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]]))
>>> x.shape, y.shape
((5, 1), (1, 5))
>>> distance = np.sqrt(x ** 2 + y ** 2)

Tip: So, np.ogrid is very useful as soon as we have to handle computations on a grid. On the other
hand, np.mgrid directly provides matrices full of indices for cases where we can’t (or don’t want to)
benefit from broadcasting:

>>> x, y = np.mgrid[0:4, 0:4]


>>> x
array([[0, 0, 0, 0],
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
>>> y
array([[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]])

See also:
Broadcasting: discussion of broadcasting in the Advanced NumPy chapter.

3.2. Numerical operations on arrays 77


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.2.4 Array shape manipulation

Flattening

>>> a = np.array([[1, 2, 3], [4, 5, 6]])


>>> a.ravel()
array([1, 2, 3, 4, 5, 6])
>>> a.T
array([[1, 4],
[2, 5],
[3, 6]])
>>> a.T.ravel()
array([1, 4, 2, 5, 3, 6])

Higher dimensions: last dimensions ravel out “first”.

Reshaping

The inverse operation to flattening:

>>> a.shape
(2, 3)
>>> b = a.ravel()
>>> b = b.reshape((2, 3))
>>> b
array([[1, 2, 3],
[4, 5, 6]])

Or,

>>> a.reshape((2, -1)) # unspecified (-1) value is inferred


array([[1, 2, 3],
[4, 5, 6]])

Warning: ndarray.reshape may return a view (cf help(np.reshape))), or copy

Tip:

>>> b[0, 0] = 99
>>> a
array([[99, 2, 3],
[ 4, 5, 6]])

Beware: reshape may also return a copy!:

>>> a = np.zeros((3, 2))


>>> b = a.T.reshape(3*2)
>>> b[0] = 9
>>> a
array([[0., 0.],
[0., 0.],
[0., 0.]])

To understand this you need to learn more about the memory layout of a NumPy array.

3.2. Numerical operations on arrays 78


Scientific Python Lectures, Edition 2024.2rc0.dev0

Adding a dimension

Indexing with the np.newaxis object allows us to add an axis to an array (you have seen this already
above in the broadcasting section):

>>> z = np.array([1, 2, 3])


>>> z
array([1, 2, 3])

>>> z[:, np.newaxis]


array([[1],
[2],
[3]])

>>> z[np.newaxis, :]
array([[1, 2, 3]])

Dimension shuffling

>>> a = np.arange(4*3*2).reshape(4, 3, 2)
>>> a.shape
(4, 3, 2)
>>> a[0, 2, 1]
5
>>> b = a.transpose(1, 2, 0)
>>> b.shape
(3, 2, 4)
>>> b[2, 1, 0]
5

Also creates a view:

>>> b[2, 1, 0] = -1
>>> a[0, 2, 1]
-1

Resizing

Size of an array can be changed with ndarray.resize:

>>> a = np.arange(4)
>>> a.resize((8,))
>>> a
array([0, 1, 2, 3, 0, 0, 0, 0])

However, it must not be referred to somewhere else:

>>> b = a
>>> a.resize((4,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot resize an array that references or is referenced
by another array in this way.
Use the np.resize function or refcheck=False

3.2. Numerical operations on arrays 79


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise: Shape manipulations

• Look at the docstring for reshape, especially the notes section which has some more information
about copies and views.
• Use flatten as an alternative to ravel. What is the difference? (Hint: check which one returns
a view and which a copy)
• Experiment with transpose for dimension shuffling.

3.2.5 Sorting data

Sorting along an axis:

>>> a = np.array([[4, 3, 5], [1, 2, 1]])


>>> b = np.sort(a, axis=1)
>>> b
array([[3, 4, 5],
[1, 1, 2]])

Note: Sorts each row separately!

In-place sort:

>>> a.sort(axis=1)
>>> a
array([[3, 4, 5],
[1, 1, 2]])

Sorting with fancy indexing:

>>> a = np.array([4, 3, 1, 2])


>>> j = np.argsort(a)
>>> j
array([2, 3, 1, 0])
>>> a[j]
array([1, 2, 3, 4])

Finding minima and maxima:

>>> a = np.array([4, 3, 1, 2])


>>> j_max = np.argmax(a)
>>> j_min = np.argmin(a)
>>> j_max, j_min
(0, 2)

Exercise: Sorting

• Try both in-place and out-of-place sorting.


• Try creating arrays with different dtypes and sorting them.
• Use all or array_equal to check the results.
• Look at np.random.shuffle for a way to create sortable input quicker.
• Combine ravel, sort and reshape.

3.2. Numerical operations on arrays 80


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Look at the axis keyword for sort and rewrite the previous exercise.

3.2.6 Summary

What do you need to know to get started?


• Know how to create arrays : array, arange, ones, zeros.
• Know the shape of the array with array.shape, then use slicing to obtain different views of the
array: array[::2], etc. Adjust the shape of the array using reshape or flatten it with ravel.
• Obtain a subset of the elements of an array and/or modify their values with masks

>>> a[a < 0] = 0

• Know miscellaneous operations on arrays, such as finding the mean or max (array.max(), array.
mean()). No need to retain everything, but have the reflex to search in the documentation (online
docs, help(), lookfor())!!
• For advanced use: master the indexing with arrays of integers, as well as broadcasting. Know more
NumPy functions to handle various array operations.

Quick read

If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you
can directly skip to the next chapter: Matplotlib: plotting.
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
come back and finish this chapter, as well as to do some more exercices.

3.3 More elaborate arrays

Section contents

• More data types


• Structured data types
• maskedarray: dealing with (propagation of) missing data

3.3.1 More data types

Casting

“Bigger” type wins in mixed-type operations:

>>> np.array([1, 2, 3]) + 1.5


array([2.5, 3.5, 4.5])

Assignment never changes the type!

3.3. More elaborate arrays 81


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> a = np.array([1, 2, 3])


>>> a.dtype
dtype('int64')
>>> a[0] = 1.9 # <-- float is truncated to integer
>>> a
array([1, 2, 3])

Forced casts:

>>> a = np.array([1.7, 1.2, 1.6])


>>> b = a.astype(int) # <-- truncates to integer
>>> b
array([1, 1, 1])

Rounding:

>>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5])


>>> b = np.around(a)
>>> b # still floating-point
array([1., 2., 2., 2., 4., 4.])
>>> c = np.around(a).astype(int)
>>> c
array([1, 2, 2, 2, 4, 4])

Different data type sizes

Integers (signed):

int8 8 bits
int16 16 bits
int32 32 bits (same as int on 32-bit platform)
int64 64 bits (same as int on 64-bit platform)

>>> np.array([1], dtype=int).dtype


dtype('int64')
>>> np.iinfo(np.int32).max, 2**31 - 1
(2147483647, 2147483647)

Unsigned integers:

uint8 8 bits
uint16 16 bits
uint32 32 bits
uint64 64 bits

>>> np.iinfo(np.uint32).max, 2**32 - 1


(4294967295, 4294967295)

Floating-point numbers:

3.3. More elaborate arrays 82


Scientific Python Lectures, Edition 2024.2rc0.dev0

float16 16 bits
float32 32 bits
float64 64 bits (same as float)
float96 96 bits, platform-dependent (same as np.longdouble)
float128 128 bits, platform-dependent (same as np.longdouble)

>>> np.finfo(np.float32).eps
1.1920929e-07
>>> np.finfo(np.float64).eps
2.2204460492503131e-16

>>> np.float32(1e-8) + np.float32(1) == 1


True
>>> np.float64(1e-8) + np.float64(1) == 1
False

Complex floating-point numbers:

complex64 two 32-bit floats


complex128 two 64-bit floats
complex192 two 96-bit floats, platform-dependent
complex256 two 128-bit floats, platform-dependent

Smaller data types

If you don’t know you need special data types, then you probably don’t.
Comparison on using float32 instead of float64:
• Half the size in memory and on disk
• Half the memory bandwidth required (may be a bit faster in some operations)
In [1]: a = np.zeros((int(1e6),), dtype=np.float64)

In [2]: b = np.zeros((int(1e6),), dtype=np.float32)

In [3]: %timeit a*a


268 us +- 2.15 us per loop (mean +- std. dev. of 7 runs, 1,000 loops each)

In [4]: %timeit b*b


133 us +- 138 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each)

• But: bigger rounding errors — sometimes in surprising places (i.e., don’t use them unless you
really need them)

3.3. More elaborate arrays 83


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.3.2 Structured data types

sensor_code (4-character string)


position (float)
value (float)

>>> samples = np.zeros((6,), dtype=[('sensor_code', 'S4'),


... ('position', float), ('value', float)])
>>> samples.ndim
1
>>> samples.shape
(6,)
>>> samples.dtype.names
('sensor_code', 'position', 'value')
>>> samples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13),
... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)]
>>> samples
array([(b'ALFA', 1. , 0.37), (b'BETA', 1. , 0.11), (b'TAU', 1. , 0.13),
(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11), (b'TAU', 1.2, 0.13)],
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')])

Field access works by indexing with field names:

>>> samples['sensor_code']
array([b'ALFA', b'BETA', b'TAU', b'ALFA', b'ALFA', b'TAU'], dtype='|S4')
>>> samples['value']
array([0.37, 0.11, 0.13, 0.37, 0.11, 0.13])
>>> samples[0]
(b'ALFA', 1., 0.37)

>>> samples[0]['sensor_code'] = 'TAU'


>>> samples[0]
(b'TAU', 1., 0.37)

Multiple fields at once:

>>> samples[['position', 'value']]


array([(1. , 0.37), (1. , 0.11), (1. , 0.13), (1.5, 0.37),
(3. , 0.11), (1.2, 0.13)],
dtype={'names': ['position', 'value'], 'formats': ['<f8', '<f8'], 'offsets': [4,
˓→ 12], 'itemsize': 20})

Fancy indexing works, as usual:

>>> samples[samples['sensor_code'] == b'ALFA']


array([(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11)],
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')])

Note: There are a bunch of other syntaxes for constructing structured arrays, see here and here.

3.3. More elaborate arrays 84


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.3.3 maskedarray: dealing with (propagation of) missing data

• For floats one could use NaN’s, but masks work for all types:

>>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])


>>> x
masked_array(data=[1, --, 3, --],
mask=[False, True, False, True],
fill_value=999999)

>>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1])


>>> x + y
masked_array(data=[2, --, --, --],
mask=[False, True, True, True],
fill_value=999999)

• Masking versions of common functions:

>>> np.ma.sqrt([1, -1, 2, -2])


masked_array(data=[1.0, --, 1.41421356237... --],
mask=[False, True, False, True],
fill_value=1e+20)

Note: There are other useful array siblings

While it is off topic in a chapter on NumPy, let’s take a moment to recall good coding practice, which
really do pay off in the long run:

Good practices

• Explicit variable names (no need of a comment to explain what is in the variable)
• Style: spaces after commas, around =, etc.
A certain number of rules for writing “beautiful” code (and, more importantly, using the same
conventions as everybody else!) are given in the Style Guide for Python Code and the Docstring
Conventions page (to manage help strings).
• Except some rare cases, variable names and comments in English.

3.4 Advanced operations

Section contents

• Polynomials
• Loading data files

3.4. Advanced operations 85


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.4.1 Polynomials

NumPy also contains polynomials in different bases:


For example, 3𝑥2 + 2𝑥 − 1:

>>> p = np.poly1d([3, 2, -1])


>>> p(0)
-1
>>> p.roots
array([-1. , 0.33333333])
>>> p.order
2

>>> x = np.linspace(0, 1, 20)


>>> rng = np.random.default_rng()
>>> y = np.cos(x) + 0.3*rng.random(20)
>>> p = np.poly1d(np.polyfit(x, y, 3))

>>> t = np.linspace(0, 1, 200) # use a larger number of points for smoother plotting
>>> plt.plot(x, y, 'o', t, p(t), '-')
[<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]

See https://numpy.org/doc/stable/reference/routines.polynomials.poly1d.html for more.

More polynomials (with more bases)

NumPy also has a more sophisticated polynomial interface, which supports e.g. the Chebyshev basis.
3𝑥2 + 2𝑥 − 1:

>>> p = np.polynomial.Polynomial([-1, 2, 3]) # coefs in different order!


>>> p(0)
-1.0
>>> p.roots()
array([-1. , 0.33333333])
>>> p.degree() # In general polynomials do not always expose 'order'
2

Example using polynomials in Chebyshev basis, for polynomials in range [-1, 1]:

>>> x = np.linspace(-1, 1, 2000)


>>> rng = np.random.default_rng()
(continues on next page)

3.4. Advanced operations 86


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> y = np.cos(x) + 0.3*rng.random(2000)
>>> p = np.polynomial.Chebyshev.fit(x, y, 90)

>>> plt.plot(x, y, 'r.')


[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(x, p(x), 'k-', lw=3)
[<matplotlib.lines.Line2D object at ...>]

The Chebyshev polynomials have some advantages in interpolation.

3.4.2 Loading data files

Text files

Example: populations.txt:
# year hare lynx carrot
1900 30e3 4e3 48300
1901 47.2e3 6.1e3 48200
1902 70.2e3 9.8e3 41500
1903 77.4e3 35.2e3 38200

>>> data = np.loadtxt('data/populations.txt')


>>> data
array([[ 1900., 30000., 4000., 48300.],
[ 1901., 47200., 6100., 48200.],
[ 1902., 70200., 9800., 41500.],
...

>>> np.savetxt('pop2.txt', data)


>>> data2 = np.loadtxt('pop2.txt')

Note: If you have a complicated text file, what you can try are:
• np.genfromtxt
• Using Python’s I/O functions and e.g. regexps for parsing (Python is quite well suited for this)

3.4. Advanced operations 87


Scientific Python Lectures, Edition 2024.2rc0.dev0

Reminder: Navigating the filesystem with IPython

In [1]: pwd # show current directory


Out[1]: '/tmp'

Images

Using Matplotlib:

>>> img = plt.imread('data/elephant.png')


>>> img.shape, img.dtype
((200, 300, 3), dtype('float32'))
>>> plt.imshow(img)
<matplotlib.image.AxesImage object at ...>
>>> plt.savefig('plot.png')

>>> plt.imsave('red_elephant.png', img[:,:,0], cmap=plt.cm.gray)

This saved only one channel (of RGB):

>>> plt.imshow(plt.imread('red_elephant.png'))
<matplotlib.image.AxesImage object at ...>

Other libraries:

3.4. Advanced operations 88


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> import imageio.v3 as iio


>>> iio.imwrite('tiny_elephant.png', (img[::6,::6] * 255).astype(np.uint8))
>>> plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest')
<matplotlib.image.AxesImage object at ...>

NumPy’s own format

NumPy has its own binary format, not portable but with efficient I/O:

>>> data = np.ones((3, 3))


>>> np.save('pop.npy', data)
>>> data3 = np.load('pop.npy')

Well-known (& more obscure) file formats

• HDF5: h5py, PyTables


• NetCDF: scipy.io.netcdf_file, netcdf4-python, . . .
• Matlab: scipy.io.loadmat, scipy.io.savemat
• MatrixMarket: scipy.io.mmread, scipy.io.mmwrite
• IDL: scipy.io.readsav
. . . if somebody uses it, there’s probably also a Python library for it.

Exercise: Text data files

Write a Python script that loads data from populations.txt:: and drop the last column and the first
5 rows. Save the smaller dataset to pop2.txt.

NumPy internals

If you are interested in the NumPy internals, there is a good discussion in Advanced NumPy.

3.4. Advanced operations 89


Scientific Python Lectures, Edition 2024.2rc0.dev0

3.5 Some exercises

3.5.1 Array manipulations

1. Form the 2-D array (without typing it in explicitly):

[[1, 6, 11],
[2, 7, 12],
[3, 8, 13],
[4, 9, 14],
[5, 10, 15]]

and generate a new array containing its 2nd and 4th rows.
2. Divide each column of the array:

>>> import numpy as np


>>> a = np.arange(25).reshape(5, 5)

elementwise with the array b = np.array([1., 5, 10, 15, 20]). (Hint: np.newaxis).
3. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the
number closest to 0.5.
• Use abs and argmin to find the column j closest for each row.
• Use fancy indexing to extract the numbers. (Hint: a[i,j] – the array i must contain the
row numbers corresponding to stuff in j.)

3.5.2 Picture manipulation: Framing a Face

Let’s do some manipulations on NumPy arrays by starting with an image of a raccoon. scipy provides
a 2D array of this image with the scipy.datasets.face function:

>>> import scipy as sp


>>> face = sp.datasets.face(gray=True) # 2D grayscale image

Here are a few images we will be able to obtain with our manipulations: use different colormaps, crop
the image, change some parts of the image.

• Let’s use the imshow function of matplotlib to display the image.

>>> import matplotlib.pyplot as plt


>>> face = sp.datasets.face(gray=True)
>>> plt.imshow(face)
<matplotlib.image.AxesImage object at 0x...>

• The face is displayed in false colors. A colormap must be


specified for it to be displayed in grey.

>>> plt.imshow(face, cmap=plt.cm.gray)


<matplotlib.image.AxesImage object at 0x...>

3.5. Some exercises 90


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Create an array of the image with a narrower centering


[for example,] remove 100 pixels from all the borders of the image. To check the result, display
this new array with imshow.
>>> crop_face = face[100:-100, 100:-100]

• We will now frame the face with a black locket. For this, we
need to create a mask corresponding to the pixels we want to be black. The center of the face
is around (660, 330), so we defined the mask by this condition (y-300)**2 + (x-660)**2
>>> sy, sx = face.shape
>>> y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels
>>> y.shape, x.shape
((768, 1), (1, 1024))
>>> centerx, centery = (660, 300) # center of the image
>>> mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle

then we assign the value 0 to the pixels of the image corresponding to the mask. The syntax
is extremely simple and intuitive:
>>> face[mask] = 0
>>> plt.imshow(face)
<matplotlib.image.AxesImage object at 0x...>

• Follow-up: copy all instructions of this exercise in a script called


face_locket.py then execute this script in IPython with %run face_locket.py.
Change the circle to an ellipsoid.

3.5.3 Data statistics

The data in populations.txt describes the populations of hares and lynxes (and carrots) in northern
Canada during 20 years:
>>> data = np.loadtxt('data/populations.txt')
>>> year, hares, lynxes, carrots = data.T # trick: columns to variables

>>> import matplotlib.pyplot as plt


>>> plt.axes([0.2, 0.1, 0.5, 0.8])
<Axes: >
>>> plt.plot(year, hares, year, lynxes, year, carrots)
[<matplotlib.lines.Line2D object at ...>, ...]
>>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5))
<matplotlib.legend.Legend object at ...>

3.5. Some exercises 91


Scientific Python Lectures, Edition 2024.2rc0.dev0

Computes and print, based on the data in populations.txt. . .


1. The mean and std of the populations of each species for the years in the period.
2. Which year each species had the largest population.
3. Which species has the largest population for each year. (Hint: argsort & fancy indexing of
np.array(['H', 'L', 'C']))
4. Which years any of the populations is above 50000. (Hint: comparisons and np.any)
5. The top 2 years for each species when they had the lowest populations. (Hint: argsort, fancy
indexing)
6. Compare (plot) the change in hare population (see help(np.gradient)) and the number of lynxes.
Check correlation (see help(np.corrcoef)).
. . . all without for-loops.
Solution: Python source file

3.5.4 Crude integral approximations

Write a function f(a, b, c) that returns 𝑎𝑏 −𝑐. Form a 24x12x6 array containing its values in parameter
ranges [0,1] x [0,1] x [0,1].
Approximate the 3-d integral
∫︁ 1 ∫︁ 1 ∫︁ 1
(𝑎𝑏 − 𝑐)𝑑𝑎 𝑑𝑏 𝑑𝑐
0 0 0

over this volume with the mean. The exact result is: ln 2 − 21 ≈ 0.1931 . . . — what is your relative error?
(Hints: use elementwise operations and broadcasting. You can make np.ogrid give a number of points
in given range with np.ogrid[0:1:20j].)
Reminder Python functions:

def f(a, b, c):


return some_result

Solution: Python source file

3.5.5 Mandelbrot set

Write a script that computes the Mandelbrot fractal. The Mandelbrot iteration:

3.5. Some exercises 92


Scientific Python Lectures, Edition 2024.2rc0.dev0

N_max = 50
some_threshold = 50

c = x + 1j*y

z = 0
for j in range(N_max):
z = z**2 + c

Point (x, y) belongs to the Mandelbrot set if |𝑧| < some_threshold.


Do this computation by:
1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5]
2. Do the iteration
3. Form the 2-d boolean mask indicating which points are in the set
4. Save the result to an image with:

>>> import matplotlib.pyplot as plt


>>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5])
<matplotlib.image.AxesImage object at ...>
>>> plt.gray()
>>> plt.savefig('mandelbrot.png')

Solution: Python source file

3.5.6 Markov chain

Markov chain transition matrix P, and probability distribution on the states p:


1. 0 <= P[i,j] <= 1: probability to go from state i to state j
2. Transition rule: 𝑝𝑛𝑒𝑤 = 𝑃 𝑇 𝑝𝑜𝑙𝑑
3. all(sum(P, axis=1) == 1), p.sum() == 1: normalization
Write a script that works with 5 states, and:
• Constructs a random matrix, and normalizes each row so that it is a transition matrix.
• Starts from a random (normalized) probability distribution p and takes 50 steps => p_50

3.5. Some exercises 93


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Computes the stationary distribution: the eigenvector of P.T with eigenvalue 1 (numerically: closest
to 1) => p_stationary
Remember to normalize the eigenvector — I didn’t. . .
• Checks if p_50 and p_stationary are equal to tolerance 1e-5
Toolbox: np.random, @, np.linalg.eig, reductions, abs(), argmin, comparisons, all, np.linalg.norm,
etc.
Solution: Python source file

3.6 Full code examples

3.6.1 Full code examples for the numpy chapter

1D plotting

Plot a basic 1D figure

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 3, 20)
y = np.linspace(0, 9, 20)
plt.plot(x, y)
(continues on next page)

3.6. Full code examples 94


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.plot(x, y, "o")
plt.show()

Total running time of the script: (0 minutes 0.057 seconds)

2D plotting

Plot a basic 2D figure

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng()
image = rng.random((30, 30))
plt.imshow(image, cmap=plt.cm.hot)
plt.colorbar()
plt.show()

Total running time of the script: (0 minutes 0.080 seconds)

3.6. Full code examples 95


Scientific Python Lectures, Edition 2024.2rc0.dev0

Distances exercise

Plot distances in a grid

import numpy as np
import matplotlib.pyplot as plt

x, y = np.arange(5), np.arange(5)[:, np.newaxis]


distance = np.sqrt(x**2 + y**2)
plt.pcolor(distance)
plt.colorbar()
plt.show()

Total running time of the script: (0 minutes 0.074 seconds)

3.6. Full code examples 96


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fitting to polynomial

Plot noisy data and their polynomial fit

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

x = np.linspace(0, 1, 20)
y = np.cos(x) + 0.3 * rng.random(20)
p = np.poly1d(np.polyfit(x, y, 3))

t = np.linspace(0, 1, 200)
plt.plot(x, y, "o", t, p(t), "-")
plt.show()

Total running time of the script: (0 minutes 0.056 seconds)

3.6. Full code examples 97


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fitting in Chebyshev basis

Plot noisy data and their polynomial fit in a Chebyshev basis

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

x = np.linspace(-1, 1, 2000)
y = np.cos(x) + 0.3 * rng.random(2000)
p = np.polynomial.Chebyshev.fit(x, y, 90)

plt.plot(x, y, "r.")
plt.plot(x, p(x), "k-", lw=3)
plt.show()

Total running time of the script: (0 minutes 0.085 seconds)

3.6. Full code examples 98


Scientific Python Lectures, Edition 2024.2rc0.dev0

Population exercise

Plot populations of hares, lynxes, and carrots

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt("../../../data/populations.txt")
year, hares, lynxes, carrots = data.T

plt.axes([0.2, 0.1, 0.5, 0.8])


plt.plot(year, hares, year, lynxes, year, carrots)
plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5))
plt.show()

Total running time of the script: (0 minutes 0.072 seconds)

3.6. Full code examples 99


Scientific Python Lectures, Edition 2024.2rc0.dev0

Reading and writing an elephant

Read and write images

import numpy as np
import matplotlib.pyplot as plt

original figure

plt.figure()
img = plt.imread("../../../data/elephant.png")
plt.imshow(img)

<matplotlib.image.AxesImage object at 0x7f4954da60d0>

red channel displayed in grey

plt.figure()
img_red = img[:, :, 0]
plt.imshow(img_red, cmap=plt.cm.gray)

3.6. Full code examples 100


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.image.AxesImage object at 0x7f49549dd9d0>

lower resolution

plt.figure()
img_tiny = img[::6, ::6]
plt.imshow(img_tiny, interpolation="nearest")

plt.show()

3.6. Full code examples 101


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.296 seconds)

Mandelbrot set

Compute the Mandelbrot fractal and plot it

3.6. Full code examples 102


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt
from numpy import newaxis
import warnings

def compute_mandelbrot(N_max, some_threshold, nx, ny):


# A grid of c-values
x = np.linspace(-2, 1, nx)
y = np.linspace(-1.5, 1.5, ny)

c = x[:, newaxis] + 1j * y[newaxis, :]

# Mandelbrot iteration

z = c

# The code below overflows in many regions of the x-y grid, suppress
# warnings temporarily
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for j in range(N_max):
z = z**2 + c
mandelbrot_set = abs(z) < some_threshold

return mandelbrot_set

(continues on next page)

3.6. Full code examples 103


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401)

plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5])


plt.gray()
plt.show()

Total running time of the script: (0 minutes 0.073 seconds)

Random walk exercise

Plot distance as a function of time for a random walk together with the theoretical result

import numpy as np
import matplotlib.pyplot as plt

# We create 1000 realizations with 200 steps each


n_stories = 1000
t_max = 200

t = np.arange(t_max)
# Steps can be -1 or 1 (note that randint excludes the upper limit)
rng = np.random.default_rng()
steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1

# The time evolution of the position is obtained by successively


# summing up individual steps. This is done for each of the
# realizations, i.e. along axis 1.
positions = np.cumsum(steps, axis=1)

# Determine the time evolution of the mean square distance.


sq_distance = positions**2
mean_sq_distance = np.mean(sq_distance, axis=0)

# Plot the distance d from the origin as a function of time and


# compare with the theoretically expected result where d(t)
(continues on next page)

3.6. Full code examples 104


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# grows as a square root of time t.
plt.figure(figsize=(4, 3))
plt.plot(t, np.sqrt(mean_sq_distance), "g.", t, np.sqrt(t), "y-")
plt.xlabel(r"$t$")
plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.066 seconds)

3.6. Full code examples 105


CHAPTER 4
Matplotlib: plotting

Thanks

Many thanks to Bill Wing and Christoph Deil for review and corrections.

Authors: Nicolas Rougier, Mike Müller, Gaël Varoquaux

Chapter contents

• Introduction
• Simple plot
• Figures, Subplots, Axes and Ticks
• Other Types of Plots: examples and exercises
• Beyond this tutorial
• Quick references
• Full code examples

106
Scientific Python Lectures, Edition 2024.2rc0.dev0

4.1 Introduction

Tip: Matplotlib is probably the most used Python package for 2D-graphics. It provides both a quick
way to visualize data from Python and publication-quality figures in many formats. We are going to
explore matplotlib in interactive mode covering most common cases.

4.1.1 IPython, Jupyter, and matplotlib modes

Tip: The Jupyter notebook and the IPython enhanced interactive Python, are tuned for the scientific-
computing workflow in Python, in combination with Matplotlib:

For interactive matplotlib sessions, turn on the matplotlib mode


IPython console
When using the IPython console, use:

In [1]: %matplotlib

Jupyter notebook
In the notebook, insert, at the beginning of the notebook the following magic:

%matplotlib inline

4.1.2 pyplot

Tip: pyplot provides a procedural interface to the matplotlib object-oriented plotting library. It is
modeled closely after Matlab™. Therefore, the majority of plotting commands in pyplot have Matlab™
analogs with similar arguments. Important commands are explained with interactive examples.

import matplotlib.pyplot as plt

4.2 Simple plot

Tip: In this section, we want to draw the cosine and sine functions on the same plot. Starting from
the default settings, we’ll enrich the figure step by step to make it nicer.
First step is to get the data for the sine and cosine functions:

import numpy as np

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

X is now a numpy array with 256 values ranging from −𝜋 to +𝜋 (included). C is the cosine (256 values)
and S is the sine (256 values).
To run the example, you can type them in an IPython interactive session:

4.1. Introduction 107


Scientific Python Lectures, Edition 2024.2rc0.dev0

$ ipython --matplotlib

This brings us to the IPython prompt:

IPython 0.13 -- An enhanced Interactive Python.


? -> Introduction to IPython's features.
%magic -> Information about IPython's 'magic' % functions.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

Tip: You can also download each of the examples and run it using regular python, but you will lose
interactive data manipulation:

$ python plot_exercise_1.py

You can get source for each step by clicking on the corresponding figure.

4.2.1 Plotting with default settings

Hint: Documentation
• plot tutorial
• plot() command

Tip: Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You
can control the defaults of almost every property in matplotlib: figure size and dpi, line width, color and
style, axes, axis and grid properties, text and font properties and so on.

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

plt.plot(X, C)
plt.plot(X, S)

plt.show()

4.2. Simple plot 108


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.2.2 Instantiating defaults

Hint: Documentation
• Customizing matplotlib

In the script below, we’ve instantiated (and commented) all the figure settings that influence the ap-
pearance of the plot.

Tip: The settings have been explicitly set to their default values, but now you can interactively play
with the values to explore their affect (see Line properties and Line styles below).

import numpy as np
import matplotlib.pyplot as plt

# Create a figure of size 8x6 inches, 80 dots per inch


plt.figure(figsize=(8, 6), dpi=80)

# Create a new subplot from a grid of 1x1


plt.subplot(1, 1, 1)

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

# Plot cosine with a blue continuous line of width 1 (pixels)


plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")

# Plot sine with a green continuous line of width 1 (pixels)


plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")

# Set x limits
plt.xlim(-4.0, 4.0)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

# Set y limits
plt.ylim(-1.0, 1.0)

# Set y ticks
(continues on next page)

4.2. Simple plot 109


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.yticks(np.linspace(-1, 1, 5))

# Save figure using 72 dots per inch


# plt.savefig("exercise_2.png", dpi=72)

# Show result on screen


plt.show()

4.2.3 Changing colors and line widths

Hint: Documentation
• Controlling line properties
• Line2D API

Tip: First step, we want to have the cosine in blue and the sine in red and a slightly thicker line for
both of them. We’ll also slightly alter the figure size to make it more horizontal.

...
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
...

4.2.4 Setting limits

4.2. Simple plot 110


Scientific Python Lectures, Edition 2024.2rc0.dev0

Hint: Documentation
• xlim() command
• ylim() command

Tip: Current limits of the figure are a bit too tight and we want to make some space in order to clearly
see all data points.

...
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)
...

4.2.5 Setting ticks

Hint: Documentation
• xticks() command
• yticks() command
• Tick container
• Tick locating and formatting

Tip: Current ticks are not ideal because they do not show the interesting values (±𝜋,:math:pm pi/2)
for sine and cosine. We’ll change them such that they show only these values.

...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, +1])
...

4.2. Simple plot 111


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.2.6 Setting tick labels

Hint: Documentation
• Working with text
• xticks() command
• yticks() command
• set_xticklabels()
• set_yticklabels()

Tip: Ticks are now properly placed but their label is not very explicit. We could guess that 3.142 is 𝜋
but it would be better to make it explicit. When we set tick values, we can also provide a corresponding
label in the second argument list. Note that we’ll use latex to allow for nice rendering of the label.

...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
...

4.2.7 Moving spines

Hint: Documentation
• spines API

4.2. Simple plot 112


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Axis container
• Transformations tutorial

Tip: Spines are the lines connecting the axis tick marks and noting the boundaries of the data area.
They can be placed at arbitrary positions and until now, they were on the border of the axis. We’ll change
that since we want to have them in the middle. Since there are four of them (top/bottom/left/right),
we’ll discard the top and right by setting their color to none and we’ll move the bottom and left ones to
coordinate 0 in data space coordinates.

...
ax = plt.gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
...

4.2.8 Adding a legend

Hint: Documentation
• Legend guide
• legend() command
• legend API

Tip: Let’s add a legend in the upper left corner. This only requires adding the keyword argument label
(that will be used in the legend box) to the plot commands.

...
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

(continues on next page)

4.2. Simple plot 113


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.legend(loc='upper left')
...

4.2.9 Annotate some points

Hint: Documentation
• Annotating axis
• annotate() command

Tip: Let’s annotate some interesting points using the annotate command. We chose the 2𝜋/3 value
and we want to annotate both the sine and the cosine. We’ll first draw a marker on the curve as well as
a straight dotted line. Then, we’ll use the annotate command to display some text with an arrow.

...

t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')

plt.annotate(r'$cos(\frac{2\pi}{3} )=-\frac{1} {2} $',


xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")


plt.scatter([t, ],[np.sin(t), ], 50, color='red')

plt.annotate(r'$sin(\frac{2\pi}{3} )=\frac{\sqrt{3} }{2} $',


xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
...

4.2. Simple plot 114


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.2.10 Devil is in the details

Hint: Documentation
• artist API
• set_bbox() method

Tip: The tick labels are now hardly visible because of the blue and red lines. We can make them
bigger and we can also adjust their properties such that they’ll be rendered on a semi-transparent white
background. This will allow us to see both the data and the labels.

...
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
...

4.3 Figures, Subplots, Axes and Ticks

A “figure” in matplotlib means the whole window in the user interface. Within this figure there can be
“subplots”.

Tip: So far we have used implicit figure and axes creation. This is handy for fast plots. We can have
more control over the display using figure, subplot, and axes explicitly. While subplot positions the plots
in a regular grid, axes allows free placement within the figure. Both can be useful depending on your
intention. We’ve already worked with figures and subplots without explicitly calling them. When we
call plot, matplotlib calls gca() to get the current axes and gca in turn calls gcf() to get the current
figure. If there is none it calls figure() to make one, strictly speaking, to make a subplot(111). Let’s
look at the details.

4.3. Figures, Subplots, Axes and Ticks 115


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.3.1 Figures

Tip: A figure is the windows in the GUI that has “Figure #” as title. Figures are numbered starting
from 1 as opposed to the normal Python way starting from 0. This is clearly MATLAB-style. There are
several parameters that determine what the figure looks like:

Argument Default Description


num 1 number of figure
figsize figure.figsize figure size in inches (width, height)
dpi figure.dpi resolution in dots per inch
facecolor figure.facecolor color of the drawing background
edgecolor figure.edgecolor color of edge around the drawing background
frameon True draw figure frame or not

Tip: The defaults can be specified in the resource file and will be used most of the time. Only the
number of the figure is frequently changed.
As with other objects, you can set figure properties also setp or with the set_something methods.
When you work with the GUI you can close a figure by clicking on the x in the upper right corner. But
you can close a figure programmatically by calling close. Depending on the argument it closes (1) the
current figure (no argument), (2) a specific figure (figure number or figure instance as argument), or (3)
all figures ("all" as argument).

plt.close(1) # Closes figure 1

4.3.2 Subplots

Tip: With subplot you can arrange plots in a regular grid. You need to specify the number of rows and
columns and the number of the plot. Note that the gridspec command is a more powerful alternative.

4.3. Figures, Subplots, Axes and Ticks 116


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.3.3 Axes

Axes are very similar to subplots but allow placement of plots at any location in the figure. So if we
want to put a smaller plot inside a bigger one we do so with axes.

4.3. Figures, Subplots, Axes and Ticks 117


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.3.4 Ticks

Well formatted ticks are an important part of publishing-ready figures. Matplotlib provides a totally
configurable system for ticks. There are tick locators to specify where ticks should appear and tick
formatters to give ticks the appearance you want. Major and minor ticks can be located and formatted
independently from each other. Per default minor ticks are not shown, i.e. there is only an empty list
for them because it is as NullLocator (see below).

Tick Locators

Tick locators control the positions of the ticks. They are set as follows:

ax = plt.gca()
ax.xaxis.set_major_locator(eval(locator))

There are several locators for different kind of requirements:

All of these locators derive from the base class matplotlib.ticker.Locator. You can make your own
locator deriving from it. Handling dates as ticks can be especially tricky. Therefore, matplotlib provides
special locators in matplotlib.dates.

4.4 Other Types of Plots: examples and exercises

4.4. Other Types of Plots: examples and exercises 118


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4. Other Types of Plots: examples and exercises 119


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4. Other Types of Plots: examples and exercises 120


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.1 Regular Plots

Starting from the code below, try to reproduce the graphic taking care of filled areas:

Hint: You need to use the fill_between() command.

n = 256
X = np.linspace(-np.pi, np.pi, n)
(continues on next page)

4.4. Other Types of Plots: examples and exercises 121


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Y = np.sin(2 * X)

plt.plot(X, Y + 1, color='blue', alpha=1.00)


plt.plot(X, Y - 1, color='blue', alpha=1.00)

Click on the figure for solution.

4.4.2 Scatter Plots

Starting from the code below, try to reproduce the graphic taking care of marker size, color and trans-
parency.

Hint: Color is given by angle of (X,Y).

n = 1024
rng = np.random.default_rng()
X = rng.normal(0,1,n)
Y = rng.normal(0,1,n)

plt.scatter(X,Y)

Click on figure for solution.

4.4.3 Bar Plots

Starting from the code below, try to reproduce the graphic by adding labels for red bars.

Hint: You need to take care of text alignment.

4.4. Other Types of Plots: examples and exercises 122


Scientific Python Lectures, Edition 2024.2rc0.dev0

n = 12
X = np.arange(n)
rng = np.random.default_rng()
Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)

plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')


plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')

for x, y in zip(X, Y1):


plt.text(x + 0.4, y + 0.05, '%.2f ' % y, ha='center', va='bottom')

plt.ylim(-1.25, +1.25)

Click on figure for solution.

4.4.4 Contour Plots

Starting from the code below, try to reproduce the graphic taking care of the colormap (see Colormaps
below).

Hint: You need to use the clabel() command.

def f(x, y):


return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet')


C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)

Click on figure for solution.

4.4. Other Types of Plots: examples and exercises 123


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.5 Imshow

Starting from the code below, try to reproduce the graphic taking care of colormap, image interpolation
and origin.

Hint: You need to take care of the origin of the image in the imshow command and use a colorbar()

def f(x, y):


return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)

n = 10
x = np.linspace(-3, 3, 4 * n)
y = np.linspace(-3, 3, 3 * n)
X, Y = np.meshgrid(x, y)
plt.imshow(f(X, Y))

Click on the figure for the solution.

4.4.6 Pie Charts

Starting from the code below, try to reproduce the graphic taking care of colors and slices size.

Hint: You need to modify Z.

rng = np.random.default_rng()
Z = rng.uniform(0, 1, 20)
plt.pie(Z)

Click on the figure for the solution.

4.4. Other Types of Plots: examples and exercises 124


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.7 Quiver Plots

Starting from the code below, try to reproduce the graphic taking care of colors and orientations.

Hint: You need to draw arrows twice.

n = 8
X, Y = np.mgrid[0:n, 0:n]
plt.quiver(X, Y)

Click on figure for solution.

4.4.8 Grids

Starting from the code below, try to reproduce the graphic taking care of line styles.

axes = plt.gca()
axes.set_xlim(0, 4)
axes.set_ylim(0, 3)
axes.set_xticklabels([])
axes.set_yticklabels([])

Click on figure for solution.

4.4. Other Types of Plots: examples and exercises 125


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.9 Multi Plots

Starting from the code below, try to reproduce the graphic.

Hint: You can use several subplots with different partition.

plt.subplot(2, 2, 1)
plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4)

Click on figure for solution.

4.4.10 Polar Axis

Hint: You only need to modify the axes line

Starting from the code below, try to reproduce the graphic.

plt.axes([0, 0, 1, 1])

N = 20
theta = np.arange(0., 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
radii = 10 * rng.random(N)
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)

for r, bar in zip(radii, bars):


bar.set_facecolor(plt.cm.jet(r / 10.))
bar.set_alpha(0.5)

Click on figure for solution.

4.4. Other Types of Plots: examples and exercises 126


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.11 3D Plots

Starting from the code below, try to reproduce the graphic.

Hint: You need to use contourf()

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

Click on figure for solution.

4.4.12 Text

Try to do the same from scratch !

Hint: Have a look at the matplotlib logo.

Click on figure for solution.

4.4. Other Types of Plots: examples and exercises 127


Scientific Python Lectures, Edition 2024.2rc0.dev0

Quick read

If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you
can directly skip to the next chapter: SciPy : high-level scientific computing.
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
come back and finish this chapter later.

4.5 Beyond this tutorial

Matplotlib benefits from extensive documentation as well as a large community of users and developers.
Here are some links of interest:

4.5.1 Tutorials

• Pyplot tutorial • Customizing your objects


• Introduction • Object containers
• Controlling line properties • Figure container
• Working with multiple figures and axes • Axes container
• Working with text • Axis containers
• Image tutorial • Tick containers
• Startup commands • Path tutorial
• Importing image data into NumPy arrays • Introduction
• Plotting NumPy arrays as images • Bézier example
• Text tutorial • Compound paths
• Text introduction • Transforms tutorial
• Basic text commands • Introduction
• Text properties and layout • Data coordinates
• Writing mathematical expressions • Axes coordinates
• Text rendering With LaTeX • Blended transformations
• Annotating text • Using offset transforms to create a shadow
• Artist tutorial effect
• Introduction • The transformation pipeline

4.5.2 Matplotlib documentation

• User guide • How-To


• FAQ • Troubleshooting
• Installation • Environment Variables
• Usage • Screenshots

4.5. Beyond this tutorial 128


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.5.3 Code documentation

The code is well documented and you can quickly access a specific command from within a python
session:

>>> import matplotlib.pyplot as plt


>>> help(plt.plot)
Help on function plot in module matplotlib.pyplot:

plot(*args: ...) -> 'list[Line2D]'


Plot y versus x as lines and/or markers.

Call signatures::

plot([x], y, [fmt], *, data=None, **kwargs)


plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
...

4.5.4 Galleries

The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each
example comes with its source.

4.5.5 Mailing lists

Finally, there is a user mailing list where you can ask for help and a developers mailing list that is more
technical.

4.6 Quick references

Here is a set of tables that show main properties and styles.

4.6. Quick references 129


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.6.1 Line properties

Property Description Appearance

alpha (or a) alpha transparency on 0-1


scale
antialiased True or False - use antialised
rendering

color (or c) matplotlib color arg


linestyle (or ls) see Line properties
linewidth (or lw) float, the line width in points
solid_capstyle Cap style for solid lines
solid_joinstyle Join style for solid lines
dash_capstyle Cap style for dashes
dash_joinstyle Join style for dashes
marker see Markers
markeredgewidth line width around the
(mew) marker symbol
markeredgecolor edge color if a marker is used
(mec)
markerfacecolor face color if a marker is used
(mfc)
markersize (ms) size of the marker in points

4.6.2 Line styles

4.6. Quick references 130


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.6.3 Markers

4.6.4 Colormaps

All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.
If you want to know more about colormaps, check the documentation on Colormaps in matplotlib.

4.6. Quick references 131


Scientific Python Lectures, Edition 2024.2rc0.dev0

4.7 Full code examples

4.7.1 Code samples for Matplotlib

The examples here are only examples relevant to the points raised in this chapter. The matplotlib
documentation comes with a much more exhaustive gallery.

Pie chart

A simple pie chart example with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

n = 20
Z = np.ones(n)
Z[-1] *= 2

plt.axes([0.025, 0.025, 0.95, 0.95])

plt.pie(Z, explode=Z * 0.05, colors=[f"{ i / float(n): f} " for i in range(n)])


plt.axis("equal")
plt.xticks([])
plt.yticks()

plt.show()

Total running time of the script: (0 minutes 0.050 seconds)

4.7. Full code examples 132


Scientific Python Lectures, Edition 2024.2rc0.dev0

A simple, good-looking plot

Demoing some simple features of matplotlib

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 4), dpi=72)


axes = fig.add_axes([0.01, 0.01, 0.98, 0.98])
X = np.linspace(0, 2, 200)
Y = np.sin(2 * np.pi * X)
plt.plot(X, Y, lw=2)
plt.ylim(-1.1, 1.1)
plt.grid()

plt.show()

Total running time of the script: (0 minutes 0.058 seconds)

4.7. Full code examples 133


Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting a scatter of points

A simple example showing how to plot a scatter of points with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

n = 1024
rng = np.random.default_rng()
X = rng.normal(0, 1, n)
Y = rng.normal(0, 1, n)
T = np.arctan2(Y, X)

plt.axes([0.025, 0.025, 0.95, 0.95])


plt.scatter(X, Y, s=75, c=T, alpha=0.5)

plt.xlim(-1.5, 1.5)
plt.xticks([])
plt.ylim(-1.5, 1.5)
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.058 seconds)

4.7. Full code examples 134


Scientific Python Lectures, Edition 2024.2rc0.dev0

Subplots

Show multiple subplots in matplotlib.

import matplotlib.pyplot as plt

fig = plt.figure()
fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975)

plt.subplot(2, 1, 1)
plt.xticks([]), plt.yticks([])

plt.subplot(2, 3, 4)
plt.xticks([])
plt.yticks([])

plt.subplot(2, 3, 5)
plt.xticks([])
plt.yticks([])

plt.subplot(2, 3, 6)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.042 seconds)

4.7. Full code examples 135


Scientific Python Lectures, Edition 2024.2rc0.dev0

Horizontal arrangement of subplots

An example showing horizontal arrangement of subplots with matplotlib.

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.subplot(2, 1, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5)

plt.subplot(2, 1, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5)

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.049 seconds)

4.7. Full code examples 136


Scientific Python Lectures, Edition 2024.2rc0.dev0

Subplot plot arrangement vertical

An example showing vertical arrangement of subplots with matplotlib.

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.subplot(1, 2, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5)

plt.subplot(1, 2, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5)

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.046 seconds)

4.7. Full code examples 137


Scientific Python Lectures, Edition 2024.2rc0.dev0

A simple plotting example

A plotting example with a few simple tweaks

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 4), dpi=72)


axes = fig.add_axes([0.01, 0.01, 0.98, 0.98])
x = np.linspace(0, 2, 200)
y = np.sin(2 * np.pi * x)
plt.plot(x, y, lw=0.25, c="k")
plt.xticks(np.arange(0.0, 2.0, 0.1))
plt.yticks(np.arange(-1.0, 1.0, 0.1))
plt.grid()
plt.show()

Total running time of the script: (0 minutes 0.077 seconds)

4.7. Full code examples 138


Scientific Python Lectures, Edition 2024.2rc0.dev0

Simple axes example

This example shows a couple of simple usage of axes.

import matplotlib.pyplot as plt

plt.axes([0.1, 0.1, 0.8, 0.8])


plt.xticks([])
plt.yticks([])
plt.text(
0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20,␣
˓→alpha=0.5

plt.axes([0.2, 0.2, 0.3, 0.3])


plt.xticks([])
plt.yticks([])
plt.text(
0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16,␣
˓→alpha=0.5

plt.show()

Total running time of the script: (0 minutes 0.040 seconds)

4.7. Full code examples 139


Scientific Python Lectures, Edition 2024.2rc0.dev0

3D plotting

A simple example of 3D plotting.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

ax = plt.figure().add_subplot(projection="3d")
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)


ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2, 2)

plt.show()

Total running time of the script: (0 minutes 0.125 seconds)

4.7. Full code examples 140


Scientific Python Lectures, Edition 2024.2rc0.dev0

Imshow elaborate

An example demoing imshow and styling the figure.

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):


return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 10
x = np.linspace(-3, 3, int(3.5 * n))
y = np.linspace(-3, 3, int(3.0 * n))
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

plt.axes([0.025, 0.025, 0.95, 0.95])


plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower")
plt.colorbar(shrink=0.92)

plt.xticks([])
plt.yticks([])
plt.show()

Total running time of the script: (0 minutes 0.130 seconds)

4.7. Full code examples 141


Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting a vector field: quiver

A simple example showing how to plot a vector field (quiver) with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

n = 8
X, Y = np.mgrid[0:n, 0:n]
T = np.arctan2(Y - n / 2.0, X - n / 2.0)
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)
U, V = R * np.cos(T), R * np.sin(T)

plt.axes([0.025, 0.025, 0.95, 0.95])


plt.quiver(X, Y, U, V, R, alpha=0.5)
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5)

plt.xlim(-1, n)
plt.xticks([])
plt.ylim(-1, n)
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.040 seconds)

4.7. Full code examples 142


Scientific Python Lectures, Edition 2024.2rc0.dev0

A example of plotting not quite right

An “ugly” example of plotting.

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

matplotlib.rc("grid", color="black", linestyle="-", linewidth=1)

fig = plt.figure(figsize=(5, 4), dpi=72)


axes = fig.add_axes([0.01, 0.01, 0.98, 0.98], facecolor=".75")
X = np.linspace(0, 2, 40)
Y = np.sin(2 * np.pi * X)
plt.plot(X, Y, lw=0.05, c="b", antialiased=False)

plt.xticks([])
plt.yticks(np.arange(-1.0, 1.0, 0.2))
plt.grid()
ax = plt.gca()

plt.show()

Total running time of the script: (0 minutes 0.032 seconds)

4.7. Full code examples 143


Scientific Python Lectures, Edition 2024.2rc0.dev0

Displaying the contours of a function

An example showing how to display the contours of a function with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):


return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.axes([0.025, 0.025, 0.95, 0.95])

plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)


C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5)
plt.clabel(C, inline=1, fontsize=10)

plt.xticks([])
plt.yticks([])
plt.show()

Total running time of the script: (0 minutes 0.087 seconds)

4.7. Full code examples 144


Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting in polar coordinates

A simple example showing how to plot in polar coordinates with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

ax = plt.axes([0.025, 0.025, 0.95, 0.95], polar=True)

N = 20
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
radii = 10 * rng.random(N)
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)

for r, bar in zip(radii, bars, strict=True):


bar.set_facecolor(plt.cm.jet(r / 10.0))
bar.set_alpha(0.5)

ax.set_xticklabels([])
ax.set_yticklabels([])
plt.show()

Total running time of the script: (0 minutes 0.104 seconds)

4.7. Full code examples 145


Scientific Python Lectures, Edition 2024.2rc0.dev0

Plot and filled plots

Simple example of plots and filling between them with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

n = 256
X = np.linspace(-np.pi, np.pi, n)
Y = np.sin(2 * X)

plt.axes([0.025, 0.025, 0.95, 0.95])

plt.plot(X, Y + 1, color="blue", alpha=1.00)


plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25)

plt.plot(X, Y - 1, color="blue", alpha=1.00)


plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25)
plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25)

plt.xlim(-np.pi, np.pi)
plt.xticks([])
plt.ylim(-2.5, 2.5)
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.031 seconds)

4.7. Full code examples 146


Scientific Python Lectures, Edition 2024.2rc0.dev0

Subplot grid

An example showing the subplot grid in matplotlib.

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.subplot(2, 2, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5)

plt.subplot(2, 2, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5)

plt.subplot(2, 2, 3)
plt.xticks([])
plt.yticks([])

plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5)

plt.subplot(2, 2, 4)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5)

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.075 seconds)

4.7. Full code examples 147


Scientific Python Lectures, Edition 2024.2rc0.dev0

Bar plots

An example of bar plots with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

n = 12
X = np.arange(n)
rng = np.random.default_rng()
Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)

plt.axes([0.025, 0.025, 0.95, 0.95])


plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white")
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")

for x, y in zip(X, Y1, strict=True):


plt.text(x + 0.4, y + 0.05, f"{ y: .2f} ", ha="center", va="bottom")

for x, y in zip(X, Y2, strict=True):


plt.text(x + 0.4, -y - 0.05, f"{ y: .2f} ", ha="center", va="top")

plt.xlim(-0.5, n)
plt.xticks([])
plt.ylim(-1.25, 1.25)
plt.yticks([])

plt.show()

4.7. Full code examples 148


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.050 seconds)

Axes

This example shows various axes command to position matplotlib axes.

import matplotlib.pyplot as plt

plt.axes([0.1, 0.1, 0.5, 0.5])


plt.xticks([])
plt.yticks([])
plt.text(
0.1, 0.1, "axes([0.1, 0.1, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5
)

plt.axes([0.2, 0.2, 0.5, 0.5])


plt.xticks([])
plt.yticks([])
plt.text(
0.1, 0.1, "axes([0.2, 0.2, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5
)

plt.axes([0.3, 0.3, 0.5, 0.5])


plt.xticks([])
plt.yticks([])
plt.text(
(continues on next page)

4.7. Full code examples 149


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


0.1, 0.1, "axes([0.3, 0.3, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5
)

plt.axes([0.4, 0.4, 0.5, 0.5])


plt.xticks([])
plt.yticks([])
plt.text(
0.1, 0.1, "axes([0.4, 0.4, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5
)

plt.show()

Total running time of the script: (0 minutes 0.069 seconds)

Grid

Displaying a grid on the axes in matploblib.

import matplotlib.pyplot as plt

ax = plt.axes([0.025, 0.025, 0.95, 0.95])

ax.set_xlim(0, 4)
ax.set_ylim(0, 3)
ax.xaxis.set_major_locator(plt.MultipleLocator(1.0))
(continues on next page)

4.7. Full code examples 150


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75")
ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75")
ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75")
ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75")
ax.set_xticklabels([])
ax.set_yticklabels([])

plt.show()

Total running time of the script: (0 minutes 0.089 seconds)

3D plotting

Demo 3D plotting with matplotlib and style the figure.

import matplotlib.pyplot as plt


from mpl_toolkits.mplot3d import axes3d

ax = plt.figure().add_subplot(projection="3d")
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contourf(X, Y, Z)
ax.clabel(cset, fontsize=9, inline=1)
(continues on next page)

4.7. Full code examples 151


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.xticks([])
plt.yticks([])
ax.set_zticks([])

ax.text2D(
-0.05,
1.05,
" 3D plots \n",
horizontalalignment="left",
verticalalignment="top",
bbox={"facecolor": "white", "alpha": 1.0},
family="DejaVu Sans",
size="x-large",
transform=plt.gca().transAxes,
)

ax.text2D(
-0.05,
0.975,
" Plot 2D or 3D data",
horizontalalignment="left",
verticalalignment="top",
family="DejaVu Sans",
size="medium",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.060 seconds)

GridSpec

An example demoing gridspec

4.7. Full code examples 152


Scientific Python Lectures, Edition 2024.2rc0.dev0

import matplotlib.pyplot as plt


from matplotlib import gridspec

plt.figure(figsize=(6, 4))
G = gridspec.GridSpec(3, 3)

axes_1 = plt.subplot(G[0, :])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5)

axes_2 = plt.subplot(G[1, :-1])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5)

axes_3 = plt.subplot(G[1:, -1])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5)

axes_4 = plt.subplot(G[-1, 0])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5)

axes_5 = plt.subplot(G[-1, -2])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5)

plt.tight_layout()
plt.show()

4.7. Full code examples 153


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.073 seconds)

Demo text printing

A example showing off elaborate text printing with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

eqs = []
eqs.append(
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}
˓→ {8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\

˓→delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \

˓→sigma_2}}\right]$"

)
eqs.append(
r"$\frac{d\rho}{d t} + \rho \vec{v} \cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \
˓→vec{v} + \rho \vec{g} $"

)
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")
eqs.append(r"$F_G = G\frac{m_1m_2} {r^2}$")

plt.axes([0.025, 0.025, 0.95, 0.95])


(continues on next page)

4.7. Full code examples 154


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

rng = np.random.default_rng()

for i in range(24):
index = rng.integers(0, len(eqs))
eq = eqs[index]
size = np.random.uniform(12, 32)
x, y = np.random.uniform(0, 1, 2)
alpha = np.random.uniform(0.25, 0.75)
plt.text(
x,
y,
eq,
ha="center",
va="center",
color="#11557c",
alpha=alpha,
transform=plt.gca().transAxes,
fontsize=size,
clip_on=True,
)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.503 seconds)

4.7.2 Code for the chapter’s exercises

4.7.3 Example demoing choices for an option

4.7.4 Code generating the summary figures with a title

Code for the chapter’s exercises

Exercise 1

Solution of the exercise 1 with matplotlib.

4.7. Full code examples 155


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

n = 256
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(X, S)

plt.show()

Total running time of the script: (0 minutes 0.052 seconds)

4.7. Full code examples 156


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 4

Exercise 4 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256)


S = np.sin(X)
C = np.cos(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.ylim(C.min() * 1.1, C.max() * 1.1)

plt.show()

Total running time of the script: (0 minutes 0.049 seconds)

4.7. Full code examples 157


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 3

Exercise 3 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

plt.xlim(-4.0, 4.0)
plt.xticks(np.linspace(-4, 4, 9))

plt.ylim(-1.0, 1.0)
plt.yticks(np.linspace(-1, 1, 5))

plt.show()

Total running time of the script: (0 minutes 0.043 seconds)

4.7. Full code examples 158


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 5

Exercise 5 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256)


S = np.sin(X)
C = np.cos(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi])

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, 0, +1])

plt.show()

Total running time of the script: (0 minutes 0.035 seconds)

4.7. Full code examples 159


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 6

Exercise 6 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256)


C = np.cos(X)
S = np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"])

plt.show()

Total running time of the script: (0 minutes 0.045 seconds)

4.7. Full code examples 160


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 2

Exercise 2 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8, 6), dpi=80)

# Create a new subplot from a grid of 1x1


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 1 (pixels)
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")

# Plot sine using green color with a continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")

# Set x limits
plt.xlim(-4.0, 4.0)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

(continues on next page)

4.7. Full code examples 161


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Set y limits
plt.ylim(-1.0, 1.0)

# Set y ticks
plt.yticks(np.linspace(-1, 1, 5))

# Show result on screen


plt.show()

Total running time of the script: (0 minutes 0.045 seconds)

Exercise 7

Exercise 7 with matplotlib

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)


C = np.cos(X)
S = np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

ax = plt.gca()
(continues on next page)

4.7. Full code examples 162


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"])

plt.show()

Total running time of the script: (0 minutes 0.050 seconds)

Exercise 8

Exercise 8 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)
(continues on next page)

4.7. Full code examples 163


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)


C = np.cos(X)
S = np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

ax = plt.gca()
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, +1], [r"$-1$", r"$+1$"])

plt.legend(loc="upper left")

plt.show()

Total running time of the script: (0 minutes 0.054 seconds)

Exercise 9

Exercise 9 with matplotlib.

4.7. Full code examples 164


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)


C = np.cos(X)
S = np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

ax = plt.gca()
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, +1], [r"$-1$", r"$+1$"])

t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--")
plt.scatter(
(continues on next page)

4.7. Full code examples 165


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[
t,
],
[
np.cos(t),
],
50,
color="blue",
)
plt.annotate(
r"$sin(\frac{2\pi}{3} )=\frac{\sqrt{3} }{2} $",
xy=(t, np.sin(t)),
xycoords="data",
xytext=(+10, +30),
textcoords="offset points",
fontsize=16,
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"},
)

plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--")


plt.scatter(
[
t,
],
[
np.sin(t),
],
50,
color="red",
)
plt.annotate(
r"$cos(\frac{2\pi}{3} )=-\frac{1} {2} $",
xy=(t, np.cos(t)),
xycoords="data",
xytext=(-90, -50),
textcoords="offset points",
fontsize=16,
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"},
)

plt.legend(loc="upper left")

plt.show()

Total running time of the script: (0 minutes 0.110 seconds)

4.7. Full code examples 166


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise

Exercises with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

ax = plt.gca()
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, 1], [r"$-1$", r"$+1$"])

(continues on next page)

4.7. Full code examples 167


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.legend(loc="upper left")

t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--")
plt.scatter(
[
t,
],
[
np.cos(t),
],
50,
color="blue",
)
plt.annotate(
r"$sin(\frac{2\pi}{3} )=\frac{\sqrt{3} }{2} $",
xy=(t, np.sin(t)),
xycoords="data",
xytext=(10, 30),
textcoords="offset points",
fontsize=16,
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"},
)

plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--")


plt.scatter(
[
t,
],
[
np.sin(t),
],
50,
color="red",
)
plt.annotate(
r"$cos(\frac{2\pi}{3} )=-\frac{1} {2} $",
xy=(t, np.cos(t)),
xycoords="data",
xytext=(-90, -50),
textcoords="offset points",
fontsize=16,
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"},
)

for label in ax.get_xticklabels() + ax.get_yticklabels():


label.set_fontsize(16)
label.set_bbox({"facecolor": "white", "edgecolor": "None", "alpha": 0.65})

plt.show()

Total running time of the script: (0 minutes 0.116 seconds)

4.7. Full code examples 168


Scientific Python Lectures, Edition 2024.2rc0.dev0

Example demoing choices for an option

The colors matplotlib line plots

An example demoing the various colors taken by matplotlib’s plot.

import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0.1, 1, 0.8], frameon=False)

for i in range(1, 11):


plt.plot([i, i], [0, 1], lw=1.5)

plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])
plt.show()

Total running time of the script: (0 minutes 0.013 seconds)

Linewidth

Plot various linewidth with matplotlib.

import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0.1, 1, 0.8], frameon=False)

for i in range(1, 11):


plt.plot([i, i], [0, 1], color="b", lw=i / 2.0)

plt.xlim(0, 11)
plt.ylim(0, 1)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

4.7. Full code examples 169


Scientific Python Lectures, Edition 2024.2rc0.dev0

Alpha: transparency

This example demonstrates using alpha for transparency.

import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0.1, 1, 0.8], frameon=False)

for i in range(1, 11):


plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0)

plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])
plt.show()

Total running time of the script: (0 minutes 0.016 seconds)

Aliased versus anti-aliased

This example demonstrates aliased versus anti-aliased text.

import matplotlib.pyplot as plt

size = 128, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)

plt.axes([0, 0, 1, 1], frameon=False)

plt.rcParams["text.antialiased"] = False
plt.text(0.5, 0.5, "Aliased", ha="center", va="center")

plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.010 seconds)

4.7. Full code examples 170


Scientific Python Lectures, Edition 2024.2rc0.dev0

Aliased versus anti-aliased

The example shows aliased versus anti-aliased text.

import matplotlib.pyplot as plt

size = 128, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

plt.rcParams["text.antialiased"] = True
plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center")

plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.011 seconds)

Marker size

Demo the marker size control in matplotlib.

import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

for i in range(1, 11):


plt.plot(
[
i,
],
[
1,
],
"s",
markersize=i,
markerfacecolor="w",
markeredgewidth=0.5,
markeredgecolor="k",
(continues on next page)

4.7. Full code examples 171


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


)

plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

Marker edge width

Demo the marker edge widths of matplotlib’s markers.

import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

for i in range(1, 11):


plt.plot(
[
i,
],
[
1,
],
"s",
markersize=5,
markeredgewidth=1 + i / 10.0,
markeredgecolor="k",
markerfacecolor="w",
)
plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

4.7. Full code examples 172


Scientific Python Lectures, Edition 2024.2rc0.dev0

Colormaps

An example plotting the matplotlib colormaps.

import numpy as np
import matplotlib.pyplot as plt

plt.rc("text", usetex=False)
a = np.outer(np.arange(0, 1, 0.01), np.ones(10))

plt.figure(figsize=(10, 5))
plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)
maps = [m for m in plt.cm.datad if not m.endswith("_r")]
maps.sort()
l = len(maps) + 1

for i, m in enumerate(maps):
plt.subplot(1, l, i + 1)
plt.axis("off")
plt.imshow(a, aspect="auto", cmap=plt.get_cmap(m), origin="lower")
plt.title(m, rotation=90, fontsize=10, va="bottom")

plt.show()

Total running time of the script: (0 minutes 1.352 seconds)

4.7. Full code examples 173


Scientific Python Lectures, Edition 2024.2rc0.dev0

Solid joint style

An example showing the different solid joint styles in matplotlib.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter")


plt.plot(
4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="bevel"
)
plt.plot(
8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="round"
)

plt.xlim(0, 12)
plt.ylim(-1, 2)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.012 seconds)

Solid cap style

An example demoing the solide cap style in matplotlib.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt")

plt.plot(
5 + np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="round"
)

(continues on next page)

4.7. Full code examples 174


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.plot(
10 + np.arange(4),
np.ones(4),
color="blue",
linewidth=8,
solid_capstyle="projecting",
)

plt.xlim(0, 14)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.011 seconds)

Marker edge color

Demo the marker edge color of matplotlib’s markers.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

rng = np.random.default_rng()

for i in range(1, 11):


r, g, b = np.random.uniform(0, 1, 3)
plt.plot(
[
i,
],
[
1,
],
"s",
markersize=5,
markerfacecolor="w",
markeredgewidth=1.5,
markeredgecolor=(r, g, b, 1),
)

plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])
(continues on next page)

4.7. Full code examples 175


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

Marker face color

Demo the marker face color of matplotlib’s markers.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

rng = np.random.default_rng()

for i in range(1, 11):


r, g, b = np.random.uniform(0, 1, 3)
plt.plot(
[
i,
],
[
1,
],
"s",
markersize=8,
markerfacecolor=(r, g, b, 1),
markeredgewidth=0.1,
markeredgecolor=(0, 0, 0, 0.5),
)
plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])
plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

4.7. Full code examples 176


Scientific Python Lectures, Edition 2024.2rc0.dev0

Dash capstyle

An example demoing the dash capstyle.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

plt.plot(
np.arange(4),
np.ones(4),
color="blue",
dashes=[15, 15],
linewidth=8,
dash_capstyle="butt",
)

plt.plot(
5 + np.arange(4),
np.ones(4),
color="blue",
dashes=[15, 15],
linewidth=8,
dash_capstyle="round",
)

plt.plot(
10 + np.arange(4),
np.ones(4),
color="blue",
dashes=[15, 15],
linewidth=8,
dash_capstyle="projecting",
)

plt.xlim(0, 14)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.011 seconds)

4.7. Full code examples 177


Scientific Python Lectures, Edition 2024.2rc0.dev0

Dash join style

Example demoing the dash join style.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

plt.plot(
np.arange(3),
[0, 1, 0],
color="blue",
dashes=[12, 5],
linewidth=8,
dash_joinstyle="miter",
)
plt.plot(
4 + np.arange(3),
[0, 1, 0],
color="blue",
dashes=[12, 5],
linewidth=8,
dash_joinstyle="bevel",
)
plt.plot(
8 + np.arange(3),
[0, 1, 0],
color="blue",
dashes=[12, 5],
linewidth=8,
dash_joinstyle="round",
)

plt.xlim(0, 12)
plt.ylim(-1, 2)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.012 seconds)

4.7. Full code examples 178


Scientific Python Lectures, Edition 2024.2rc0.dev0

Markers

Show the different markers of matplotlib.

import numpy as np
import matplotlib.pyplot as plt

def marker(m, i):


X = i * 0.5 * np.ones(11)
Y = np.arange(11)

plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1))


plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom")

markers = [
0,
1,
2,
3,
4,
5,
6,
7,
"o",
"h",
"_",
"1",
"2",
"3",
"4",
"8",
"p",
"^",
"v",
"<",
">",
"|",
(continues on next page)

4.7. Full code examples 179


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


"d",
",",
"+",
"s",
"*",
"|",
"x",
"D",
"H",
".",
]

n_markers = len(markers)

size = 20 * n_markers, 300


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
plt.axes([0, 0.01, 1, 0.9], frameon=False)

for i, m in enumerate(markers):
marker(m, i)

plt.xlim(-0.2, 0.2 + 0.5 * n_markers)


plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.058 seconds)

Linestyles

Plot the different line styles.

4.7. Full code examples 180


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

def linestyle(ls, i):


X = i * 0.5 * np.ones(11)
Y = np.arange(11)
plt.plot(
X,
Y,
ls,
color=(0.0, 0.0, 1, 1),
lw=3,
ms=8,
mfc=(0.75, 0.75, 1, 1),
mec=(0, 0, 1, 1),
)
plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va="bottom")

linestyles = [
"-",
"--",
":",
"-.",
".",
",",
"o",
"^",
"v",
"<",
">",
"s",
"+",
(continues on next page)

4.7. Full code examples 181


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


"x",
"d",
"1",
"2",
"3",
"4",
"h",
"p",
"|",
"_",
"D",
"H",
]
n_lines = len(linestyles)

size = 20 * n_lines, 300


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
plt.axes([0, 0.01, 1, 0.9], frameon=False)

for i, ls in enumerate(linestyles):
linestyle(ls, i)

plt.xlim(-0.2, 0.2 + 0.5 * n_lines)


plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.039 seconds)

Locators for tick on axis

An example demoing different locators to position ticks on axis for matplotlib.

4.7. Full code examples 182


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

def tickline():
plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([])
ax = plt.gca()
ax.spines["right"].set_color("none")
ax.spines["left"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("none")
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
ax.plot(np.arange(11), np.zeros(11))
return ax

locators = [
"plt.NullLocator()",
"plt.MultipleLocator(1.0)",
"plt.FixedLocator([0, 2, 8, 9, 10])",
"plt.IndexLocator(3, 1)",
"plt.LinearLocator(5)",
"plt.LogLocator(2, [1.0])",
"plt.AutoLocator()",
]

n_locators = len(locators)

size = 512, 40 * n_locators


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)

(continues on next page)

4.7. Full code examples 183


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

for i, locator in enumerate(locators):


plt.subplot(n_locators, 1, i + 1)
ax = tickline()
ax.xaxis.set_major_locator(eval(locator))
plt.text(5, 0.3, locator[3:], ha="center")

plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99)


plt.show()

Total running time of the script: (0 minutes 0.791 seconds)

Code generating the summary figures with a title

3D plotting vignette

Demo 3D plotting with matplotlib and decorate the figure.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
(continues on next page)

4.7. Full code examples 184


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)


ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2, 2)
plt.xticks([])
plt.yticks([])
ax.set_zticks([])

ax.text2D(
0.05,
0.93,
" 3D plots \n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
bbox={"facecolor": "white", "alpha": 1.0},
transform=plt.gca().transAxes,
)

ax.text2D(
0.05,
0.87,
" Plot 2D or 3D data",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.042 seconds)

Plotting in polar, decorated

An example showing how to plot in polar coordinate, and some decorations.

4.7. Full code examples 185


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

plt.subplot(1, 1, 1, polar=True)

N = 20
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
radii = 10 * rng.random(N)
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars, strict=True):
bar.set_facecolor(plt.cm.jet(r / 10.0))
bar.set_alpha(0.5)
plt.gca().set_xticklabels([])
plt.gca().set_yticklabels([])

plt.text(
-0.2,
1.02,
" Polar Axis \n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
bbox={"facecolor": "white", "alpha": 1.0},
transform=plt.gca().transAxes,
)
(continues on next page)

4.7. Full code examples 186


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.text(
-0.2,
1.01,
"\n\n Plot anything using polar axis ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.120 seconds)

Plot example vignette

An example of plots with matplotlib, and added annotations.

import numpy as np
import matplotlib.pyplot as plt

n = 256
X = np.linspace(0, 2, n)
Y = np.sin(2 * np.pi * X)
(continues on next page)

4.7. Full code examples 187


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.plot(X, Y, lw=2, color="violet")


plt.xlim(-0.2, 2.2)
plt.xticks([])
plt.ylim(-1.2, 1.2)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Regular Plot: plt.plot(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Plot lines and/or markers ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.028 seconds)

4.7. Full code examples 188


Scientific Python Lectures, Edition 2024.2rc0.dev0

Multiple plots vignette

Demo multiple plots and style the figure.

import matplotlib.pyplot as plt

ax = plt.subplot(2, 1, 1)
ax.set_xticklabels([])
ax.set_yticklabels([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.72),
width=0.66,
height=0.34,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)
(continues on next page)

4.7. Full code examples 189


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.text(
-0.05,
1.02,
" Multiplot: plt.subplot(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=ax.transAxes,
)
plt.text(
-0.05,
1.01,
"\n\n Plot several plots at once ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=ax.transAxes,
)

ax = plt.subplot(2, 2, 3)
ax.set_xticklabels([])
ax.set_yticklabels([])

ax = plt.subplot(2, 2, 4)
ax.set_xticklabels([])
ax.set_yticklabels([])

plt.show()

Total running time of the script: (0 minutes 0.090 seconds)

Boxplot with matplotlib

An example of doing box plots with matplotlib

4.7. Full code examples 190


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 5))


axes = plt.subplot(111)

n = 5
Z = np.zeros((n, 4))
X = np.linspace(0, 2, n)
rng = np.random.default_rng()
Y = rng.random((n, 4))
plt.boxplot(Y)

plt.xticks([])
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
(continues on next page)

4.7. Full code examples 191


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


)
)

plt.text(
-0.05,
1.02,
" Box Plot: plt.boxplot(...)\n ",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=axes.transAxes,
)

plt.text(
-0.04,
0.98,
"\n Make a box and whisker plot ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=axes.transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.039 seconds)

Plot scatter decorated

An example showing the scatter function, with decorations.

4.7. Full code examples 192


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

n = 1024
rng = np.random.default_rng()
X = rng.normal(0, 1, n)
Y = rng.normal(0, 1, n)

T = np.arctan2(Y, X)

plt.scatter(X, Y, s=75, c=T, alpha=0.5)


plt.xlim(-1.5, 1.5)
plt.xticks([])
plt.ylim(-1.5, 1.5)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
(continues on next page)

4.7. Full code examples 193


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Scatter Plot: plt.scatter(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Make a scatter plot of x versus y ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.059 seconds)

Pie chart vignette

Demo pie chart with matplotlib and style the figure.

4.7. Full code examples 194


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

n = 20
X = np.ones(n)
X[-1] *= 2
plt.pie(X, explode=X * 0.05, colors=[f"{ i / float(n): f} " for i in range(n)])

fig = plt.gcf()
w, h = fig.get_figwidth(), fig.get_figheight()
r = h / float(w)

plt.xlim(-1.5, 1.5)
plt.ylim(-1.5 * r, 1.5 * r)
plt.xticks([])
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
(continues on next page)

4.7. Full code examples 195


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Pie Chart: plt.pie(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Make a pie chart of an array ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.052 seconds)

Imshow demo

Demoing imshow

4.7. Full code examples 196


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):


return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 10
x = np.linspace(-3, 3, 8 * n)
y = np.linspace(-3, 3, 6 * n)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower")
plt.xticks([])
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
(continues on next page)

4.7. Full code examples 197


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Imshow: plt.imshow(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Display an image to current axes ",
horizontalalignment="left",
verticalalignment="top",
family="DejaVu Sans",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.035 seconds)

Bar plot advanced

An more elaborate bar plot example

4.7. Full code examples 198


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

n = 16
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, Y1, facecolor="#9999ff", edgecolor="white")
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")
plt.xlim(-0.5, n)
plt.xticks([])
plt.ylim(-1, 1)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
(continues on next page)

4.7. Full code examples 199


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Bar Plot: plt.bar(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Make a bar plot with rectangles ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.045 seconds)

Plotting quiver decorated

An example showing quiver with decorations.

4.7. Full code examples 200


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

n = 8
X, Y = np.mgrid[0:n, 0:n]
T = np.arctan2(Y - n / 2.0, X - n / 2.0)
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)
U, V = R * np.cos(T), R * np.sin(T)

plt.quiver(X, Y, U, V, R, alpha=0.5)
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5)

plt.xlim(-1, n)
plt.xticks([])
plt.ylim(-1, n)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
(continues on next page)

4.7. Full code examples 201


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Quiver Plot: plt.quiver(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Plot a 2-D field of arrows ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.043 seconds)

Display the contours of a function

An example demoing how to plot the contours of a function, with additional layout tweaks.

4.7. Full code examples 202


Scientific Python Lectures, Edition 2024.2rc0.dev0

/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/
˓→matplotlib/examples/pretty_plots/plot_contour_ext.py:24: UserWarning: The following␣

˓→kwargs were not used by contour: 'linewidth'

C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5)

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):


return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)


C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5)
plt.clabel(C, inline=1, fontsize=10)
plt.xticks([])
plt.yticks([])
(continues on next page)

4.7. Full code examples 203


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Contour Plot: plt.contour(..)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Draw contour lines and filled contours ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.089 seconds)

4.7. Full code examples 204


Scientific Python Lectures, Edition 2024.2rc0.dev0

Grid elaborate

An example displaying a grid on the axes and tweaking the layout.

Text(-0.05, 1.01, '\n\n Draw ticks and grid ')

import matplotlib.pyplot as plt


from matplotlib.ticker import MultipleLocator

fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white")


axes = plt.subplot(111)
axes.set_xlim(0, 4)
axes.set_ylim(0, 3)

axes.xaxis.set_major_locator(MultipleLocator(1.0))
axes.xaxis.set_minor_locator(MultipleLocator(0.1))
axes.yaxis.set_major_locator(MultipleLocator(1.0))
axes.yaxis.set_minor_locator(MultipleLocator(0.1))
axes.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75")
axes.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75")
axes.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75")
axes.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75")
axes.set_xticklabels([])
(continues on next page)

4.7. Full code examples 205


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


axes.set_yticklabels([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Grid: plt.grid(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=axes.transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Draw ticks and grid ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=axes.transAxes,
)

Total running time of the script: (0 minutes 0.089 seconds)

4.7. Full code examples 206


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text printing decorated

An example showing text printing and decorating the resulting figure.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
plt.xticks([])
plt.yticks([])

eqs = []
eqs.append(
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}
˓→ {8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\

˓→delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \

˓→sigma_2}}\right]$"

)
eqs.append(
r"$\frac{d\rho}{d t} + \rho \vec{v} \cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \
˓→vec{v} + \rho \vec{g} $"

)
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")
eqs.append(r"$F_G = G\frac{m_1m_2} {r^2}$")

rng = np.random.default_rng()

(continues on next page)

4.7. Full code examples 207


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


for i in range(24):
index = rng.integers(0, len(eqs))
eq = eqs[index]
size = rng.uniform(12, 32)
x, y = rng.uniform(0, 1, 2)
alpha = rng.uniform(0.25, 0.75)
plt.text(
x,
y,
eq,
ha="center",
va="center",
color="#11557c",
alpha=alpha,
transform=plt.gca().transAxes,
fontsize=size,
clip_on=True,
)

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Text: plt.text(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Draw any kind of text ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
(continues on next page)

4.7. Full code examples 208


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


)

plt.show()

Total running time of the script: (0 minutes 0.481 seconds)

4.7. Full code examples 209


CHAPTER 5
SciPy : high-level scientific computing

Authors: Gaël Varoquaux, Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, Ralf Gommers

Scipy

The scipy package contains various toolboxes dedicated to common issues in scientific computing.
Its different submodules correspond to different applications, such as interpolation, integration, opti-
mization, image processing, statistics, special functions, etc.

Tip: scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU
Scientific Library for C and C++), or Matlab’s toolboxes. scipy is the core package for scientific routines
in Python; it is meant to operate efficiently on numpy arrays, so that NumPy and SciPy work hand in
hand.
Before implementing a routine, it is worth checking if the desired data processing is not already imple-
mented in SciPy. As non-professional programmers, scientists often tend to re-invent the wheel, which
leads to buggy, non-optimal, difficult-to-share and unmaintainable code. By contrast, SciPy’s routines
are optimized and tested, and should therefore be used when possible.

Chapters contents

• File input/output: scipy.io


• Special functions: scipy.special
• Linear algebra operations: scipy.linalg
• Interpolation: scipy.interpolate

210
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Optimization and fit: scipy.optimize


• Statistics and random numbers: scipy.stats
• Numerical integration: scipy.integrate
• Fast Fourier transforms: scipy.fft
• Signal processing: scipy.signal
• Image manipulation: scipy.ndimage
• Summary exercises on scientific computing
• Full code examples for the SciPy chapter

Warning: This tutorial is far from an introduction to numerical computing. As enumerating the
different submodules and functions in SciPy would be very boring, we concentrate instead on a few
examples to give a general idea of how to use scipy for scientific computing.

scipy is composed of task-specific sub-modules:

scipy.cluster Vector quantization / Kmeans


scipy.constants Physical and mathematical constants
scipy.fft Fourier transform
scipy.integrate Integration routines
scipy.interpolate Interpolation
scipy.io Data input and output
scipy.linalg Linear algebra routines
scipy.ndimage n-dimensional image package
scipy.odr Orthogonal distance regression
scipy.optimize Optimization
scipy.signal Signal processing
scipy.sparse Sparse matrices
scipy.spatial Spatial data structures and algorithms
scipy.special Any special mathematical functions
scipy.stats Statistics

Tip: They all depend on numpy, but are mostly independent of each other. The standard way of
importing NumPy and these SciPy modules is:

>>> import numpy as np


>>> import scipy as sp

5.1 File input/output: scipy.io

scipy.io contains functions for loading and saving data in several common formats including Matlab,
IDL, Matrix Market, and Harwell-Boeing.
Matlab files: Loading and saving:

>>> import scipy as sp


>>> a = np.ones((3, 3))
>>> sp.io.savemat('file.mat', {'a': a}) # savemat expects a dictionary
(continues on next page)

5.1. File input/output: scipy.io 211


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> data = sp.io.loadmat('file.mat')
>>> data['a']
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

Warning: Python / Matlab mismatch: The Matlab file format does not support 1D arrays.
>>> a = np.ones(3)
>>> a
array([1., 1., 1.])
>>> a.shape
(3,)
>>> sp.io.savemat('file.mat', {'a': a})
>>> a2 = sp.io.loadmat('file.mat')['a']
>>> a2
array([[1., 1., 1.]])
>>> a2.shape
(1, 3)

Notice that the original array was a one-dimensional array, whereas the saved and reloaded array is
a two-dimensional array with a single row.
For other formats, see the scipy.io documentation.

See also:
• Load text files: numpy.loadtxt()/numpy.savetxt()
• Clever loading of text/csv files: numpy.genfromtxt()
• Fast and efficient, but NumPy-specific, binary format: numpy.save()/numpy.load()
• Basic input/output of images in Matplotlib: matplotlib.pyplot.imread()/matplotlib.pyplot.
imsave()
• More advanced input/output of images: imageio

5.2 Special functions: scipy.special

“Special” functions are functions commonly used in science and mathematics that are not considered to
be “elementary” functions. Examples include
• the gamma function, scipy.special.gamma(),
• the error function, scipy.special.erf(),
• Bessel functions, such as scipy.special.jv() (Bessel function of the first kind), and
• elliptic functions, such as scipy.special.ellipj() (Jacobi elliptic functions).
Other special functions are combinations of familiar elementary functions, but they offer better accuracy
or robustness than their naive implementations would.
Most of these function are computed elementwise and follow standard NumPy broadcasting rules when
the input arrays have different shapes. For example, scipy.special.xlog1py() is mathematically
equivalent to 𝑥 log(1 + 𝑦).

5.2. Special functions: scipy.special 212


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> import scipy as sp


>>> x = np.asarray([1, 2])
>>> y = np.asarray([[3], [4], [5]])
>>> res = sp.special.xlog1py(x, y)
>>> res.shape
(3, 2)
>>> ref = x * np.log(1 + y)
>>> np.allclose(res, ref)
True

However, scipy.special.xlog1py() is numerically favorable for small 𝑦, when explicit addition of 1


would lead to loss of precision due to floating point truncation error.

>>> x = 2.5
>>> y = 1e-18
>>> x * np.log(1 + y)
0.0
>>> sp.special.xlog1py(x, y)
2.5e-18

Many special functions also have “logarithmized” variants. For instance, the gamma function Γ(·) is
related to the factorial function by 𝑛! = Γ(𝑛 + 1), but it extends the domain from the positive integers
to the complex plane.

>>> x = np.arange(10)
>>> np.allclose(sp.special.gamma(x + 1), sp.special.factorial(x))
True
>>> sp.special.gamma(5) < sp.special.gamma(5.5) < sp.special.gamma(6)
True

The factorial function grows quickly, and so the gamma function overflows for moderate values of the
argument. However, sometimes only the logarithm of the gamma function is needed. In such cases, we
can compute the logarithm of the gamma function directly using scipy.special.gammaln().

>>> x = [5, 50, 500]


>>> np.log(sp.special.gamma(x))
array([ 3.17805383, 144.56574395, inf])
>>> sp.special.gammaln(x)
array([ 3.17805383, 144.56574395, 2605.11585036])

Such functions can often be used when the intermediate components of a calculation would overflow
or underflow, but the final result would not. For example, suppose we wish to compute the ratio
Γ(500)/Γ(499).

>>> a = sp.special.gamma(500)
>>> b = sp.special.gamma(499)
>>> a, b
(inf, inf)

Both the numerator and denominator overflow, so performing 𝑎/𝑏 will not return the result we seek.
However, the magnitude of the result should be moderate, so the use of logarithms comes to mind.
Combining the identities log(𝑎/𝑏) = log(𝑎) − log(𝑏) and exp(log(𝑥)) = 𝑥, we get:

>>> log_a = sp.special.gammaln(500)


>>> log_b = sp.special.gammaln(499)
>>> log_res = log_a - log_b
>>> res = np.exp(log_res)
(continues on next page)

5.2. Special functions: scipy.special 213


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> res
499.0000000...

Similarly, suppose we wish to compute the difference log(Γ(500) − Γ(499)). For this, we use scipy.
special.logsumexp(), which computes log(exp(𝑥)+exp(𝑦)) using a numerical trick that avoids overflow.

>>> res = sp.special.logsumexp([log_a, log_b],


... b=[1, -1]) # weights the terms of the sum
>>> res
2605.113844343...

For more information about these and many other special functions, see the documentation of scipy.
special.

5.3 Linear algebra operations: scipy.linalg

scipy.linalg provides a Python interface to efficient, compiled implementations of standard linear alge-
bra operations: the BLAS (Basic Linear Algebra Subroutines) and LAPACK (Linear Algebra PACKage)
libraries.
For example, the scipy.linalg.det() function computes the determinant of a square matrix:

>>> import scipy as sp


>>> arr = np.array([[1, 2],
... [3, 4]])
>>> sp.linalg.det(arr)
-2.0

Mathematically, the solution of a linear system 𝐴𝑥 = 𝑏 is 𝑥 = 𝐴−1 𝑏, but explicit inversion of a matrix is
numerically unstable and should be avoided. Instead, use scipy.linalg.solve():

>>> A = np.array([[1, 2],


... [2, 3]])
>>> b = np.array([14, 23])
>>> x = sp.linalg.solve(A, b)
>>> x
array([4., 5.])
>>> np.allclose(A @ x, b)
True

Linear systems with special structure can often be solved more efficiently than more general systems. For
example, systems with triangular matrices can be solved using scipy.linalg.solve_triangular():

>>> A_upper = np.triu(A)


>>> A_upper
array([[1, 2],
[0, 3]])
>>> np.allclose(sp.linalg.solve_triangular(A_upper, b, lower=False),
... sp.linalg.solve(A_upper, b))
True

scipy.linalg also features matrix factorizations/decompositions such as the singular value decomposi-
tion.

>>> A = np.array([[1, 2],


... [2, 3]])
(continues on next page)

5.3. Linear algebra operations: scipy.linalg 214


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> U, s, Vh = sp.linalg.svd(A)
>>> s # singular values
array([4.23606798, 0.23606798])

The original matrix can be recovered by matrix multiplication of the factors:

>>> S = np.diag(s) # convert to diagonal matrix before matrix multiplication


>>> A2 = U @ S @ Vh
>>> np.allclose(A2, A)
True
>>> A3 = (U * s) @ Vh # more efficient: use array math broadcasting rules!
>>> np.allclose(A3, A)
True

Many other decompositions (e.g. LU, Cholesky, QR), solvers for structured linear systems (e.g. triangu-
lar, circulant), eigenvalue problem algorithms, matrix functions (e.g. matrix exponential), and routines
for special matrix creation (e.g. block diagonal, toeplitz) are available in scipy.linalg.

5.4 Interpolation: scipy.interpolate

scipy.interpolate is used for fitting a function – an “interpolant” – to experimental or computed data.


Once fit, the interpolant can be used to approximate the underlying function at intermediate points; it
can also be used to compute the integral, derivative, or inverse of the function.
Some kinds of interpolants, known as “smoothing splines”, are designed to generate smooth curves from
noisy data. For example, suppose we have the following data:

>>> rng = np.random.default_rng(27446968)


>>> measured_time = np.linspace(0, 2*np.pi, 20)
>>> function = np.sin(measured_time)
>>> noise = rng.normal(loc=0, scale=0.1, size=20)
>>> measurements = function + noise

scipy.interpolate.make_smoothing_spline() can be used to form a curve similar to the underlying


sine function.

>>> smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time,␣


˓→measurements)

>>> interpolation_time = np.linspace(0, 2*np.pi, 200)


>>> smooth_results = smoothing_spline(interpolation_time)

5.4. Interpolation: scipy.interpolate 215


Scientific Python Lectures, Edition 2024.2rc0.dev0

On the other hand, if the data are not noisy, it may be desirable to pass exactly through each point.

>>> interp_spline = sp.interpolate.make_interp_spline(measured_time, function)


>>> interp_results = interp_spline(interpolation_time)

The derivative and antiderivative methods of the result object can be used for differentiation and
integration. For the latter, the constant of integration is assumed to be zero, but we can “wrap” the
antiderivative to include a nonzero constant of integration.

>>> d_interp_spline = interp_spline.derivative()


>>> d_interp_results = d_interp_spline(interpolation_time)
>>> i_interp_spline = lambda t: interp_spline.antiderivative()(t) - 1
>>> i_interp_results = i_interp_spline(interpolation_time)

For functions that are monotonic on an interval (e.g. sin from 𝜋/2 to 3𝜋/2), we can reverse the arguments
of make_interp_spline to interpolate the inverse function. Because the first argument is expected to
be monotonically increasing, we also reverse the order of elements in the arrays with numpy.flip().

>>> i = (measured_time > np.pi/2) & (measured_time < 3*np.pi/2)


>>> inverse_spline = sp.interpolate.make_interp_spline(np.flip(function[i]),
... np.flip(measured_time[i]))
>>> inverse_spline(0)
array(3.14159265)

See the summary exercise on Maximum wind speed prediction at the Sprogø station for a more advanced
spline interpolation example, and read the SciPy interpolation tutorial and the scipy.interpolate
documentation for much more information.

5.4. Interpolation: scipy.interpolate 216


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.5 Optimization and fit: scipy.optimize

scipy.optimize provides algorithms for root finding, curve fitting, and more general optimization.

5.5.1 Root Finding

scipy.optimize.root_scalar() attempts to find a root of a specified scalar-valued function (i.e., an


argument at which the function value is zero). Like many scipy.optimize functions, the function needs
an initial guess of the solution, which the algorithm will refine until it converges or recognizes failure.
We also provide the derivative to improve the rate of convergence.

>>> def f(x):


... return (x-1)*(x-2)
>>> def df(x):
... return 2*x - 3
>>> x0 = 0 # guess
>>> res = sp.optimize.root_scalar(f, x0=x0, fprime=df)
>>> res
converged: True
flag: converged
function_calls: 12
iterations: 6
root: 1.0
method: newton

Warning: None of the functions in scipy.optimize that accept a guess are guaranteed to converge
for all possible guesses! (For example, try x0=1.5 in the example above, where the derivative of
the function is exactly zero.) If this occurs, try a different guess, adjust the options (like providing
a bracket as shown below), or consider whether SciPy offers a more appropriate method for the
problem.

Note that only one the root at 1.0 is found. By inspection, we can tell that there is a second root at
2.0. We can direct the function toward a particular root by changing the guess or by passing a bracket
that contains only the root we seek.

>>> res = sp.optimize.root_scalar(f, bracket=(1.5, 10))


>>> res.root
2.0

For multivariate problems, use scipy.optimize.root().

>>> def f(x):


... # intersection of unit circle and line from origin
... return [x[0]**2 + x[1]**2 - 1,
... x[1] - x[0]]
>>> res = sp.optimize.root(f, x0=[0, 0])
>>> np.allclose(f(res.x), 0, atol=1e-10)
True
>>> np.allclose(res.x, np.sqrt(2)/2)
True

Over-constrained problems can be solved in the least-squares sense using scipy.optimize.root() with
method='lm' (Levenberg-Marquardt).

5.5. Optimization and fit: scipy.optimize 217


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> def f(x):


... # intersection of unit circle, line from origin, and parabola
... return [x[0]**2 + x[1]**2 - 1,
... x[1] - x[0],
... x[1] - x[0]**2]
>>> res = sp.optimize.root(f, x0=[1, 1], method='lm')
>>> res.success
True
>>> res.x
array([0.76096066, 0.66017736])

See the documentation of scipy.optimize.root_scalar() and scipy.optimize.root() for a variety


of other solution algorithms and options.

5.5.2 Curve fitting

Suppose we have data that is sinusoidal but noisy:

>>> x = np.linspace(-5, 5, num=50) # 50 values between -5 and 5


>>> noise = 0.01 * np.cos(100 * x)
>>> a, b = 2.9, 1.5
>>> y = a * np.cos(b * x) + noise

We can approximate the underlying amplitude, frequency, and phase from the data by least squares
curve fitting. To begin, we write a function that accepts the independent variable as the first argument
and all parameters to fit as separate arguments:

>>> def f(x, a, b, c):


... return a * np.sin(b * x + c)

We then use scipy.optimize.curve_fit() to find 𝑎 and 𝑏:

5.5. Optimization and fit: scipy.optimize 218


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> params, _ = sp.optimize.curve_fit(f, x, y, p0=[2, 1, 3])


>>> params
array([2.900026 , 1.50012043, 1.57079633])
>>> ref = [a, b, np.pi/2] # what we'd expect
>>> np.allclose(params, ref, rtol=1e-3)
True

Exercise: Curve fitting of temperature data

The temperature extremes in Alaska for each month, starting in January, are given by (in
degrees Celsius):
max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18
min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58

1. Plot these temperature extremes.


2. Define a function that can describe min and max temperatures. Hint: this function
has to have a period of 1 year. Hint: include a time offset.
3. Fit this function to the data with scipy.optimize.curve_fit().
4. Plot the result. Is the fit reasonable? If not, why?
5. Is the time offset for min and max temperatures the same within the fit accuracy?
solution

5.5.3 Optimization

Suppose we wish to minimize the scalar-valued function of a single variable 𝑓 (𝑥) = 𝑥2 + 10 sin(𝑥):

>>> def f(x):


... return x**2 + 10*np.sin(x)
>>> x = np.arange(-5, 5, 0.1)
>>> plt.plot(x, f(x))
[<matplotlib.lines.Line2D object at ...>]
>>> plt.show()

We can see that the function has a local minimizer near 𝑥 = 3.8 and a global minimizer near 𝑥 = −1.3,
but the precise values cannot be determined from the plot.
The most appropriate function for this purpose is scipy.optimize.minimize_scalar(). Since we know

5.5. Optimization and fit: scipy.optimize 219


Scientific Python Lectures, Edition 2024.2rc0.dev0

the approximate locations of the minima, we will provide bounds that restrict the search to the vicinity
of the global minimum.

>>> res = sp.optimize.minimize_scalar(f, bounds=(-2, -1))


>>> res
message: Solution found.
success: True
status: 0
fun: -7.9458233756...
x: -1.306440997...
nit: 8
nfev: 8
>>> res.fun == f(res.x)
True

If we did not already know the approximate location of the global minimum, we could use one of
SciPy’s global minimizers, such as scipy.optimize.differential_evolution(). We are required to
pass bounds, but they do not need to be tight.

>>> bounds=[(-5, 5)] # list of lower, upper bound for each variable
>>> res = sp.optimize.differential_evolution(f, bounds=bounds)
>>> res
message: Optimization terminated successfully.
success: True
fun: -7.9458233756...
x: [-1.306e+00]
nit: 6
nfev: 111
jac: [ 9.948e-06]

For multivariate optimization, a good choice for many problems is scipy.optimize.minimize(). Sup-
pose we wish to find the minimum of a quadratic function of two variables, 𝑓 (𝑥0 , 𝑥1 ) = (𝑥0 −1)2 +(𝑥1 −2)2 .

>>> def f(x):


... return (x[0] - 1)**2 + (x[1] - 2)**2

Like scipy.optimize.root(), scipy.optimize.minimize() requires a guess x0. (Note that this is the
initial value of both variables rather than the value of the variable we happened to label 𝑥0 .)

>>> res = sp.optimize.minimize(f, x0=[0, 0])


>>> res
message: Optimization terminated successfully.
success: True
status: 0
fun: 1.70578...e-16
x: [ 1.000e+00 2.000e+00]
nit: 2
jac: [ 3.219e-09 -8.462e-09]
hess_inv: [[ 9.000e-01 -2.000e-01]
[-2.000e-01 6.000e-01]]
nfev: 9
njev: 3

Maximization?

Is scipy.optimize.minimize() restricted to the solution of minimization problems? Nope! To solve


a maximization problem, simply minimize the negative of the original objective function.

5.5. Optimization and fit: scipy.optimize 220


Scientific Python Lectures, Edition 2024.2rc0.dev0

This barely scratches the surface of SciPy’s optimization features, which include mixed integer linear
programming, constrained nonlinear programming, and the solution of assignment problems. For much
more information, see the documentation of scipy.optimize and the advanced chapter Mathematical
optimization: finding minima of functions.

Exercise: 2-D minimization

The six-hump camelback function

𝑥4 2
𝑓 (𝑥, 𝑦) = (4 − 2.1𝑥2 + )𝑥 + 𝑥𝑦 + (4𝑦 2 − 4)𝑦 2
3
has multiple local minima. Find a global minimum (there is more than one, each with the
same value of the objective function) and at least one other local minimum.
Hints:
• Variables can be restricted to −2 < 𝑥 < 2 and −1 < 𝑦 < 1.
• numpy.meshgrid() and matplotlib.pyplot.imshow() can help with visualization.
• Try minimizing with scipy.optimize.minimize() with an initial guess of (𝑥, 𝑦) =
(0, 0). Does it find the global minimum, or converge to a local minimum? What about
other initial guesses?
• Try minimizing with scipy.optimize.differential_evolution().
solution

See the summary exercise on Non linear least squares curve fitting: application to point extraction in
topographical lidar data for another, more advanced example.

5.5. Optimization and fit: scipy.optimize 221


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.6 Statistics and random numbers: scipy.stats

scipy.stats contains fundamental tools for statistics in Python.

5.6.1 Statistical Distributions

Consider a random variable distributed according to the standard normal. We draw a sample consisting
of 100000 observations from the random variable. The normalized histogram of the sample is an estimator
of the random variable’s probability density function (PDF):

>>> dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution


>>> sample = dist.rvs(size=100000) # "random variate sample"
>>> plt.hist(sample, bins=50, density=True, label='normalized histogram')
>>> x = np.linspace(-5, 5)
>>> plt.plot(x, dist.pdf(x), label='PDF')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.legend()
<matplotlib.legend.Legend object at ...>

Distribution objects and frozen distributions

Each of the 100+ scipy.stats distribution families is represented by an object with a __call__
method. Here, we call the scipy.stats.norm object to specify its location and scale, and it returns a
frozen distribution: a particular element of a distribution family with all parameters fixed. The frozen
distribution object has methods to compute essential functions of the particular distribution.

Suppose we knew that the sample had been drawn from a distribution belonging to the family of normal
distributions, but we did not know the particular distribution’s location (mean) and scale (standard
deviation). We perform maximum likelihood estimation of the unknown parameters using the distribution
family’s fit method:

>>> loc, scale = sp.stats.norm.fit(sample)


>>> loc
0.0015767005...
(continues on next page)

5.6. Statistics and random numbers: scipy.stats 222


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> scale
0.9973396878...

Since we know the true parameters of the distribution from which the sample was drawn, we are not
surprised that these estimates are similar.

Exercise: Probability distributions

Generate 1000 random variates from a gamma distribution with a shape parameter of 1. Hint: the
shape parameter is passed as the first argument when freezing the distribution. Plot the histogram of
the sample, and overlay the distribution’s PDF. Estimate the shape parameter from the sample using
the fit method.
Extra: the distributions have many useful methods. Explore them using tab completion. Plot the
cumulative density function of the distribution, and compute the variance.

5.6.2 Sample Statistics and Hypothesis Tests

The sample mean is an estimator of the mean of the distribution from which the sample was drawn:

>>> np.mean(sample)
0.001576700508...

NumPy includes some of the most fundamental sample statistics (e.g. numpy.mean(), numpy.var(),
numpy.percentile()); scipy.stats includes many more. For instance, the geometric mean is a common
measure of central tendency for data that tends to be distributed over many orders of magnitude.

>>> sp.stats.gmean(2**sample)
1.0010934829...

SciPy also includes a variety of hypothesis tests that produce a sample statistic and a p-value. For
instance, suppose we wish to test the null hypothesis that sample was drawn from a normal distribution:

>>> res = sp.stats.normaltest(sample)


>>> res.statistic
5.20841759...
>>> res.pvalue
0.07396163283...

Here, statistic is a sample statistic that tends to be high for samples that are drawn from non-normal
distributions. pvalue is the probability of observing such a high value of the statistic for a sample
that has been drawn from a normal distribution. If the p-value is unusually small, this may be taken
as evidence that sample was not drawn from the normal distribution. Our statistic and p-value are
moderate, so the test is inconclusive.
There are many other features of scipy.stats, including circular statistics, quasi-Monte Carlo methods,
and resampling methods. For much more information, see the documentation of scipy.stats and the
advanced chapter statistics.

5.6. Statistics and random numbers: scipy.stats 223


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.7 Numerical integration: scipy.integrate

5.7.1 Quadrature
∫︀ 𝜋/2
Suppose we wish to compute the definite integral 0 sin(𝑡)𝑑𝑡 numerically. scipy.integrate.quad()
chooses one of several adaptive techniques depending on the parameters, and is therefore the recom-
mended first choice for integration of function of a single variable:

>>> integral, error_estimate = sp.integrate.quad(np.sin, 0, np.pi/2)


>>> np.allclose(integral, 1) # numerical result ~ analytical result
True
>>> abs(integral - 1) < error_estimate # actual error < estimated error
True

Other functions for numerical quadrature, including integration of multivariate functions and approxi-
mating integrals from samples, are available in scipy.integrate.

5.7.2 Initial Value Problems

scipy.integrate also features routines for integrating Ordinary Differential Equations (ODE). For
example, scipy.integrate.solve_ivp() integrates ODEs of the form:

𝑑𝑦
= 𝑓 (𝑡, 𝑦(𝑡))
𝑑𝑡
from an initial time 𝑡0 and initial state 𝑦(𝑡 = 𝑡0 ) = 𝑡0 to a final time 𝑡𝑓 or until an event occurs (e.g. a
specified state is reached).
As an introduction, consider the initial value problem given by 𝑑𝑦 𝑑𝑡 = −2𝑦 and the initial condition
𝑦(𝑡 = 0) = 1 on the interval 𝑡 = 0 . . . 4. We begin by defining a callable that computes 𝑓 (𝑡, 𝑦(𝑡)) given
the current time and state.

>>> def f(t, y):


... return -2 * y

Then, to compute y as a function of time:

>>> t_span = (0, 4) # time interval


>>> t_eval = np.linspace(*t_span) # times at which to evaluate `y`
>>> y0 = [1,] # initial state
>>> res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval)

and plot the result:

>>> plt.plot(res.t, res.y[0])


[<matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel('t')
Text(0.5, ..., 't')
>>> plt.ylabel('y')
Text(..., 0.5, 'y')
>>> plt.title('Solution of Initial Value Problem')
Text(0.5, 1.0, 'Solution of Initial Value Problem')

5.7. Numerical integration: scipy.integrate 224


Scientific Python Lectures, Edition 2024.2rc0.dev0

Let us integrate a more complex ODE: a damped spring-mass oscillator. The position of√︀ a mass attached
to a spring obeys the 2nd order ODE 𝑦¨ + 2𝜁𝜔0 𝑦˙ + 𝜔02 𝑦 = 0 with natural frequency 𝜔0 = 𝑘/𝑚, damping
ratio 𝜁 = 𝑐/(2𝑚𝜔0 ), spring constant 𝑘, mass 𝑚, and damping coefficient 𝑐.
Before using scipy.integrate.solve_ivp(), the 2nd order ODE needs to be transformed into a system
of first-order ODEs. Note that
𝑑𝑦 𝑑𝑦˙
= 𝑦˙ = 𝑦¨ = −(2𝜁𝜔0 𝑦˙ + 𝜔02 𝑦)
𝑑𝑡 𝑑𝑡
If we define 𝑧 = [𝑧0 , 𝑧1 ] where 𝑧0 = 𝑦 and 𝑧1 = 𝑦,˙ then the first order equation:
[︂ 𝑑𝑧0 ]︂ [︂ ]︂
𝑑𝑧 𝑑𝑡 𝑧1
= 𝑑𝑧1 =
𝑑𝑡 𝑑𝑡
−(2𝜁𝜔0 𝑧1 + 𝜔02 𝑧0 )

is equivalent to the original second order equation.


We set:

>>> m = 0.5 # kg
>>> k = 4 # N/m
>>> c = 0.4 # N s/m
>>> zeta = c / (2 * m * np.sqrt(k/m))
>>> omega = np.sqrt(k / m)

and define the function that computes 𝑧˙ = 𝑓 (𝑡, 𝑧(𝑡)):

>>> def f(t, z, zeta, omega):


... return (z[1], -2.0 * zeta * omega * z[1] - omega**2 * z[0])

Integration of the system follows:

>>> t_span = (0, 10)


>>> t_eval = np.linspace(*t_span, 100)
(continues on next page)

5.7. Numerical integration: scipy.integrate 225


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> z0 = [1, 0]
>>> res = sp.integrate.solve_ivp(f, t_span, z0, t_eval=t_eval,
... args=(zeta, omega), method='LSODA')

Tip: With the option method=’LSODA’, scipy.integrate.solve_ivp() uses the LSODA (Liver-
more Solver for Ordinary Differential equations with Automatic method switching for stiff and non-stiff
problems). See the ODEPACK Fortran library for more details.

See also:
Partial Differental Equations
There is no Partial Differential Equations (PDE) solver in SciPy. Some Python packages for solving
PDE’s are available, such as fipy or SfePy.

5.8 Fast Fourier transforms: scipy.fft

The scipy.fft module computes fast Fourier transforms (FFTs) and offers utilities to handle them.
Some important functions are:
• scipy.fft.fft() to compute the FFT
• scipy.fft.fftfreq() to generate the sampling frequencies
• scipy.fft.ifft() to compute the inverse FFT, from frequency space to signal space

As an illustration, a (noisy) input signal (sig), and its FFT:

>>> sig_fft = sp.fft.fft(sig)


>>> freqs = sp.fft.fftfreq(sig.size, d=time_step)

Signal FFT

As the signal comes from a real-valued function, the Fourier transform is symmetric.
The peak signal frequency can be found with freqs[power.argmax()]

5.8. Fast Fourier transforms: scipy.fft 226


Scientific Python Lectures, Edition 2024.2rc0.dev0

Setting the Fourier component above this frequency to zero and inverting the FFT with scipy.fft.
ifft(), gives a filtered signal.

Note: The code of this example can be found here

numpy.fft

NumPy also has an implementation of FFT (numpy.fft). However, the SciPy one should be preferred,
as it uses more efficient underlying implementations.

Fully worked examples:

Crude periodicity finding (link) Gaussian image blur (link)

5.8. Fast Fourier transforms: scipy.fft 227


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise: Denoise moon landing image

1. Examine the provided image moonlanding.png, which is heavily contaminated with periodic
noise. In this exercise, we aim to clean up the noise using the Fast Fourier Transform.
2. Load the image using matplotlib.pyplot.imread().
3. Find and use the 2-D FFT function in scipy.fft, and plot the spectrum (Fourier transform of)
the image. Do you have any trouble visualising the spectrum? If so, why?
4. The spectrum consists of high and low frequency components. The noise is contained in the
high-frequency part of the spectrum, so set some of those components to zero (use array slicing).
5. Apply the inverse Fourier transform to see the resulting image.
Solution

5.8. Fast Fourier transforms: scipy.fft 228


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.9 Signal processing: scipy.signal

Tip: scipy.signal is for typical signal processing: 1D, regularly-sampled signals.

Resampling scipy.signal.resample(): resample a signal to n points using FFT.

>>> t = np.linspace(0, 5, 100)


>>> x = np.sin(t)

>>> x_resampled = sp.signal.resample(x, 25)

>>> plt.plot(t, x)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(t[::4], x_resampled, 'ko')
[<matplotlib.lines.Line2D object at ...>]

Tip: Notice how on the side of the window the resampling is less accurate and has a rippling effect.
This resampling is different from the interpolation provided by scipy.interpolate as it only applies to
regularly sampled data.

Detrending scipy.signal.detrend(): remove linear trend from signal:

5.9. Signal processing: scipy.signal 229


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> t = np.linspace(0, 5, 100)


>>> rng = np.random.default_rng()
>>> x = t + rng.normal(size=100)

>>> x_detrended = sp.signal.detrend(x)

>>> plt.plot(t, x)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(t, x_detrended)
[<matplotlib.lines.Line2D object at ...>]

Filtering: For non-linear filtering, scipy.signal has filtering (median filter scipy.signal.medfilt(),
Wiener scipy.signal.wiener()), but we will discuss this in the image section.

Tip: scipy.signal also has a full-blown set of tools for the design of linear filter (finite and infinite
response filters), but this is out of the scope of this tutorial.

Spectral analysis: scipy.signal.spectrogram() compute a spectrogram –frequency spectrums over


consecutive time windows–, while scipy.signal.welch() comptes a power spectrum density (PSD).

5.9. Signal processing: scipy.signal 230


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.10 Image manipulation: scipy.ndimage

scipy.ndimage provides manipulation of n-dimensional arrays as images.

5.10.1 Geometrical transformations on images

Changing orientation, resolution, ..

>>> import scipy as sp

>>> # Load an image


>>> face = sp.datasets.face(gray=True)

>>> # Shift, rotate and zoom it


>>> shifted_face = sp.ndimage.shift(face, (50, 50))
>>> shifted_face2 = sp.ndimage.shift(face, (50, 50), mode='nearest')
>>> rotated_face = sp.ndimage.rotate(face, 30)
>>> cropped_face = face[50:-50, 50:-50]
>>> zoomed_face = sp.ndimage.zoom(face, 2)
>>> zoomed_face.shape
(1536, 2048)

>>> plt.subplot(151)
<Axes: >

>>> plt.imshow(shifted_face, cmap=plt.cm.gray)


<matplotlib.image.AxesImage object at 0x...>

>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5)

>>> # etc.

5.10.2 Image filtering

Generate a noisy face:

>>> import scipy as sp


>>> face = sp.datasets.face(gray=True)
>>> face = face[:512, -512:] # crop out square on right
>>> import numpy as np
>>> noisy_face = np.copy(face).astype(float)
>>> rng = np.random.default_rng()
>>> noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape)

Apply a variety of filters on it:

5.10. Image manipulation: scipy.ndimage 231


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)


>>> median_face = sp.ndimage.median_filter(noisy_face, size=5)
>>> wiener_face = sp.signal.wiener(noisy_face, (5, 5))

Other filters in scipy.ndimage.filters and scipy.signal can be applied to images.

Exercise

Compare histograms for the different filtered images.

5.10.3 Mathematical morphology

Tip: Mathematical morphology stems from set theory. It characterizes and transforms geometrical
structures. Binary (black and white) images, in particular, can be transformed using this theory: the
sets to be transformed are the sets of neighboring non-zero-valued pixels. The theory was also extended
to gray-valued images.

Mathematical-morphology operations use a structuring element in order to modify geometrical structures.


Let us first generate a structuring element:

>>> el = sp.ndimage.generate_binary_structure(2, 1)
>>> el
array([[False, True, False],
[...True, True, True],
[False, True, False]])
>>> el.astype(int)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])

5.10. Image manipulation: scipy.ndimage 232


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Erosion scipy.ndimage.binary_erosion()

>>> a = np.zeros((7, 7), dtype=int)


>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> sp.ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> # Erosion removes objects smaller than the structure
>>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])

• Dilation scipy.ndimage.binary_dilation()

>>> a = np.zeros((5, 5))


>>> a[2, 2] = 1
>>> a
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> sp.ndimage.binary_dilation(a).astype(a.dtype)
array([[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.]])

• Opening scipy.ndimage.binary_opening()

>>> a = np.zeros((5, 5), dtype=int)


>>> a[1:4, 1:4] = 1
>>> a[4, 4] = 1
>>> a
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 1]])
(continues on next page)

5.10. Image manipulation: scipy.ndimage 233


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> # Opening removes small objects
>>> sp.ndimage.binary_opening(a, structure=np.ones((3, 3))).astype(int)
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]])
>>> # Opening can also smooth corners
>>> sp.ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])

• Closing: scipy.ndimage.binary_closing()

Exercise

Check that opening amounts to eroding, then dilating.

An opening operation removes small structures, while a closing operation fills small holes. Such opera-
tions can therefore be used to “clean” an image.

>>> a = np.zeros((50, 50))


>>> a[10:-10, 10:-10] = 1
>>> rng = np.random.default_rng()
>>> a += 0.25 * rng.standard_normal(a.shape)
>>> mask = a>=0.5
>>> opened_mask = sp.ndimage.binary_opening(mask)
>>> closed_mask = sp.ndimage.binary_closing(opened_mask)

Exercise

Check that the area of the reconstructed square is smaller than the area of the initial
square. (The opposite would occur if the closing step was performed before the opening).

For gray-valued images, eroding (resp. dilating) amounts to replacing a pixel by the minimal (resp.
maximal) value among pixels covered by the structuring element centered on the pixel of interest.

>>> a = np.zeros((7, 7), dtype=int)


>>> a[1:6, 1:6] = 3
(continues on next page)

5.10. Image manipulation: scipy.ndimage 234


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> a[4, 4] = 2; a[2, 3] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 3, 3, 3, 3, 3, 0],
[0, 3, 3, 1, 3, 3, 0],
[0, 3, 3, 3, 3, 3, 0],
[0, 3, 3, 3, 2, 3, 0],
[0, 3, 3, 3, 3, 3, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> sp.ndimage.grey_erosion(a, size=(3, 3))
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 3, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])

5.10.4 Connected components and measurements on images

Let us first generate a nice synthetic binary image.

>>> x, y = np.indices((100, 100))


>>> sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2
>>> mask = sig > 1

scipy.ndimage.label() assigns a different label to each connected component:

5.10. Image manipulation: scipy.ndimage 235


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> labels, nb = sp.ndimage.label(mask)


>>> nb
8

Now compute measurements on each connected component:

>>> areas = sp.ndimage.sum(mask, labels, range(1, labels.max()+1))


>>> areas # The number of pixels in each connected component
array([190., 45., 424., 278., 459., 190., 549., 424.])
>>> maxima = sp.ndimage.maximum(sig, labels, range(1, labels.max()+1))
>>> maxima # The maximum signal in each connected component
array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, 6.71673619,
1.80238238, 16.76547217, 5.51954079])

Extract the 4th connected component, and crop the array around it:

>>> sp.ndimage.find_objects(labels)[3]
(slice(30, 48, None), slice(30, 48, None))
>>> sl = sp.ndimage.find_objects(labels)[3]
>>> import matplotlib.pyplot as plt
>>> plt.imshow(sig[sl])
<matplotlib.image.AxesImage object at ...>

See the summary exercise on Image processing application: counting bubbles and unmolten grains for a
more advanced example.

5.11 Summary exercises on scientific computing

The summary exercises use mainly NumPy, SciPy and Matplotlib. They provide some real-life examples
of scientific computing with Python. Now that the basics of working with NumPy and SciPy have been
introduced, the interested user is invited to try these exercises.

5.11. Summary exercises on scientific computing 236


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.11.1 Maximum wind speed prediction at the Sprogø station

The exercise goal is to predict the maximum wind speed occurring every 50 years even if no measure
exists for such a period. The available data are only measured over 21 years at the Sprogø meteorological
station located in Denmark. First, the statistical steps will be given and then illustrated with functions
from the scipy.interpolate module. At the end the interested readers are invited to compute results from
raw data and in a slightly different approach.

Statistical approach

The annual maxima are supposed to fit a normal probability density function. However such function
is not going to be estimated because it gives a probability from a wind speed maxima. Finding the
maximum wind speed occurring every 50 years requires the opposite approach, the result needs to be
found from a defined probability. That is the quantile function role and the exercise goal will be to find
it. In the current model, it is supposed that the maximum wind speed occurring every 50 years is defined
as the upper 2% quantile.
By definition, the quantile function is the inverse of the cumulative distribution function. The latter
describes the probability distribution of an annual maxima. In the exercise, the cumulative probability
p_i for a given year i is defined as p_i = i/(N+1) with N = 21, the number of measured years. Thus
it will be possible to calculate the cumulative probability of every measured wind speed maxima. From
those experimental points, the scipy.interpolate module will be very useful for fitting the quantile function.
Finally the 50 years maxima is going to be evaluated from the cumulative probability of the 2% quantile.

Computing the cumulative probabilities

The annual wind speeds maxima have already been computed and saved in the NumPy format in the
file examples/max-speeds.npy, thus they will be loaded by using NumPy:

>>> import numpy as np


>>> max_speeds = np.load('intro/scipy/summary-exercises/examples/max-speeds.npy')
>>> years_nb = max_speeds.shape[0]

Following the cumulative probability definition p_i from the previous section, the corresponding values
will be:

>>> cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1)

and they are assumed to fit the given wind speeds:

>>> sorted_max_speeds = np.sort(max_speeds)

Prediction with UnivariateSpline

In this section the quantile function will be estimated by using the UnivariateSpline class which can
represent a spline from points. The default behavior is to build a spline of degree 3 and points can
have different weights according to their reliability. Variants are InterpolatedUnivariateSpline and
LSQUnivariateSpline on which errors checking is going to change. In case a 2D spline is wanted, the
BivariateSpline class family is provided. All those classes for 1D and 2D splines use the FITPACK
Fortran subroutines, that’s why a lower library access is available through the splrep and splev functions
for respectively representing and evaluating a spline. Moreover interpolation functions without the use
of FITPACK parameters are also provided for simpler use.
For the Sprogø maxima wind speeds, the UnivariateSpline will be used because a spline of degree 3
seems to correctly fit the data:

5.11. Summary exercises on scientific computing 237


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> import scipy as sp


>>> quantile_func = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds)

The quantile function is now going to be evaluated from the full range of probabilities:

>>> nprob = np.linspace(0, 1, 100)


>>> fitted_max_speeds = quantile_func(nprob)

In the current model, the maximum wind speed occurring every 50 years is defined as the upper 2%
quantile. As a result, the cumulative probability value will be:

>>> fifty_prob = 1. - 0.02

So the storm wind speed occurring every 50 years can be guessed by:

>>> fifty_wind = quantile_func(fifty_prob)


>>> fifty_wind
array(32.97989825...)

The results are now gathered on a Matplotlib figure:

Fig. 1: Solution: Python source file

5.11. Summary exercises on scientific computing 238


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise with the Gumbell distribution

The interested readers are now invited to make an exercise by using the wind speeds measured over 21
years. The measurement period is around 90 minutes (the original period was around 10 minutes but the
file size has been reduced for making the exercise setup easier). The data are stored in NumPy format
inside the file examples/sprog-windspeeds.npy. Do not look at the source code for the plots until you
have completed the exercise.
• The first step will be to find the annual maxima by using NumPy and plot them as a matplotlib
bar figure.

Fig. 2: Solution: Python source file

• The second step will be to use the Gumbell distribution on cumulative probabilities p_i defined as
-log( -log(p_i) ) for fitting a linear quantile function (remember that you can define the degree
of the UnivariateSpline). Plotting the annual maxima versus the Gumbell distribution should
give you the following figure.
• The last step will be to find 34.23 m/s for the maximum wind speed occurring every 50 years.

5.11. Summary exercises on scientific computing 239


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fig. 3: Solution: Python source file

5.11. Summary exercises on scientific computing 240


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.11.2 Non linear least squares curve fitting: application to point extraction in
topographical lidar data

The goal of this exercise is to fit a model to some data. The data used in this tutorial are lidar data
and are described in details in the following introductory paragraph. If you’re impatient and want to
practice now, please skip it and go directly to Loading and visualization.

Introduction

Lidars systems are optical rangefinders that analyze property of scattered light to measure distances.
Most of them emit a short light impulsion towards a target and record the reflected signal. This signal
is then processed to extract the distance between the lidar system and the target.
Topographical lidar systems are such systems embedded in airborne platforms. They measure distances
between the platform and the Earth, so as to deliver information on the Earth’s topography (see1 for
more details).
In this tutorial, the goal is to analyze the waveform recorded by the lidar system2 . Such a signal
contains peaks whose center and amplitude permit to compute the position and some characteristics of
the hit target. When the footprint of the laser beam is around 1m on the Earth surface, the beam can
hit multiple targets during the two-way propagation (for example the ground and the top of a tree or
building). The sum of the contributions of each target hit by the laser beam then produces a complex
signal with multiple peaks, each one containing information about one target.
One state of the art method to extract information from these data is to decompose them in a sum of
Gaussian functions where each function represents the contribution of a target hit by the laser beam.
Therefore, we use the scipy.optimize module to fit a waveform to one or a sum of Gaussian functions.

Loading and visualization

Load the first waveform using:

>>> import numpy as np


>>> waveform_1 = np.load('intro/scipy/summary-exercises/examples/waveform_1.npy')

and visualize it:

>>> import matplotlib.pyplot as plt


>>> t = np.arange(len(waveform_1))
>>> plt.plot(t, waveform_1)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.show()

As shown below, this waveform is a 80-bin-length signal with a single peak with an amplitude of ap-
proximately 30 in the 15 nanosecond bin. Additionally, the base level of noise is approximately 3. These
values can be used in the initial solution.
1 Mallet, C. and Bretar, F. Full-Waveform Topographic Lidar: State-of-the-Art. ISPRS Journal of Photogrammetry

and Remote Sensing 64(1), pp.1-16, January 2009 http://dx.doi.org/10.1016/j.isprsjprs.2008.09.007


2 The data used for this tutorial are part of the demonstration data available for the FullAnalyze software and were

kindly provided by the GIS DRAIX.

5.11. Summary exercises on scientific computing 241


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fitting a waveform with a simple Gaussian model

The signal is very simple and can be modeled as a single Gaussian function and an offset corresponding
to the background noise. To fit the signal with the function, we must:
• define the model
• propose an initial solution
• call scipy.optimize.leastsq

Model

A Gaussian function defined by


{︃ (︂ )︂2 }︃
𝑡−𝜇
𝐵 + 𝐴 exp −
𝜎

can be defined in python by:

>>> def model(t, coeffs):


... return coeffs[0] + coeffs[1] * np.exp( - ((t-coeffs[2])/coeffs[3])**2 )

where
• coeffs[0] is 𝐵 (noise)
• coeffs[1] is 𝐴 (amplitude)
• coeffs[2] is 𝜇 (center)

5.11. Summary exercises on scientific computing 242


Scientific Python Lectures, Edition 2024.2rc0.dev0

• coeffs[3] is 𝜎 (width)

Initial solution

One possible initial solution that we determine by inspection is:

>>> x0 = np.array([3, 30, 15, 1], dtype=float)

Fit

scipy.optimize.leastsq minimizes the sum of squares of the function given as an argument. Basically,
the function to minimize is the residuals (the difference between the data and the model):

>>> def residuals(coeffs, y, t):


... return y - model(t, coeffs)

So let’s get our solution by calling scipy.optimize.leastsq() with the following arguments:
• the function to minimize
• an initial solution
• the additional arguments to pass to the function

>>> import scipy as sp


>>> t = np.arange(len(waveform_1))
>>> x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t))
>>> x
array([ 2.70363, 27.82020, 15.47924, 3.05636])

And visualize the solution:

fig, ax = plt.subplots(figsize=(8, 6))


plt.plot(t, waveform_1, t, model(t, x))
plt.xlabel("Time [ns]")
plt.ylabel("Amplitude [bins]")
plt.legend(["Waveform", "Model"])
plt.show()

Remark: from scipy v0.8 and above, you should rather use scipy.optimize.curve_fit() which takes
the model and the data as arguments, so you don’t need to define the residuals any more.

Going further

• Try with a more complex waveform (for instance waveform_2.npy) that contains three significant
peaks. You must adapt the model which is now a sum of Gaussian functions instead of only one
Gaussian peak.
• In some cases, writing an explicit function to compute the Jacobian is faster than letting leastsq
estimate it numerically. Create a function to compute the Jacobian of the residuals and use it as
an input for leastsq.
• When we want to detect very small peaks in the signal, or when the initial guess is too far from a
good solution, the result given by the algorithm is often not satisfying. Adding constraints to the
parameters of the model enables to overcome such limitations. An example of a priori knowledge
we can add is the sign of our variables (which are all positive).
• See the solution.

5.11. Summary exercises on scientific computing 243


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.11. Summary exercises on scientific computing 244


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Further exercise: compare the result of scipy.optimize.leastsq() and what you can get with
scipy.optimize.fmin_slsqp() when adding boundary constraints.

5.11.3 Image processing application: counting bubbles and unmolten grains

Statement of the problem

1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments
in the docstring of imshow to display the image with the “right” orientation (origin in the bottom
left corner, and not the upper left corner as for standard arrays).
This Scanning Element Microscopy image shows a glass sample (light gray matrix) with some
bubbles (on black) and unmolten sand grains (dark gray). We wish to determine the fraction
of the sample covered by these three phases, and to estimate the typical size of sand grains and
bubbles, their sizes, etc.
2. Crop the image to remove the lower panel with measure information.
3. Slightly filter the image with a median filter in order to refine its histogram. Check how the
histogram changes.

5.11. Summary exercises on scientific computing 245


Scientific Python Lectures, Edition 2024.2rc0.dev0

4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand
pixels, glass pixels and bubble pixels. Other option (homework): write a function that determines
automatically the thresholds from the minima of the histogram.
5. Display an image in which the three phases are colored with three different colors.
6. Use mathematical morphology to clean the different phases.
7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are
smaller than 10 pixels. To do so, use ndimage.sum or np.bincount to compute the grain sizes.
8. Compute the mean size of bubbles.

5.11.4 Example of solution for the image processing exercise: unmolten grains in
glass

1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments
in the docstring of imshow to display the image with the “right” orientation (origin in the bottom
left corner, and not the upper left corner as for standard arrays).

>>> dat = plt.imread('data/MV_HFV_012.jpg')

5.11. Summary exercises on scientific computing 246


Scientific Python Lectures, Edition 2024.2rc0.dev0

2. Crop the image to remove the lower panel with measure information.

>>> dat = dat[:-60]

3. Slightly filter the image with a median filter in order to refine its histogram. Check how the
histogram changes.

>>> filtdat = sp.ndimage.median_filter(dat, size=(7,7))


>>> hi_dat = np.histogram(dat, bins=np.arange(256))
>>> hi_filtdat = np.histogram(filtdat, bins=np.arange(256))

4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand
pixels, glass pixels and bubble pixels. Other option (homework): write a function that determines
automatically the thresholds from the minima of the histogram.

>>> void = filtdat <= 50


>>> sand = np.logical_and(filtdat > 50, filtdat <= 114)
>>> glass = filtdat > 114

5. Display an image in which the three phases are colored with three different colors.

>>> phases = void.astype(int) + 2*glass.astype(int) + 3*sand.astype(int)

5.11. Summary exercises on scientific computing 247


Scientific Python Lectures, Edition 2024.2rc0.dev0

6. Use mathematical morphology to clean the different phases.

>>> sand_op = sp.ndimage.binary_opening(sand, iterations=2)

7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are
smaller than 10 pixels. To do so, use sp.ndimage.sum or np.bincount to compute the grain sizes.

>>> sand_labels, sand_nb = sp.ndimage.label(sand_op)


>>> sand_areas = np.array(sp.ndimage.sum(sand_op, sand_labels, np.arange(sand_
˓→labels.max()+1)))

>>> mask = sand_areas > 100


>>> remove_small_sand = mask[sand_labels.ravel()].reshape(sand_labels.shape)

8. Compute the mean size of bubbles.

>>> bubbles_labels, bubbles_nb = sp.ndimage.label(void)


>>> bubbles_areas = np.bincount(bubbles_labels.ravel())[1:]
>>> mean_bubble_size = bubbles_areas.mean()
>>> median_bubble_size = np.median(bubbles_areas)
(continues on next page)

5.11. Summary exercises on scientific computing 248


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> mean_bubble_size, median_bubble_size
(1699.875, 65.0)

5.12 Full code examples for the SciPy chapter

5.12.1 Finding the minimum of a smooth function

Demos various methods to find the minimum of a function.

import numpy as np
import matplotlib.pyplot as plt

def f(x):
return x**2 + 10 * np.sin(x)

x = np.arange(-5, 5, 0.1)
plt.plot(x, f(x))

[<matplotlib.lines.Line2D object at 0x7f49548eef90>]

Now find the minimum with a few methods

5.12. Full code examples for the SciPy chapter 249


Scientific Python Lectures, Edition 2024.2rc0.dev0

import scipy as sp

# The default (Nelder Mead)


print(sp.optimize.minimize(f, x0=0))

message: Optimization terminated successfully.


success: True
status: 0
fun: -7.945823375615215
x: [-1.306e+00]
nit: 5
jac: [-1.192e-06]
hess_inv: [[ 8.589e-02]]
nfev: 12
njev: 6

plt.show()

Total running time of the script: (0 minutes 0.043 seconds)

5.12.2 Resample a signal with scipy.signal.resample

scipy.signal.resample() uses FFT to resample a 1D signal.


Generate a signal with 100 data point

import numpy as np

t = np.linspace(0, 5, 100)
x = np.sin(t)

Downsample it by a factor of 4

import scipy as sp

x_resampled = sp.signal.resample(x, 25)

Plot

import matplotlib.pyplot as plt

plt.figure(figsize=(5, 4))
plt.plot(t, x, label="Original signal")
plt.plot(t[::4], x_resampled, "ko", label="Resampled signal")

plt.legend(loc="best")
plt.show()

5.12. Full code examples for the SciPy chapter 250


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.219 seconds)

5.12.3 Detrending a signal

scipy.signal.detrend() removes a linear trend.


Generate a random signal with a trend

import numpy as np

t = np.linspace(0, 5, 100)
rng = np.random.default_rng()
x = t + rng.normal(size=100)

Detrend

import scipy as sp

x_detrended = sp.signal.detrend(x)

Plot

import matplotlib.pyplot as plt

plt.figure(figsize=(5, 4))
plt.plot(t, x, label="x")
plt.plot(t, x_detrended, label="x_detrended")
plt.legend(loc="best")
plt.show()

5.12. Full code examples for the SciPy chapter 251


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.049 seconds)

5.12.4 Integrating a simple ODE

Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition y(t=0) = 1.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

(continues on next page)

5.12. Full code examples for the SciPy chapter 252


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


def f(t, y):
return -2 * y

t_span = (0, 4) # time interval


t_eval = np.linspace(*t_span) # times at which to evaluate `y`
y0 = [
1,
] # initial state
res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval)

plt.figure(figsize=(4, 3))
plt.plot(res.t, res.y[0])
plt.xlabel("t")
plt.ylabel("y")
plt.title("Solution of Initial Value Problem")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.088 seconds)

5.12.5 Normal distribution: histogram and PDF

Explore the normal distribution: a histogram built from samples and the PDF (probability density
function).

5.12. Full code examples for the SciPy chapter 253


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution


sample = dist.rvs(size=100000) # "random variate sample"
plt.hist(
sample,
bins=51, # group the observations into 50 bins
density=True, # normalize the frequencies
label="normalized histogram",
)

x = np.linspace(-5, 5) # possible values of the random variable


plt.plot(x, dist.pdf(x), label="PDF")
plt.legend()
plt.show()

Total running time of the script: (0 minutes 0.107 seconds)

5.12.6 Integrate the Damped spring-mass oscillator

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

m = 0.5 # kg
k = 4 # N/m
c = 0.4 # N s/m

zeta = c / (2 * m * np.sqrt(k / m))


omega = np.sqrt(k / m)

def f(t, z, zeta, omega):


(continues on next page)

5.12. Full code examples for the SciPy chapter 254


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


return (z[1], -zeta * omega * z[1] - omega**2 * z[0])

t_span = (0, 10)


t_eval = np.linspace(*t_span, 100)
z0 = [1, 0]
res = sp.integrate.solve_ivp(
f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA"
)

plt.figure(figsize=(4, 3))
plt.plot(res.t, res.y[0], label="y")
plt.plot(res.t, res.y[1], label="dy/dt")
plt.legend(loc="best")
plt.show()

Total running time of the script: (0 minutes 0.056 seconds)

5.12.7 Comparing 2 sets of samples from Gaussians

import numpy as np
import matplotlib.pyplot as plt

# Generates 2 sets of observations


rng = np.random.default_rng(27446968)
samples1 = rng.normal(0, size=1000)
samples2 = rng.normal(1, size=1000)

(continues on next page)

5.12. Full code examples for the SciPy chapter 255


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Compute a histogram of the sample
bins = np.linspace(-4, 4, 30)
histogram1, bins = np.histogram(samples1, bins=bins, density=True)
histogram2, bins = np.histogram(samples2, bins=bins, density=True)

plt.figure(figsize=(6, 4))
plt.hist(samples1, bins=bins, density=True, label="Samples 1")
plt.hist(samples2, bins=bins, density=True, label="Samples 2")
plt.legend(loc="best")
plt.show()

Total running time of the script: (0 minutes 0.106 seconds)

5.12.8 Curve fitting

Demos a simple curve fitting


First generate some data

import numpy as np

# Seed the random number generator for reproducibility


rng = np.random.default_rng(27446968)

x_data = np.linspace(-5, 5, num=50)


noise = 0.01 * np.cos(100 * x_data)
a, b = 2.9, 1.5
y_data = a * np.cos(b * x_data) + noise

# And plot it
import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)

5.12. Full code examples for the SciPy chapter 256


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.collections.PathCollection object at 0x7f4954cc1850>

Now fit a simple sine function to the data

import scipy as sp

def test_func(x, a, b, c):


return a * np.sin(b * x + c)

params, params_covariance = sp.optimize.curve_fit(


test_func, x_data, y_data, p0=[2, 1, 3]
)

print(params)

[2.900026 1.50012043 1.57079633]

And plot the resulting curve on the data

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label="Data")
plt.plot(x_data, test_func(x_data, *params), label="Fitted function")

plt.legend(loc="best")

plt.show()

5.12. Full code examples for the SciPy chapter 257


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.132 seconds)

5.12.9 Spectrogram, power spectral density

Demo spectrogram and power spectral density on a frequency chirp.

import numpy as np
import matplotlib.pyplot as plt

Generate a chirp signal

# Seed the random number generator


np.random.seed(0)

time_step = 0.01
time_vec = np.arange(0, 70, time_step)

# A signal with a small frequency chirp


sig = np.sin(0.5 * np.pi * time_vec * (1 + 0.1 * time_vec))

plt.figure(figsize=(8, 5))
plt.plot(time_vec, sig)

5.12. Full code examples for the SciPy chapter 258


Scientific Python Lectures, Edition 2024.2rc0.dev0

[<matplotlib.lines.Line2D object at 0x7f4987c9d910>]

Compute and plot the spectrogram

The spectrum of the signal on consecutive time windows

import scipy as sp

freqs, times, spectrogram = sp.signal.spectrogram(sig)

plt.figure(figsize=(5, 4))
plt.imshow(spectrogram, aspect="auto", cmap="hot_r", origin="lower")
plt.title("Spectrogram")
plt.ylabel("Frequency band")
plt.xlabel("Time window")
plt.tight_layout()

5.12. Full code examples for the SciPy chapter 259


Scientific Python Lectures, Edition 2024.2rc0.dev0

Compute and plot the power spectral density (PSD)

The power of the signal per frequency band

freqs, psd = sp.signal.welch(sig)

plt.figure(figsize=(5, 4))
plt.semilogx(freqs, psd)
plt.title("PSD: power spectral density")
plt.xlabel("Frequency")
plt.ylabel("Power")
plt.tight_layout()

5.12. Full code examples for the SciPy chapter 260


Scientific Python Lectures, Edition 2024.2rc0.dev0

plt.show()

Total running time of the script: (0 minutes 0.386 seconds)

5.12.10 Demo mathematical morphology

A basic demo of binary opening and closing.

# Generate some binary data


import numpy as np

np.random.seed(0)
a = np.zeros((50, 50))
a[10:-10, 10:-10] = 1
a += 0.25 * np.random.standard_normal(a.shape)
mask = a >= 0.5

# Apply mathematical morphology


(continues on next page)

5.12. Full code examples for the SciPy chapter 261


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


import scipy as sp

opened_mask = sp.ndimage.binary_opening(mask)
closed_mask = sp.ndimage.binary_closing(opened_mask)

# Plot
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 3.5))
plt.subplot(141)
plt.imshow(a, cmap=plt.cm.gray)
plt.axis("off")
plt.title("a")

plt.subplot(142)
plt.imshow(mask, cmap=plt.cm.gray)
plt.axis("off")
plt.title("mask")

plt.subplot(143)
plt.imshow(opened_mask, cmap=plt.cm.gray)
plt.axis("off")
plt.title("opened_mask")

plt.subplot(144)
plt.imshow(closed_mask, cmap=plt.cm.gray)
plt.title("closed_mask")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)

plt.show()

Total running time of the script: (0 minutes 0.104 seconds)

5.12.11 Plot geometrical transformations on images

Demo geometrical transformations of images.

Downloading file 'face.dat' from 'https://raw.githubusercontent.com/scipy/dataset-


˓→face/main/face.dat' to '/home/runner/.cache/scipy-data'.

5.12. Full code examples for the SciPy chapter 262


Scientific Python Lectures, Edition 2024.2rc0.dev0

# Load some data


import scipy as sp

face = sp.datasets.face(gray=True)

# Apply a variety of transformations


import matplotlib.pyplot as plt

shifted_face = sp.ndimage.shift(face, (50, 50))


shifted_face2 = sp.ndimage.shift(face, (50, 50), mode="nearest")
rotated_face = sp.ndimage.rotate(face, 30)
cropped_face = face[50:-50, 50:-50]
zoomed_face = sp.ndimage.zoom(face, 2)
zoomed_face.shape

plt.figure(figsize=(15, 3))
plt.subplot(151)
plt.imshow(shifted_face, cmap=plt.cm.gray)
plt.axis("off")

plt.subplot(152)
plt.imshow(shifted_face2, cmap=plt.cm.gray)
plt.axis("off")

plt.subplot(153)
plt.imshow(rotated_face, cmap=plt.cm.gray)
plt.axis("off")

plt.subplot(154)
plt.imshow(cropped_face, cmap=plt.cm.gray)
plt.axis("off")

plt.subplot(155)
plt.imshow(zoomed_face, cmap=plt.cm.gray)
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)

plt.show()

Total running time of the script: (0 minutes 0.915 seconds)

5.12.12 Demo connected components

Extracting and labeling connected components in a 2D array

import numpy as np
import matplotlib.pyplot as plt

Generate some binary data

x, y = np.indices((100, 100))
sig = (
np.sin(2 * np.pi * x / 50.0)
* np.sin(2 * np.pi * y / 50.0)
(continues on next page)

5.12. Full code examples for the SciPy chapter 263


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


* (1 + x * y / 50.0**2) ** 2
)
mask = sig > 1

plt.figure(figsize=(7, 3.5))
plt.subplot(1, 2, 1)
plt.imshow(sig)
plt.axis("off")
plt.title("sig")

plt.subplot(1, 2, 2)
plt.imshow(mask, cmap=plt.cm.gray)
plt.axis("off")
plt.title("mask")
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)

Label connected components

import scipy as sp

labels, nb = sp.ndimage.label(mask)

plt.figure(figsize=(3.5, 3.5))
plt.imshow(labels)
plt.title("label")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)

5.12. Full code examples for the SciPy chapter 264


Scientific Python Lectures, Edition 2024.2rc0.dev0

Extract the 4th connected component, and crop the array around it

sl = sp.ndimage.find_objects(labels == 4)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(sig[sl[0]])
plt.title("Cropped connected component")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)

plt.show()

Total running time of the script: (0 minutes 0.129 seconds)

5.12. Full code examples for the SciPy chapter 265


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.12.13 Minima and roots of a function

Demos finding minima and roots of a function.

Define the function

import numpy as np

x = np.arange(-10, 10, 0.1)

def f(x):
return x**2 + 10 * np.sin(x)

Find minima

import scipy as sp

# Global optimization
grid = (-10, 10, 0.1)
xmin_global = sp.optimize.brute(f, (grid,))
print(f"Global minima found { xmin_global} ")

# Constrain optimization
xmin_local = sp.optimize.fminbound(f, 0, 10)
print(f"Local minimum found { xmin_local} ")

Global minima found [-1.30641113]


Local minimum found 3.8374671194983834

Root finding

root = sp.optimize.root(f, 1) # our initial guess is 1


print(f"First root found { root.x} ")
root2 = sp.optimize.root(f, -2.5)
print(f"Second root found { root2.x} ")

First root found [0.]


Second root found [-2.47948183]

Plot function, minima, and roots

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 4))


ax = fig.add_subplot(111)

# Plot the function


ax.plot(x, f(x), "b-", label="f(x)")

# Plot the minima


(continues on next page)

5.12. Full code examples for the SciPy chapter 266


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


xmins = np.array([xmin_global[0], xmin_local])
ax.plot(xmins, f(xmins), "go", label="Minima")

# Plot the roots


roots = np.array([root.x, root2.x])
ax.plot(roots, f(roots), "kv", label="Roots")

# Decorate the figure


ax.legend(loc="best")
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
ax.axhline(0, color="gray")
plt.show()

Total running time of the script: (0 minutes 0.079 seconds)

5.12. Full code examples for the SciPy chapter 267


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.12.14 Plot filtering on images

Demo filtering for denoising of images.

# Load some data


import scipy as sp

face = sp.datasets.face(gray=True)
face = face[:512, -512:] # crop out square on right

# Apply a variety of filters


import matplotlib.pyplot as plt

import numpy as np

noisy_face = np.copy(face).astype(float)
rng = np.random.default_rng()
noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape)
blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)
median_face = sp.ndimage.median_filter(noisy_face, size=5)
wiener_face = sp.signal.wiener(noisy_face, (5, 5))

plt.figure(figsize=(12, 3.5))
plt.subplot(141)
plt.imshow(noisy_face, cmap=plt.cm.gray)
plt.axis("off")
plt.title("noisy")

plt.subplot(142)
plt.imshow(blurred_face, cmap=plt.cm.gray)
plt.axis("off")
plt.title("Gaussian filter")

plt.subplot(143)
plt.imshow(median_face, cmap=plt.cm.gray)
plt.axis("off")
plt.title("median filter")

plt.subplot(144)
plt.imshow(wiener_face, cmap=plt.cm.gray)
plt.title("Wiener filter")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)

plt.show()

5.12. Full code examples for the SciPy chapter 268


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.478 seconds)

5.12.15 Optimization of a two-parameter function

import numpy as np

# Define the function that we are interested in


def sixhump(x):
return (
(4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2
+ x[0] * x[1]
+ (-4 + 4 * x[1] ** 2) * x[1] ** 2
)

# Make a grid to evaluate the function (for plotting)


xlim = [-2, 2]
ylim = [-1, 1]
x = np.linspace(*xlim)
y = np.linspace(*ylim)
xg, yg = np.meshgrid(x, y)

A 2D image plot of the function

Simple visualization in 2D

import matplotlib.pyplot as plt

plt.figure()
plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower")
plt.colorbar()

5.12. Full code examples for the SciPy chapter 269


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.colorbar.Colorbar object at 0x7f4955d7e150>

A 3D surface plot of the function

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
surf = ax.plot_surface(
xg,
yg,
sixhump([xg, yg]),
rstride=1,
cstride=1,
cmap=plt.cm.viridis,
linewidth=0,
antialiased=False,
)

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("f(x, y)")
ax.set_title("Six-hump Camelback function")

5.12. Full code examples for the SciPy chapter 270


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 1.0, 'Six-hump Camelback function')

Find minima

import scipy as sp

# local minimization
res_local = sp.optimize.minimize(sixhump, x0=[0, 0])

# global minimization
res_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim])

plt.figure()
# Show the function in 2D
plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower")
plt.colorbar()
# Mark the minima
plt.scatter(res_local.x[0], res_local.x[1], label="local minimizer")
plt.scatter(res_global.x[0], res_global.x[1], label="global minimizer")
plt.legend()
plt.show()

5.12. Full code examples for the SciPy chapter 271


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.386 seconds)

5.12.16 Plotting and manipulating FFTs for filtering

Plot the power of the FFT of a signal and inverse FFT back to reconstruct a signal.
This example demonstrate scipy.fft.fft(), scipy.fft.fftfreq() and scipy.fft.ifft(). It imple-
ments a basic filter that is very suboptimal, and should not be used.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

Generate the signal

# Seed the random number generator


rng = np.random.default_rng(27446968)

time_step = 0.02
period = 5.0

time_vec = np.arange(0, 20, time_step)


sig = np.sin(2 * np.pi / period * time_vec) + 0.5 * rng.normal(size=time_vec.size)

plt.figure(figsize=(6, 5))
plt.plot(time_vec, sig, label="Original signal")

5.12. Full code examples for the SciPy chapter 272


Scientific Python Lectures, Edition 2024.2rc0.dev0

[<matplotlib.lines.Line2D object at 0x7f495545e850>]

Compute and plot the power

# The FFT of the signal


sig_fft = sp.fft.fft(sig)

# And the power (sig_fft is of complex dtype)


power = np.abs(sig_fft) ** 2

# The corresponding frequencies


sample_freq = sp.fft.fftfreq(sig.size, d=time_step)

# Plot the FFT power


plt.figure(figsize=(6, 5))
plt.plot(sample_freq, power)
plt.xlabel("Frequency [Hz]")
plt.ylabel("plower")

# Find the peak frequency: we can focus on only the positive frequencies
pos_mask = np.where(sample_freq > 0)
freqs = sample_freq[pos_mask]
peak_freq = freqs[power[pos_mask].argmax()]

# Check that it does indeed correspond to the frequency that we generate


(continues on next page)

5.12. Full code examples for the SciPy chapter 273


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# the signal with
np.allclose(peak_freq, 1.0 / period)

# An inner plot to show the peak frequency


axes = plt.axes([0.55, 0.3, 0.3, 0.5])
plt.title("Peak frequency")
plt.plot(freqs[:8], power[pos_mask][:8])
plt.setp(axes, yticks=[])

# scipy.signal.find_peaks_cwt can also be used for more advanced


# peak detection

[]

Remove all the high frequencies

We now remove all the high frequencies and transform back from frequencies to signal.

high_freq_fft = sig_fft.copy()
high_freq_fft[np.abs(sample_freq) > peak_freq] = 0
filtered_sig = sp.fft.ifft(high_freq_fft)

plt.figure(figsize=(6, 5))
plt.plot(time_vec, sig, label="Original signal")
(continues on next page)

5.12. Full code examples for the SciPy chapter 274


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.plot(time_vec, filtered_sig, linewidth=3, label="Filtered signal")
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")

plt.legend(loc="best")

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/matplotlib/cbook.
˓→py:1762: ComplexWarning: Casting complex values to real discards the imaginary part

return math.isfinite(val)
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/matplotlib/cbook.
˓→py:1398: ComplexWarning: Casting complex values to real discards the imaginary part

return np.asarray(x, float)

<matplotlib.legend.Legend object at 0x7f4955411bd0>

Note This is actually a bad way of creating a filter: such brutal cut-off in frequency space does not
control distortion on the signal.
Filters should be created using the SciPy filter design code

plt.show()

Total running time of the script: (0 minutes 0.243 seconds)

5.12. Full code examples for the SciPy chapter 275


Scientific Python Lectures, Edition 2024.2rc0.dev0

5.12.17 A demo of 1D interpolation

5.12. Full code examples for the SciPy chapter 276


Scientific Python Lectures, Edition 2024.2rc0.dev0


# Generate data
import numpy as np

rng = np.random.default_rng(27446968)
measured_time = np.linspace(0, 2 * np.pi, 20)
function = np.sin(measured_time)
noise = rng.normal(loc=0, scale=0.1, size=20)
measurements = function + noise

# Smooth the curve and interpolate at new times


import scipy as sp

smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements)


interpolation_time = np.linspace(0, 2 * np.pi, 200)
smooth_results = smoothing_spline(interpolation_time)

# Plot the data, the interpolant, and the original function


import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.plot(measured_time, measurements, ".", ms=6, label="measurements")
plt.plot(interpolation_time, smooth_results, label="smoothing spline")
plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve
˓→")

plt.legend()
plt.show()

# Fit the data exactly


interp_spline = sp.interpolate.make_interp_spline(measured_time, function)
interp_results = interp_spline(interpolation_time)

# Plot the data, the interpolant, and the original function


plt.figure(figsize=(6, 4))
(continues on next page)

5.12. Full code examples for the SciPy chapter 277


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.plot(measured_time, function, ".", ms=6, label="measurements")
plt.plot(interpolation_time, interp_results, label="interpolating spline")
plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve
˓→")

plt.legend()
plt.show()

# Plot interpolant, its derivative, and its antiderivative


plt.figure(figsize=(6, 4))
t = interpolation_time
plt.plot(t, interp_spline(t), label="spline")
plt.plot(t, interp_spline.derivative()(t), label="derivative")
plt.plot(t, interp_spline.antiderivative()(t) - 1, label="antiderivative")

plt.legend()
plt.show()

Total running time of the script: (0 minutes 0.204 seconds)

5.12.18 Solutions of the exercises for SciPy

Solutions of the exercises for SciPy

Crude periodicity finding

Discover the periods in evolution of animal populations (../../../../data/populations.txt)

Load the data

import numpy as np

data = np.loadtxt("../../../../data/populations.txt")
years = data[:, 0]
populations = data[:, 1:]

Plot the data

import matplotlib.pyplot as plt

plt.figure()
plt.plot(years, populations * 1e-3)
plt.xlabel("Year")
plt.ylabel(r"Population number ($\cdot10^3$)")
plt.legend(["hare", "lynx", "carrot"], loc=1)

5.12. Full code examples for the SciPy chapter 278


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.legend.Legend object at 0x7f495497bf10>

Plot its periods

import scipy as sp

ft_populations = sp.fft.fft(populations, axis=0)


frequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0])
periods = 1 / frequencies

plt.figure()
plt.plot(periods, abs(ft_populations) * 1e-3, "o")
plt.xlim(0, 22)
plt.xlabel("Period")
plt.ylabel(r"Power ($\cdot10^3$)")

plt.show()

5.12. Full code examples for the SciPy chapter 279


Scientific Python Lectures, Edition 2024.2rc0.dev0

/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/scipy/
˓→examples/solutions/plot_periodicity_finder.py:39: RuntimeWarning: divide by zero␣

˓→encountered in divide

periods = 1 / frequencies

There’s probably a period of around 10 years (obvious from the plot), but for this crude a method,
there’s not enough data to say much more.
Total running time of the script: (0 minutes 0.121 seconds)

Curve fitting: temperature as a function of month of the year

We have the min and max temperatures in Alaska for each months of the year. We would like to find a
function to describe this yearly evolution.
For this, we will fit a periodic function.

5.12. Full code examples for the SciPy chapter 280


Scientific Python Lectures, Edition 2024.2rc0.dev0

The data

import numpy as np

temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])

import matplotlib.pyplot as plt

months = np.arange(12)
plt.plot(months, temp_max, "ro")
plt.plot(months, temp_min, "bo")
plt.xlabel("Month")
plt.ylabel("Min and max temperature")

Text(35.472222222222214, 0.5, 'Min and max temperature')

5.12. Full code examples for the SciPy chapter 281


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fitting it to a periodic function

import scipy as sp

def yearly_temps(times, avg, ampl, time_offset):


return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max())

res_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0])


res_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0])

Plotting the fit

days = np.linspace(0, 12, num=365)

plt.figure()
plt.plot(months, temp_max, "ro")
plt.plot(days, yearly_temps(days, *res_max), "r-")
plt.plot(months, temp_min, "bo")
plt.plot(days, yearly_temps(days, *res_min), "b-")
plt.xlabel("Month")
plt.ylabel(r"Temperature ($^\circ$C)")

plt.show()

Total running time of the script: (0 minutes 0.132 seconds)

5.12. Full code examples for the SciPy chapter 282


Scientific Python Lectures, Edition 2024.2rc0.dev0

Simple image blur by convolution with a Gaussian kernel

Blur an an image (../../../../data/elephant.png) using a Gaussian kernel.


Convolution is easy to perform with FFT: convolving two signals boils down to multiplying their FFTs
(and performing an inverse FFT).

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

The original image

# read image
img = plt.imread("../../../../data/elephant.png")
plt.figure()
plt.imshow(img)

<matplotlib.image.AxesImage object at 0x7f4954a3a0d0>

5.12. Full code examples for the SciPy chapter 283


Scientific Python Lectures, Edition 2024.2rc0.dev0

Prepare an Gaussian convolution kernel

# First a 1-D Gaussian


t = np.linspace(-10, 10, 30)
bump = np.exp(-0.1 * t**2)
bump /= np.trapz(bump) # normalize the integral to 1

# make a 2-D kernel out of it


kernel = bump[:, np.newaxis] * bump[np.newaxis, :]

Implement convolution via FFT

# Padded fourier transform, with the same shape as the image


# We use :func:`scipy.fft.fft2` to have a 2D FFT
kernel_ft = sp.fft.fft2(kernel, s=img.shape[:2], axes=(0, 1))

# convolve
img_ft = sp.fft.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = sp.fft.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range


img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2)

5.12. Full code examples for the SciPy chapter 284


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.image.AxesImage object at 0x7f4955a67810>

Further exercise (only if you are familiar with this stuff):


A “wrapped border” appears in the upper left and top edges of the image. This is because the padding
is not done correctly, and does not take the kernel size into account (so the convolution “flows out of
bounds of the image”). Try to remove this artifact.

A function to do it: scipy.signal.fftconvolve()

The above exercise was only for didactic reasons: there exists a function in scipy that will do
this for us, and probably do a better job: scipy.signal.fftconvolve()

# mode='same' is there to enforce the same output shape as input arrays


# (ie avoid border effects)
img3 = sp.signal.fftconvolve(img, kernel[:, :, np.newaxis], mode="same")
plt.figure()
plt.imshow(img3)

5.12. Full code examples for the SciPy chapter 285


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.image.AxesImage object at 0x7f49601653d0>

Note that we still have a decay to zero at the border of the image. Using scipy.ndimage.
gaussian_filter() would get rid of this artifact

plt.show()

Total running time of the script: (0 minutes 0.377 seconds)

Image denoising by FFT

Denoise an image (../../../../data/moonlanding.png) by implementing a blur with an FFT.


Implements, via FFT, the following convolution:
∫︁
𝑓1 (𝑡) = 𝑑𝑡′ 𝐾(𝑡 − 𝑡′ )𝑓0 (𝑡′ )

𝑓˜1 (𝜔) = 𝐾(𝜔)


˜ 𝑓˜0 (𝜔)

5.12. Full code examples for the SciPy chapter 286


Scientific Python Lectures, Edition 2024.2rc0.dev0

Read and plot the image

import numpy as np
import matplotlib.pyplot as plt

im = plt.imread("../../../../data/moonlanding.png").astype(float)

plt.figure()
plt.imshow(im, plt.cm.gray)
plt.title("Original image")

Text(0.5, 1.0, 'Original image')

Compute the 2d FFT of the input image

import scipy as sp

im_fft = sp.fft.fft2(im)

# Show the results

def plot_spectrum(im_fft):
from matplotlib.colors import LogNorm

# A logarithmic colormap
(continues on next page)

5.12. Full code examples for the SciPy chapter 287


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5))
plt.colorbar()

plt.figure()
plot_spectrum(im_fft)
plt.title("Fourier transform")

Text(0.5, 1.0, 'Fourier transform')

Filter in FFT

# In the lines following, we'll make a copy of the original spectrum and
# truncate coefficients.

# Define the fraction of coefficients (in each direction) we keep


keep_fraction = 0.1

# Call ff a copy of the original transform. NumPy arrays have a copy


# method for this purpose.
im_fft2 = im_fft.copy()

# Set r and c to be the number of rows and columns of the array.


r, c = im_fft2.shape

(continues on next page)

5.12. Full code examples for the SciPy chapter 288


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Set to zero all rows with indices between r*keep_fraction and
# r*(1-keep_fraction):
im_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0

# Similarly with the columns:


im_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0

plt.figure()
plot_spectrum(im_fft2)
plt.title("Filtered Spectrum")

Text(0.5, 1.0, 'Filtered Spectrum')

Reconstruct the final image

# Reconstruct the denoised image from the filtered spectrum, keep only the
# real part for display.
im_new = sp.fft.ifft2(im_fft2).real

plt.figure()
plt.imshow(im_new, plt.cm.gray)
plt.title("Reconstructed Image")

5.12. Full code examples for the SciPy chapter 289


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 1.0, 'Reconstructed Image')

Easier and better: scipy.ndimage.gaussian_filter()

Implementing filtering directly with FFTs is tricky and time consuming. We can use the
Gaussian filter from scipy.ndimage

im_blur = sp.ndimage.gaussian_filter(im, 4)

plt.figure()
plt.imshow(im_blur, plt.cm.gray)
plt.title("Blurred image")

plt.show()

5.12. Full code examples for the SciPy chapter 290


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.865 seconds)

See also:
References to go further
• Some chapters of the advanced and the packages and applications parts of the SciPy lectures
• The SciPy cookbook

5.12. Full code examples for the SciPy chapter 291


CHAPTER 6
Getting help and finding documentation

Author: Emmanuelle Gouillart


Rather than knowing all functions in NumPy and SciPy, it is important to find rapidly information
throughout the documentation and the available help. Here are some ways to get information:
• In Ipython, help function opens the docstring of the function. Only type the beginning of the
function’s name and use tab completion to display the matching functions.

In [1]: help(np.van<TAB>

In [2]: help(np.vander)
Help on _ArrayFunctionDispatcher in module numpy:

vander(x, N=None, increasing=False)


Generate a Vandermonde matrix.

The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `increasing` boolean argument.
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such
a matrix with a geometric progression in each row is named for Alexandre-
Theophile Vandermonde.

Parameters
----------
x : array_like
1-D input array.
N : int, optional
Number of columns in the output. If `N` is not specified, a square
array is returned (``N = len(x)``).
(continues on next page)

292
Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


increasing : bool, optional
Order of the powers of the columns. If True, the powers increase
from left to right, if False (the default) they are reversed.

.. versionadded:: 1.9.0

Returns
-------
out : ndarray
Vandermonde matrix. If `increasing` is False, the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
True, the columns are ``x^0, x^1, ..., x^(N-1)``.

See Also
--------
polynomial.polynomial.polyvander

Examples
--------
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])

>>> np.column_stack([x**(N-1-i) for i in range(N)])


array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])

>>> x = np.array([1, 2, 3, 5])


>>> np.vander(x)
array([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> np.vander(x, increasing=True)
array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
[ 1, 3, 9, 27],
[ 1, 5, 25, 125]])

The determinant of a square Vandermonde matrix is the product


of the differences between the values of the input vector:

>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48

In Ipython it is not possible to open a separated window for help and documentation; however one can
always open a second Ipython shell just to display help and docstrings. . .
• Numpy’s and Scipy’s documentations can be browsed online on https://scipy.org and https://

293
Scientific Python Lectures, Edition 2024.2rc0.dev0

numpy.org. The search button is quite useful inside the reference documentation of the two
packages.
Tutorials on various topics as well as the complete API with all docstrings are found on this website.
• Numpy’s and Scipy’s documentation is enriched and updated on a regular basis by users on a wiki
https://numpy.org/doc/stable/. As a result, some docstrings are clearer or more detailed on the
wiki, and you may want to read directly the documentation on the wiki instead of the official
documentation website. Note that anyone can create an account on the wiki and write better
documentation; this is an easy way to contribute to an open-source project and improve the tools
you are using!
• The SciPy Cookbook https://scipy-cookbook.readthedocs.io gives recipes on many common prob-
lems frequently encountered, such as fitting data points, solving ODE, etc.
• Matplotlib’s website https://matplotlib.org/ features a very nice gallery with a large number of
plots, each of them shows both the source code and the resulting plot. This is very useful for
learning by example. More standard documentation is also available.
Finally, two more “technical” possibilities are useful as well:
• In Ipython, the magical function %psearch search for objects matching patterns. This is useful if,
for example, one does not know the exact name of a function.

In [3]: import numpy as np

• numpy.lookfor looks for keywords inside the docstrings of specified modules.

In [4]: np.lookfor('convolution')
Search results for 'convolution'
--------------------------------
numpy.convolve
Returns the discrete, linear convolution of two one-dimensional sequences.
numpy.ma.convolve
Returns the discrete, linear convolution of two one-dimensional sequences.
numpy.polymul
Find the product of two polynomials.
numpy.bartlett
Return the Bartlett window.
numpy.correlate
Cross-correlation of two 1-dimensional sequences.
numpy.vectorize
vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None,

• If everything listed above fails (and Google doesn’t have the answer). . . don’t despair! There is
a vibrant Scientific Python community. Scientific Python is present on various platform. https:
//scientific-python.org/community/
Packages like SciPy and NumPy also have their own channels. Have a look at their respective
websites to find out how to engage with users and maintainers.

294
Part II

Advanced topics

295
Scientific Python Lectures, Edition 2024.2rc0.dev0

This part of the Scientific Python Lectures is dedicated to advanced usage. It strives to educate the
proficient Python coder to be an expert and tackles various specific topics.

296
CHAPTER 7
Advanced Python Constructs

Author Zbigniew Jędrzejewski-Szmek


This section covers some features of the Python language which can be considered advanced — in
the sense that not every language has them, and also in the sense that they are more useful in more
complicated programs or libraries, but not in the sense of being particularly specialized, or particularly
complicated.
It is important to underline that this chapter is purely about the language itself — about features
supported through special syntax complemented by functionality of the Python stdlib, which could not
be implemented through clever external modules.
The process of developing the Python programming language, its syntax, is very transparent; proposed
changes are evaluated from various angles and discussed via Python Enhancement Proposals — PEPs.
As a result, features described in this chapter were added after it was shown that they indeed solve real
problems and that their use is as simple as possible.

Chapter contents

• Iterators, generator expressions and generators


– Iterators
– Generator expressions
– Generators
– Bidirectional communication
– Chaining generators
• Decorators
– Replacing or tweaking the original object

297
Scientific Python Lectures, Edition 2024.2rc0.dev0

– Decorators implemented as classes and as functions


– Copying the docstring and other attributes of the original function
– Examples in the standard library
– Deprecation of functions
– A while-loop removing decorator
– A plugin registration system
• Context managers
– Catching exceptions
– Using generators to define context managers

7.1 Iterators, generator expressions and generators

7.1.1 Iterators

Simplicity

Duplication of effort is wasteful, and replacing the various home-grown approaches with a standard
feature usually ends up making things more readable, and interoperable as well.
Guido van Rossum — Adding Optional Static Typing to Python

An iterator is an object adhering to the iterator protocol — basically this means that it has a next
method, which, when called, returns the next item in the sequence, and when there’s nothing to return,
raises the StopIteration exception.
An iterator object allows to loop just once. It holds the state (position) of a single iteration, or from the
other side, each loop over a sequence requires a single iterator object. This means that we can iterate
over the same sequence more than once concurrently. Separating the iteration logic from the sequence
allows us to have more than one way of iteration.
Calling the __iter__ method on a container to create an iterator object is the most straightforward way
to get hold of an iterator. The iter function does that for us, saving a few keystrokes.

>>> nums = [1, 2, 3] # note that ... varies: these are different objects
>>> iter(nums)
<...iterator object at ...>
>>> nums.__iter__()
<...iterator object at ...>
>>> nums.__reversed__()
<...reverseiterator object at ...>

>>> it = iter(nums)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
(continues on next page)

7.1. Iterators, generator expressions and generators 298


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


File "<stdin>", line 1, in <module>
StopIteration

When used in a loop, StopIteration is swallowed and causes the loop to finish. But with explicit
invocation, we can see that once the iterator is exhausted, accessing it raises an exception.
Using the for..in loop also uses the __iter__ method. This allows us to transparently start the iteration
over a sequence. But if we already have the iterator, we want to be able to use it in an for loop in
the same way. In order to achieve this, iterators in addition to next are also required to have a method
called __iter__ which returns the iterator (self).
Support for iteration is pervasive in Python: all sequences and unordered containers in the standard
library allow this. The concept is also stretched to other things: e.g. file objects support iteration over
lines.

>>> with open("/etc/fstab") as f:


... f is f.__iter__()
...
True

The file is an iterator itself and it’s __iter__ method doesn’t create a separate object: only a single
thread of sequential access is allowed.

7.1.2 Generator expressions

A second way in which iterator objects are created is through generator expressions, the basis for list
comprehensions. To increase clarity, a generator expression must always be enclosed in parentheses
or an expression. If round parentheses are used, then a generator iterator is created. If rectangular
parentheses are used, the process is short-circuited and we get a list.

>>> (i for i in nums)


<generator object <genexpr> at 0x...>
>>> [i for i in nums]
[1, 2, 3]
>>> list(i for i in nums)
[1, 2, 3]

The list comprehension syntax also extends to dictionary and set comprehensions. A set is cre-
ated when the generator expression is enclosed in curly braces. A dict is created when the generator
expression contains “pairs” of the form key:value:

>>> {i for i in range(3)}


{0, 1, 2}
>>> {i:i**2 for i in range(3)}
{0: 0, 1: 1, 2: 4}

One gotcha should be mentioned: in old Pythons the index variable (i) would leak, and in versions >=
3 this is fixed.

7.1. Iterators, generator expressions and generators 299


Scientific Python Lectures, Edition 2024.2rc0.dev0

7.1.3 Generators

Generators

A generator is a function that produces a sequence of results instead of a single value.


David Beazley — A Curious Course on Coroutines and Concurrency

A third way to create iterator objects is to call a generator function. A generator is a function containing
the keyword yield. It must be noted that the mere presence of this keyword completely changes the
nature of the function: this yield statement doesn’t have to be invoked, or even reachable, but causes
the function to be marked as a generator. When a normal function is called, the instructions contained in
the body start to be executed. When a generator is called, the execution stops before the first instruction
in the body. An invocation of a generator function creates a generator object, adhering to the iterator
protocol. As with normal function invocations, concurrent and recursive invocations are allowed.
When next is called, the function is executed until the first yield. Each encountered yield statement
gives a value becomes the return value of next. After executing the yield statement, the execution of
this function is suspended.

>>> def f():


... yield 1
... yield 2
>>> f()
<generator object f at 0x...>
>>> gen = f()
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

Let’s go over the life of the single invocation of the generator function.

>>> def f():


... print("-- start --")
... yield 3
... print("-- finish --")
... yield 4
>>> gen = f()
>>> next(gen)
-- start --
3
>>> next(gen)
-- finish --
4
>>> next(gen)
Traceback (most recent call last):
...
StopIteration

Contrary to a normal function, where executing f() would immediately cause the first print to be
executed, gen is assigned without executing any statements in the function body. Only when gen.
__next__() is invoked by next, the statements up to the first yield are executed. The second next
prints -- finish -- and execution halts on the second yield. The third next falls of the end of the

7.1. Iterators, generator expressions and generators 300


Scientific Python Lectures, Edition 2024.2rc0.dev0

function. Since no yield was reached, an exception is raised.


What happens with the function after a yield, when the control passes to the caller? The state of
each generator is stored in the generator object. From the point of view of the generator function, is
looks almost as if it was running in a separate thread, but this is just an illusion: execution is strictly
single-threaded, but the interpreter keeps and restores the state in between the requests for the next
value.
Why are generators useful? As noted in the parts about iterators, a generator function is just a different
way to create an iterator object. Everything that can be done with yield statements, could also be
done with next methods. Nevertheless, using a function and having the interpreter perform its magic
to create an iterator has advantages. A function can be much shorter than the definition of a class with
the required next and __iter__ methods. What is more important, it is easier for the author of the
generator to understand the state which is kept in local variables, as opposed to instance attributes,
which have to be used to pass data between consecutive invocations of next on an iterator object.
A broader question is why are iterators useful? When an iterator is used to power a loop, the loop
becomes very simple. The code to initialise the state, to decide if the loop is finished, and to find the
next value is extracted into a separate place. This highlights the body of the loop — the interesting
part. In addition, it is possible to reuse the iterator code in other places.

7.1.4 Bidirectional communication

Each yield statement causes a value to be passed to the caller. This is the reason for the introduction
of generators by PEP 255. But communication in the reverse direction is also useful. One obvious way
would be some external state, either a global variable or a shared mutable object. Direct communication
is possible thanks to PEP 342. It is achieved by turning the previously boring yield statement into an
expression. When the generator resumes execution after a yield statement, the caller can call a method
on the generator object to either pass a value into the generator, which then is returned by the yield
statement, or a different method to inject an exception into the generator.
The first of the new methods is send(value), which is similar to next(), but passes value into the
generator to be used for the value of the yield expression. In fact, g.next() and g.send(None) are
equivalent.
The second of the new methods is throw(type, value=None, traceback=None) which is equivalent to:

raise type, value, traceback

at the point of the yield statement.


Unlike raise (which immediately raises an exception from the current execution point), throw() first
resumes the generator, and only then raises the exception. The word throw was picked because it
is suggestive of putting the exception in another location, and is associated with exceptions in other
languages.
What happens when an exception is raised inside the generator? It can be either raised explicitly or
when executing some statements or it can be injected at the point of a yield statement by means of
the throw() method. In either case, such an exception propagates in the standard manner: it can
be intercepted by an except or finally clause, or otherwise it causes the execution of the generator
function to be aborted and propagates in the caller.
For completeness’ sake, it’s worth mentioning that generator iterators also have a close() method,
which can be used to force a generator that would otherwise be able to provide more values to finish
immediately. It allows the generator __del__ method to destroy objects holding the state of generator.
Let’s define a generator which just prints what is passed in through send and throw.

>>> import itertools


>>> def g():
... print('--start--')
... for i in itertools.count():
(continues on next page)

7.1. Iterators, generator expressions and generators 301


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


... print('--yielding %i --' % i)
... try:
... ans = yield i
... except GeneratorExit:
... print('--closing--')
... raise
... except Exception as e:
... print('--yield raised %r --' % e)
... else:
... print('--yield returned %s --' % ans)

>>> it = g()
>>> next(it)
--start--
--yielding 0--
0
>>> it.send(11)
--yield returned 11--
--yielding 1--
1
>>> it.throw(IndexError)
--yield raised IndexError()--
--yielding 2--
2
>>> it.close()
--closing--

7.1.5 Chaining generators

Note: This is a preview of PEP 380 (not yet implemented, but accepted for Python 3.3).

Let’s say we are writing a generator and we want to yield a number of values generated by a second
generator, a subgenerator. If yielding of values is the only concern, this can be performed without
much difficulty using a loop such as

subgen = some_other_generator()
for v in subgen:
yield v

However, if the subgenerator is to interact properly with the caller in the case of calls to send(), throw()
and close(), things become considerably more difficult. The yield statement has to be guarded by a
try..except..finally structure similar to the one defined in the previous section to “debug” the generator
function. Such code is provided in PEP 380#id13, here it suffices to say that new syntax to properly
yield from a subgenerator is being introduced in Python 3.3:

yield from some_other_generator()

This behaves like the explicit loop above, repeatedly yielding values from some_other_generator until
it is exhausted, but also forwards send, throw and close to the subgenerator.

7.1. Iterators, generator expressions and generators 302


Scientific Python Lectures, Edition 2024.2rc0.dev0

7.2 Decorators

Summary

This amazing feature appeared in the language almost apologetically and with concern that it might
not be that useful.
Bruce Eckel — An Introduction to Python Decorators

Since functions and classes are objects, they can be passed around. Since they are mutable objects, they
can be modified. The act of altering a function or class object after it has been constructed but before
is is bound to its name is called decorating.
There are two things hiding behind the name “decorator” — one is the function which does the work of
decorating, i.e. performs the real work, and the other one is the expression adhering to the decorator
syntax, i.e. an at-symbol and the name of the decorating function.
Function can be decorated by using the decorator syntax for functions:

@decorator # ❷
def function(): # ❶
pass

• A function is defined in the standard way. ❶


• An expression starting with @ placed before the function definition is the decorator ❷. The part
after @ must be a simple expression, usually this is just the name of a function or class. This part is
evaluated first, and after the function defined below is ready, the decorator is called with the newly
defined function object as the single argument. The value returned by the decorator is attached to
the original name of the function.
Decorators can be applied to functions and to classes. For classes the semantics are identical — the
original class definition is used as an argument to call the decorator and whatever is returned is assigned
under the original name.
Before the decorator syntax was implemented (PEP 318), it was possible to achieve the same effect by
assigning the function or class object to a temporary variable and then invoking the decorator explicitly
and then assigning the return value to the name of the function. This sounds like more typing, and it
is, and also the name of the decorated function doubling as a temporary variable must be used at least
three times, which is prone to errors. Nevertheless, the example above is equivalent to:

def function(): # ❶
pass
function = decorator(function) # ❷

Decorators can be stacked — the order of application is bottom-to-top, or inside-out. The semantics
are such that the originally defined function is used as an argument for the first decorator, whatever is
returned by the first decorator is used as an argument for the second decorator, . . . , and whatever is
returned by the last decorator is attached under the name of the original function.
The decorator syntax was chosen for its readability. Since the decorator is specified before the header
of the function, it is obvious that its is not a part of the function body and its clear that it can only
operate on the whole function. Because the expression is prefixed with @ is stands out and is hard to
miss (“in your face”, according to the PEP :) ). When more than one decorator is applied, each one is
placed on a separate line in an easy to read way.

7.2. Decorators 303


Scientific Python Lectures, Edition 2024.2rc0.dev0

7.2.1 Replacing or tweaking the original object

Decorators can either return the same function or class object or they can return a completely different
object. In the first case, the decorator can exploit the fact that function and class objects are mutable
and add attributes, e.g. add a docstring to a class. A decorator might do something useful even without
modifying the object, for example register the decorated class in a global registry. In the second case,
virtually anything is possible: when something different is substituted for the original function or class,
the new object can be completely different. Nevertheless, such behaviour is not the purpose of decorators:
they are intended to tweak the decorated object, not do something unpredictable. Therefore, when a
function is “decorated” by replacing it with a different function, the new function usually calls the original
function, after doing some preparatory work. Likewise, when a class is “decorated” by replacing if with
a new class, the new class is usually derived from the original class. When the purpose of the decorator
is to do something “every time”, like to log every call to a decorated function, only the second type of
decorators can be used. On the other hand, if the first type is sufficient, it is better to use it, because it
is simpler.

7.2.2 Decorators implemented as classes and as functions

The only requirement on decorators is that they can be called with a single argument. This means that
decorators can be implemented as normal functions, or as classes with a __call__ method, or in theory,
even as lambda functions.
Let’s compare the function and class approaches. The decorator expression (the part after @) can be
either just a name, or a call. The bare-name approach is nice (less to type, looks cleaner, etc.), but is
only possible when no arguments are needed to customise the decorator. Decorators written as functions
can be used in those two cases:

>>> def simple_decorator(function):


... print("doing decoration")
... return function
>>> @simple_decorator
... def function():
... print("inside function")
doing decoration
>>> function()
inside function

>>> def decorator_with_arguments(arg):


... print("defining the decorator")
... def _decorator(function):
... # in this inner function, arg is available too
... print("doing decoration, %r " % arg)
... return function
... return _decorator
>>> @decorator_with_arguments("abc")
... def function():
... print("inside function")
defining the decorator
doing decoration, 'abc'
>>> function()
inside function

The two trivial decorators above fall into the category of decorators which return the original function.
If they were to return a new function, an extra level of nestedness would be required. In the worst case,
three levels of nested functions.

7.2. Decorators 304


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> def replacing_decorator_with_args(arg):


... print("defining the decorator")
... def _decorator(function):
... # in this inner function, arg is available too
... print("doing decoration, %r " % arg)
... def _wrapper(*args, **kwargs):
... print("inside wrapper, %r %r " % (args, kwargs))
... return function(*args, **kwargs)
... return _wrapper
... return _decorator
>>> @replacing_decorator_with_args("abc")
... def function(*args, **kwargs):
... print("inside function, %r %r " % (args, kwargs))
... return 14
defining the decorator
doing decoration, 'abc'
>>> function(11, 12)
inside wrapper, (11, 12) {}
inside function, (11, 12) {}
14

The _wrapper function is defined to accept all positional and keyword arguments. In general we cannot
know what arguments the decorated function is supposed to accept, so the wrapper function just passes
everything to the wrapped function. One unfortunate consequence is that the apparent argument list is
misleading.
Compared to decorators defined as functions, complex decorators defined as classes are simpler. When
an object is created, the __init__ method is only allowed to return None, and the type of the created
object cannot be changed. This means that when a decorator is defined as a class, it doesn’t make
much sense to use the argument-less form: the final decorated object would just be an instance of the
decorating class, returned by the constructor call, which is not very useful. Therefore it’s enough to
discuss class-based decorators where arguments are given in the decorator expression and the decorator
__init__ method is used for decorator construction.

>>> class decorator_class(object):


... def __init__(self, arg):
... # this method is called in the decorator expression
... print("in decorator init, %s " % arg)
... self.arg = arg
... def __call__(self, function):
... # this method is called to do the job
... print("in decorator call, %s " % self.arg)
... return function
>>> deco_instance = decorator_class('foo')
in decorator init, foo
>>> @deco_instance
... def function(*args, **kwargs):
... print("in function, %s %s " % (args, kwargs))
in decorator call, foo
>>> function()
in function, () {}

Contrary to normal rules (PEP 8) decorators written as classes behave more like functions and therefore
their name often starts with a lowercase letter.
In reality, it doesn’t make much sense to create a new class just to have a decorator which returns the
original function. Objects are supposed to hold state, and such decorators are more useful when the
decorator returns a new object.

7.2. Decorators 305


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> class replacing_decorator_class(object):


... def __init__(self, arg):
... # this method is called in the decorator expression
... print("in decorator init, %s " % arg)
... self.arg = arg
... def __call__(self, function):
... # this method is called to do the job
... print("in decorator call, %s " % self.arg)
... self.function = function
... return self._wrapper
... def _wrapper(self, *args, **kwargs):
... print("in the wrapper, %s %s " % (args, kwargs))
... return self.function(*args, **kwargs)
>>> deco_instance = replacing_decorator_class('foo')
in decorator init, foo
>>> @deco_instance
... def function(*args, **kwargs):
... print("in function, %s %s " % (args, kwargs))
in decorator call, foo
>>> function(11, 12)
in the wrapper, (11, 12) {}
in function, (11, 12) {}

A decorator like this can do pretty much anything, since it can modify the original function object and
mangle the arguments, call the original function or not, and afterwards mangle the return value.

7.2.3 Copying the docstring and other attributes of the original function

When a new function is returned by the decorator to replace the original function, an unfortunate
consequence is that the original function name, the original docstring, the original argument list are
lost. Those attributes of the original function can partially be “transplanted” to the new function
by setting __doc__ (the docstring), __module__ and __name__ (the full name of the function), and
__annotations__ (extra information about arguments and the return value of the function available in
Python 3). This can be done automatically by using functools.update_wrapper.

functools.update_wrapper(wrapper, wrapped)

“Update a wrapper function to look like the wrapped function.”


>>> import functools
>>> def replacing_decorator_with_args(arg):
... print("defining the decorator")
... def _decorator(function):
... print("doing decoration, %r " % arg)
... def _wrapper(*args, **kwargs):
... print("inside wrapper, %r %r " % (args, kwargs))
... return function(*args, **kwargs)
... return functools.update_wrapper(_wrapper, function)
... return _decorator
>>> @replacing_decorator_with_args("abc")
... def function():
... "extensive documentation"
... print("inside function")
... return 14
defining the decorator
doing decoration, 'abc'

7.2. Decorators 306


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> function
<function function at 0x...>
>>> print(function.__doc__)
extensive documentation

One important thing is missing from the list of attributes which can be copied to the replacement
function: the argument list. The default values for arguments can be modified through the __defaults__,
__kwdefaults__ attributes, but unfortunately the argument list itself cannot be set as an attribute. This
means that help(function) will display a useless argument list which will be confusing for the user of
the function. An effective but ugly way around this problem is to create the wrapper dynamically, using
eval. This can be automated by using the external decorator module. It provides support for the
decorator decorator, which takes a wrapper and turns it into a decorator which preserves the function
signature.
To sum things up, decorators should always use functools.update_wrapper or some other means of
copying function attributes.

7.2.4 Examples in the standard library

First, it should be mentioned that there’s a number of useful decorators available in the standard library.
There are three decorators which really form a part of the language:
• classmethod causes a method to become a “class method”, which means that it can be invoked
without creating an instance of the class. When a normal method is invoked, the interpreter inserts
the instance object as the first positional parameter, self. When a class method is invoked, the
class itself is given as the first parameter, often called cls.
Class methods are still accessible through the class’ namespace, so they don’t pollute the module’s
namespace. Class methods can be used to provide alternative constructors:

class Array(object):
def __init__(self, data):
self.data = data

@classmethod
def fromfile(cls, file):
data = numpy.load(file)
return cls(data)

This is cleaner than using a multitude of flags to __init__.


• staticmethod is applied to methods to make them “static”, i.e. basically a normal function, but
accessible through the class namespace. This can be useful when the function is only needed inside
this class (its name would then be prefixed with _), or when we want the user to think of the
method as connected to the class, despite an implementation which doesn’t require this.
• property is the pythonic answer to the problem of getters and setters. A method decorated with
property becomes a getter which is automatically called on attribute access.

>>> class A(object):


... @property
... def a(self):
... "an important attribute"
... return "a value"
>>> A.a
<property object at 0x...>
>>> A().a
'a value'

7.2. Decorators 307


Scientific Python Lectures, Edition 2024.2rc0.dev0

In this example, A.a is an read-only attribute. It is also documented: help(A) includes the
docstring for attribute a taken from the getter method. Defining a as a property allows it to be a
calculated on the fly, and has the side effect of making it read-only, because no setter is defined.
To have a setter and a getter, two methods are required, obviously:

class Rectangle(object):
def __init__(self, edge):
self.edge = edge

@property
def area(self):
"""Computed area.

Setting this updates the edge length to the proper value.


"""
return self.edge**2

@area.setter
def area(self, area):
self.edge = area ** 0.5

The way that this works, is that the property decorator replaces the getter method with a property
object. This object in turn has three methods, getter, setter, and deleter, which can be used
as decorators. Their job is to set the getter, setter and deleter of the property object (stored as
attributes fget, fset, and fdel). The getter can be set like in the example above, when creating
the object. When defining the setter, we already have the property object under area, and we add
the setter to it by using the setter method. All this happens when we are creating the class.
Afterwards, when an instance of the class has been created, the property object is special. When the
interpreter executes attribute access, assignment, or deletion, the job is delegated to the methods
of the property object.
To make everything crystal clear, let’s define a “debug” example:

>>> class D(object):


... @property
... def a(self):
... print("getting 1")
... return 1
... @a.setter
... def a(self, value):
... print("setting %r " % value)
... @a.deleter
... def a(self):
... print("deleting")
>>> D.a
<property object at 0x...>
>>> D.a.fget
<function ...>
>>> D.a.fset
<function ...>
>>> D.a.fdel
<function ...>
>>> d = D() # ... varies, this is not the same `a` function
>>> d.a
getting 1
1
>>> d.a = 2
(continues on next page)

7.2. Decorators 308


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


setting 2
>>> del d.a
deleting
>>> d.a
getting 1
1

Properties are a bit of a stretch for the decorator syntax. One of the premises of the decorator
syntax — that the name is not duplicated — is violated, but nothing better has been invented so
far. It is just good style to use the same name for the getter, setter, and deleter methods.
Some newer examples include:
• functools.lru_cache memoizes an arbitrary function maintaining a limited cache of argu-
ments:answer pairs (Python 3.2)
• functools.total_ordering is a class decorator which fills in missing ordering methods (__lt__,
__gt__, __le__, . . . ) based on a single available one.

7.2.5 Deprecation of functions

Let’s say we want to print a deprecation warning on stderr on the first invocation of a function we don’t
like anymore. If we don’t want to modify the function, we can use a decorator:

class deprecated(object):
"""Print a deprecation warning once on first use of the function.

>>> @deprecated() # doctest: +SKIP


... def f():
... pass
>>> f() # doctest: +SKIP
f is deprecated
"""
def __call__(self, func):
self.func = func
self.count = 0
return self._wrapper
def _wrapper(self, *args, **kwargs):
self.count += 1
if self.count == 1:
print(self.func.__name__, 'is deprecated')
return self.func(*args, **kwargs)

It can also be implemented as a function:

def deprecated(func):
"""Print a deprecation warning once on first use of the function.

>>> @deprecated # doctest: +SKIP


... def f():
... pass
>>> f() # doctest: +SKIP
f is deprecated
"""
count = [0]
def wrapper(*args, **kwargs):
count[0] += 1
(continues on next page)

7.2. Decorators 309


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


if count[0] == 1:
print(func.__name__, 'is deprecated')
return func(*args, **kwargs)
return wrapper

7.2.6 A while-loop removing decorator

Let’s say we have function which returns a lists of things, and this list created by running a loop. If we
don’t know how many objects will be needed, the standard way to do this is something like:
def find_answers():
answers = []
while True:
ans = look_for_next_answer()
if ans is None:
break
answers.append(ans)
return answers

This is fine, as long as the body of the loop is fairly compact. Once it becomes more complicated, as
often happens in real code, this becomes pretty unreadable. We could simplify this by using yield
statements, but then the user would have to explicitly call list(find_answers()).
We can define a decorator which constructs the list for us:
def vectorized(generator_func):
def wrapper(*args, **kwargs):
return list(generator_func(*args, **kwargs))
return functools.update_wrapper(wrapper, generator_func)

Our function then becomes:


@vectorized
def find_answers():
while True:
ans = look_for_next_answer()
if ans is None:
break
yield ans

7.2.7 A plugin registration system

This is a class decorator which doesn’t modify the class, but just puts it in a global registry. It falls into
the category of decorators returning the original object:
class WordProcessor(object):
PLUGINS = []
def process(self, text):
for plugin in self.PLUGINS:
text = plugin().cleanup(text)
return text

@classmethod
def plugin(cls, plugin):
cls.PLUGINS.append(plugin)
(continues on next page)

7.2. Decorators 310


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

@WordProcessor.plugin
class CleanMdashesExtension(object):
def cleanup(self, text):
return text.replace('&mdash;', u'\N{em dash}')

Here we use a decorator to decentralise the registration of plugins. We call our decorator with a noun,
instead of a verb, because we use it to declare that our class is a plugin for WordProcessor. Method
plugin simply appends the class to the list of plugins.
A word about the plugin itself: it replaces HTML entity for em-dash with a real Unicode em-dash
character. It exploits the unicode literal notation to insert a character by using its name in the unicode
database (“EM DASH”). If the Unicode character was inserted directly, it would be impossible to
distinguish it from an en-dash in the source of a program.
See also:
More examples and reading
• PEP 318 (function and method decorator syntax)
• PEP 3129 (class decorator syntax)
• https://wiki.python.org/moin/PythonDecoratorLibrary
• https://docs.python.org/dev/library/functools.html
• https://pypi.org/project/decorator
• Bruce Eckel
– Decorators I: Introduction to Python Decorators
– Python Decorators II: Decorator Arguments
– Python Decorators III: A Decorator-Based Build System

7.3 Context managers

A context manager is an object with __enter__ and __exit__ methods which can be used in the with
statement:

with manager as var:


do_something(var)

is in the simplest case equivalent to

var = manager.__enter__()
try:
do_something(var)
finally:
manager.__exit__()

In other words, the context manager protocol defined in PEP 343 permits the extraction of the boring
part of a try..except..finally structure into a separate class leaving only the interesting do_something
block.
1. The __enter__ method is called first. It can return a value which will be assigned to var. The
as-part is optional: if it isn’t present, the value returned by __enter__ is simply ignored.
2. The block of code underneath with is executed. Just like with try clauses, it can either execute
successfully to the end, or it can break, continue or return, or it can throw an exception. Either

7.3. Context managers 311


Scientific Python Lectures, Edition 2024.2rc0.dev0

way, after the block is finished, the __exit__ method is called. If an exception was thrown,
the information about the exception is passed to __exit__, which is described below in the next
subsection. In the normal case, exceptions can be ignored, just like in a finally clause, and will
be rethrown after __exit__ is finished.
Let’s say we want to make sure that a file is closed immediately after we are done writing to it:

>>> class closing(object):


... def __init__(self, obj):
... self.obj = obj
... def __enter__(self):
... return self.obj
... def __exit__(self, *args):
... self.obj.close()
>>> with closing(open('/tmp/file', 'w')) as f:
... f.write('the contents\n')

Here we have made sure that the f.close() is called when the with block is exited. Since closing files is
such a common operation, the support for this is already present in the file class. It has an __exit__
method which calls close and can be used as a context manager itself:

>>> with open('/tmp/file', 'a') as f:


... f.write('more contents\n')

The common use for try..finally is releasing resources. Various different cases are implemented
similarly: in the __enter__ phase the resource is acquired, in the __exit__ phase it is released, and the
exception, if thrown, is propagated. As with files, there’s often a natural operation to perform after the
object has been used and it is most convenient to have the support built in. With each release, Python
provides support in more places:
• all file-like objects:
– file ➥ automatically closed
– fileinput, tempfile
– bz2.BZ2File, gzip.GzipFile, tarfile.TarFile, zipfile.ZipFile
– ftplib, nntplib ➥ close connection
• locks
– multiprocessing.RLock ➥ lock and unlock
– multiprocessing.Semaphore
– memoryview ➥ automatically release
• decimal.localcontext ➥ modify precision of computations temporarily
• _winreg.PyHKEY ➥ open and close hive key
• warnings.catch_warnings ➥ kill warnings temporarily
• contextlib.closing ➥ the same as the example above, call close
• parallel programming
– concurrent.futures.ThreadPoolExecutor ➥ invoke in parallel then kill thread pool
– concurrent.futures.ProcessPoolExecutor ➥ invoke in parallel then kill process pool
– nogil ➥ solve the GIL problem temporarily (cython only :( )

7.3. Context managers 312


Scientific Python Lectures, Edition 2024.2rc0.dev0

7.3.1 Catching exceptions

When an exception is thrown in the with-block, it is passed as arguments to __exit__. Three arguments
are used, the same as returned by sys.exc_info(): type, value, traceback. When no exception is thrown,
None is used for all three arguments. The context manager can “swallow” the exception by returning a
true value from __exit__. Exceptions can be easily ignored, because if __exit__ doesn’t use return
and just falls of the end, None is returned, a false value, and therefore the exception is rethrown after
__exit__ is finished.
The ability to catch exceptions opens interesting possibilities. A classic example comes from unit-tests
— we want to make sure that some code throws the right kind of exception:

class assert_raises(object):
# based on pytest and unittest.TestCase
def __init__(self, type):
self.type = type
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
if type is None:
raise AssertionError('exception expected')
if issubclass(type, self.type):
return True # swallow the expected exception
raise AssertionError('wrong exception type')

with assert_raises(KeyError):
{}['foo']

7.3.2 Using generators to define context managers

When discussing generators, it was said that we prefer generators to iterators implemented as classes
because they are shorter, sweeter, and the state is stored as local, not instance, variables. On the other
hand, as described in Bidirectional communication, the flow of data between the generator and its caller
can be bidirectional. This includes exceptions, which can be thrown into the generator. We would like to
implement context managers as special generator functions. In fact, the generator protocol was designed
to support this use case.

@contextlib.contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>

The contextlib.contextmanager helper takes a generator and turns it into a context manager. The
generator has to obey some rules which are enforced by the wrapper function — most importantly it
must yield exactly once. The part before the yield is executed from __enter__, the block of code
protected by the context manager is executed when the generator is suspended in yield, and the rest
is executed in __exit__. If an exception is thrown, the interpreter hands it to the wrapper through
__exit__ arguments, and the wrapper function then throws it at the point of the yield statement.
Through the use of generators, the context manager is shorter and simpler.
Let’s rewrite the closing example as a generator:

@contextlib.contextmanager
def closing(obj):
(continues on next page)

7.3. Context managers 313


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


try:
yield obj
finally:
obj.close()

Let’s rewrite the assert_raises example as a generator:

@contextlib.contextmanager
def assert_raises(type):
try:
yield
except type:
return
except Exception as value:
raise AssertionError('wrong exception type')
else:
raise AssertionError('exception expected')

Here we use a decorator to turn generator functions into context managers!

7.3. Context managers 314


CHAPTER 8
Advanced NumPy

Author: Pauli Virtanen


NumPy is at the base of Python’s scientific stack of tools. Its purpose to implement efficient operations
on many items in a block of memory. Understanding how it works in detail helps in making efficient use
of its flexibility, taking useful shortcuts.
This section covers:
• Anatomy of NumPy arrays, and its consequences. Tips and tricks.
• Universal functions: what, why, and what to do if you want a new one.
• Integration with other tools: NumPy offers several ways to wrap any data in an ndarray, without
unnecessary copies.
• Recently added features, and what’s in them: PEP 3118 buffers, generalized ufuncs, . . .

Prerequisites

• NumPy
• Cython
• Pillow (Python imaging library, used in a couple of examples)

Chapter contents

• Life of ndarray
– It’s. . .

315
Scientific Python Lectures, Edition 2024.2rc0.dev0

– Block of memory
– Data types
– Indexing scheme: strides
– Findings in dissection
• Universal functions
– What they are?
– Exercise: building an ufunc from scratch
– Solution: building an ufunc from scratch
– Generalized ufuncs
• Interoperability features
– Sharing multidimensional, typed data
– The old buffer protocol
– The old buffer protocol
– Array interface protocol
• Array siblings: chararray, maskedarray
– chararray: vectorized string operations
– masked_array missing data
– recarray: purely convenience
• Summary
• Contributing to NumPy/SciPy
– Why
– Reporting bugs
– Contributing to documentation
– Contributing features
– How to help, in general

Tip: In this section, NumPy will be imported as follows:

>>> import numpy as np

8.1 Life of ndarray

8.1.1 It’s. . .

ndarray =
block of memory + indexing scheme + data type descriptor
• raw data
• how to locate an element
• how to interpret an element

8.1. Life of ndarray 316


Scientific Python Lectures, Edition 2024.2rc0.dev0

typedef struct PyArrayObject {


PyObject_HEAD

/* Block of memory */
char *data;

/* Data type descriptor */


PyArray_Descr *descr;

/* Indexing scheme */
int nd;
npy_intp *dimensions;
npy_intp *strides;

/* Other stuff */
PyObject *base;
int flags;
PyObject *weakreflist;
} PyArrayObject;

8.1.2 Block of memory

>>> x = np.array([1, 2, 3], dtype=np.int32)


>>> x.data
<... at ...>
>>> bytes(x.data)
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'

Memory address of the data:

>>> x.__array_interface__['data'][0]
64803824

The whole __array_interface__:

>>> x.__array_interface__
{'data': (..., False), 'strides': None, 'descr': [('', '<i4')], 'typestr': '<i4',
˓→'shape': (3,), 'version': 3}

Reminder: two ndarrays may share the same memory:

>>> x = np.array([1, 2, 3, 4])


>>> y = x[:-1]
>>> x[0] = 9
>>> y
array([9, 2, 3])

8.1. Life of ndarray 317


Scientific Python Lectures, Edition 2024.2rc0.dev0

Memory does not need to be owned by an ndarray:

>>> x = b'1234'

x is a string (in Python 3 a bytes), we can represent its data as an array of ints:

>>> y = np.frombuffer(x, dtype=np.int8)


>>> y.data
<... at ...>
>>> y.base is x
True

>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : False
ALIGNED : True
WRITEBACKIFCOPY : False

The owndata and writeable flags indicate status of the memory block.
See also:
array interface

8.1.3 Data types

The descriptor

dtype describes a single item in the array:

type scalar type of the data, one of:


int8, int16, float64, et al. (fixed size)
str, unicode, void (flexible size)
itemsize size of the data block
byte- byte order: big-endian > / little-endian < / not applicable |
order
fields sub-dtypes, if it’s a structured data type
shape shape of the array, if it’s a sub-array

>>> np.dtype(int).type
<class 'numpy.int64'>
>>> np.dtype(int).itemsize
8
>>> np.dtype(int).byteorder
'='

8.1. Life of ndarray 318


Scientific Python Lectures, Edition 2024.2rc0.dev0

Example: reading .wav files

The .wav file header:

chunk_id "RIFF"
chunk_size 4-byte unsigned little-endian integer
format "WAVE"
fmt_id "fmt "
fmt_size 4-byte unsigned little-endian integer
audio_fmt 2-byte unsigned little-endian integer
num_channels 2-byte unsigned little-endian integer
sample_rate 4-byte unsigned little-endian integer
byte_rate 4-byte unsigned little-endian integer
block_align 2-byte unsigned little-endian integer
bits_per_sample 2-byte unsigned little-endian integer
data_id "data"
data_size 4-byte unsigned little-endian integer

• 44-byte block of raw data (in the beginning of the file)


• . . . followed by data_size bytes of actual sound data.
The .wav file header as a NumPy structured data type:

>>> wav_header_dtype = np.dtype([


... ("chunk_id", (bytes, 4)), # flexible-sized scalar type, item size 4
... ("chunk_size", "<u4"), # little-endian unsigned 32-bit integer
... ("format", "S4"), # 4-byte string
... ("fmt_id", "S4"),
... ("fmt_size", "<u4"),
... ("audio_fmt", "<u2"), #
... ("num_channels", "<u2"), # .. more of the same ...
... ("sample_rate", "<u4"), #
... ("byte_rate", "<u4"),
... ("block_align", "<u2"),
... ("bits_per_sample", "<u2"),
... ("data_id", ("S1", (2, 2))), # sub-array, just for fun!
... ("data_size", "u4"),
... #
... # the sound data itself cannot be represented here:
... # it does not have a fixed size
... ])

See also:
wavreader.py

>>> wav_header_dtype['format']
dtype('S4')
>>> wav_header_dtype.fields
mappingproxy({'chunk_id': (dtype('S4'), 0), 'chunk_size': (dtype('uint32'), 4),
˓→'format': (dtype('S4'), 8), 'fmt_id': (dtype('S4'), 12), 'fmt_size': (dtype('uint32

˓→'), 16), 'audio_fmt': (dtype('uint16'), 20), 'num_channels': (dtype('uint16'), 22),

˓→'sample_rate': (dtype('uint32'), 24), 'byte_rate': (dtype('uint32'), 28), 'block_

˓→align': (dtype('uint16'), 32), 'bits_per_sample': (dtype('uint16'), 34), 'data_id':␣

˓→(dtype(('S1', (2, 2))), 36), 'data_size': (dtype('uint32'), 40)})

>>> wav_header_dtype.fields['format']
(dtype('S4'), 8)

• The first element is the sub-dtype in the structured data, corresponding to the name format

8.1. Life of ndarray 319


Scientific Python Lectures, Edition 2024.2rc0.dev0

• The second one is its offset (in bytes) from the beginning of the item

Exercise

Mini-exercise, make a “sparse” dtype by using offsets, and only some of the fields:
>>> wav_header_dtype = np.dtype(dict(
... names=['format', 'sample_rate', 'data_id'],
... offsets=[offset_1, offset_2, offset_3], # counted from start of structure in␣
˓→bytes

... formats=list of dtypes for each of the fields,


... ))

and use that to read the sample rate, and data_id (as sub-array).

>>> f = open('data/test.wav', 'r')


>>> wav_header = np.fromfile(f, dtype=wav_header_dtype, count=1)
>>> f.close()
>>> print(wav_header)
[ ('RIFF', 17402L, 'WAVE', 'fmt ', 16L, 1, 1, 16000L, 32000L, 2, 16, [['d', 'a'], ['t
˓→', 'a']], 17366L)]

>>> wav_header['sample_rate']
array([16000], dtype=uint32)

Let’s try accessing the sub-array:

>>> wav_header['data_id']
array([[['d', 'a'],
['t', 'a']]],
dtype='|S1')
>>> wav_header.shape
(1,)
>>> wav_header['data_id'].shape
(1, 2, 2)

When accessing sub-arrays, the dimensions get added to the end!

Note: There are existing modules such as wavfile, audiolab, etc. for loading sound data. . .

Casting and re-interpretation/views

casting
• on assignment
• on array construction
• on arithmetic
• etc.
• and manually: .astype(dtype)
data re-interpretation
• manually: .view(dtype)

8.1. Life of ndarray 320


Scientific Python Lectures, Edition 2024.2rc0.dev0

Casting

• Casting in arithmetic, in nutshell:


– only type (not value!) of operands matters
– largest “safe” type able to represent both is picked
– scalars can “lose” to arrays in some situations
• Casting in general copies data:

>>> x = np.array([1, 2, 3, 4], dtype=float)


>>> x
array([1., 2., 3., 4.])
>>> y = x.astype(np.int8)
>>> y
array([1, 2, 3, 4], dtype=int8)
>>> y + 1
array([2, 3, 4, 5], dtype=int8)
>>> y + 256
array([257, 258, 259, 260], dtype=int16)
>>> y + 256.0
array([257., 258., 259., 260.])
>>> y + np.array([256], dtype=np.int32)
array([257, 258, 259, 260], dtype=int32)

• Casting on setitem: dtype of the array is not changed on item assignment:

>>> y[:] = y + 1.5


>>> y
array([2, 3, 4, 5], dtype=int8)

Note: Exact rules: see NumPy documentation

Re-interpretation / viewing

• Data block in memory (4 bytes)

0x01 || 0x02 || 0x03 || 0x04

– 4 of uint8, OR,
– 4 of int8, OR,
– 2 of int16, OR,
– 1 of int32, OR,
– 1 of float32, OR,
– ...
How to switch from one to another?
1. Switch the dtype:

>>> x = np.array([1, 2, 3, 4], dtype=np.uint8)


>>> x.dtype = "<i2"
>>> x
(continues on next page)

8.1. Life of ndarray 321


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


array([ 513, 1027], dtype=int16)
>>> 0x0201, 0x0403
(513, 1027)

0x01 0x02 || 0x03 0x04

Note: little-endian: least significant byte is on the left in memory

2. Create a new view of type uint32, shorthand i4:

>>> y = x.view("<i4")
>>> y
array([67305985], dtype=int32)
>>> 0x04030201
67305985

0x01 0x02 0x03 0x04

Note:
• .view() makes views, does not copy (or alter) the memory block
• only changes the dtype (and adjusts array shape):

>>> x[1] = 5
>>> y
array([328193], dtype=int32)
>>> y.base is x
True

Mini-exercise: data re-interpretation

See also:
view-colors.py
You have RGBA data in an array:

>>> x = np.zeros((10, 10, 4), dtype=np.int8)


>>> x[:, :, 0] = 1
>>> x[:, :, 1] = 2
>>> x[:, :, 2] = 3
>>> x[:, :, 3] = 4

where the last three dimensions are the R, B, and G, and alpha channels.
How to make a (10, 10) structured array with field names ‘r’, ‘g’, ‘b’, ‘a’ without copying data?

>>> y = ...

>>> assert (y['r'] == 1).all()


>>> assert (y['g'] == 2).all()
(continues on next page)

8.1. Life of ndarray 322


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> assert (y['b'] == 3).all()
>>> assert (y['a'] == 4).all()

Solution

>>> y = x.view([('r', 'i1'),


... ('g', 'i1'),
... ('b', 'i1'),
... ('a', 'i1')]
... )[:, :, 0]

Warning: Another two arrays, each occupying exactly 4 bytes of memory:


>>> x = np.array([[1, 3], [2, 4]], dtype=np.uint8)
>>> x
array([[1, 3],
[2, 4]], dtype=uint8)
>>> y = x.transpose()
>>> y
array([[1, 2],
[3, 4]], dtype=uint8)

We view the elements of x (1 byte each) as int16 (2 bytes each):


>>> x.view(np.int16)
array([[ 769],
[1026]], dtype=int16)

What is happening here? Take a look at the bytes stored in memory by x:


>>> x.tobytes()
b'\x01\x03\x02\x04'

The \x stands for heXadecimal, so what we are seeing is:


0x01 0x03 0x02 0x04

We ask NumPy to interpret these bytes as elements of dtype int16—each of which occupies two
bytes in memory. Therefore, 0x01 0x03 becomes the first uint16 and 0x02 0x04 the second.
You may then expect to see 0x0103 (259, when converting from hexadecimal to decimal) as the first
result. But your computer likely stores most significant bytes first, and as such reads the number as
0x0301 or 769 (go on and type 0x0301 into your Python terminal to verify).
We can do the same on a copy of y (why doesn’t it work on y directly?):
>>> y.copy().view(np.int16)
array([[ 513],
[1027]], dtype=int16)

Can you explain these numbers, 513 and 1027, as well as the output shape of the resulting array?

8.1. Life of ndarray 323


Scientific Python Lectures, Edition 2024.2rc0.dev0

8.1.4 Indexing scheme: strides

Main point

The question:

>>> x = np.array([[1, 2, 3],


... [4, 5, 6],
... [7, 8, 9]], dtype=np.int8)
>>> x.tobytes('A')
b'\x01\x02\x03\x04\x05\x06\x07\x08\t'

At which byte in ``x.data`` does the item ``x[1, 2]`` begin?

The answer (in NumPy)


• strides: the number of bytes to jump to find the next element
• 1 stride per dimension

>>> x.strides
(3, 1)
>>> byte_offset = 3 * 1 + 1 * 2 # to find x[1, 2]
>>> x.flat[byte_offset]
6
>>> x[1, 2]
6

simple, flexible

C and Fortran order

Note: The Python built-in bytes returns bytes in C-order by default which can cause confusion when
trying to inspect memory layout. We use numpy.ndarray.tobytes() with order=A instead, which
preserves the C or F ordering of the bytes in memory.

>>> x = np.array([[1, 2, 3],


... [4, 5, 6]], dtype=np.int16, order='C')
>>> x.strides
(6, 2)
>>> x.tobytes('A')
b'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00'

• Need to jump 6 bytes to find the next row


• Need to jump 2 bytes to find the next column

>>> y = np.array(x, order='F')


>>> y.strides
(2, 4)
>>> y.tobytes('A')
b'\x01\x00\x04\x00\x02\x00\x05\x00\x03\x00\x06\x00'

• Need to jump 2 bytes to find the next row


• Need to jump 4 bytes to find the next column
• Similarly to higher dimensions:

8.1. Life of ndarray 324


Scientific Python Lectures, Edition 2024.2rc0.dev0

– C: last dimensions vary fastest (= smaller strides)


– F: first dimensions vary fastest
shape = (𝑑1 , 𝑑2 , ..., 𝑑𝑛 )
strides = (𝑠1 , 𝑠2 , ..., 𝑠𝑛 )
𝑠𝐶
𝑗 = 𝑑𝑗+1 𝑑𝑗+2 ...𝑑𝑛 × itemsize

𝑠𝐹
𝑗 = 𝑑1 𝑑2 ...𝑑𝑗−1 × itemsize

Note: Now we can understand the behavior of .view():

>>> y = np.array([[1, 3], [2, 4]], dtype=np.uint8).transpose()


>>> x = y.copy()

Transposition does not affect the memory layout of the data, only strides

>>> x.strides
(2, 1)
>>> y.strides
(1, 2)

>>> x.tobytes('A')
b'\x01\x02\x03\x04'
>>> y.tobytes('A')
b'\x01\x03\x02\x04'

• the results are different when interpreted as 2 of int16


• .copy() creates new arrays in the C order (by default)

Note: In-place operations with views


Prior to NumPy version 1.13, in-place operations with views could result in incorrect results for large
arrays. Since version 1.13, NumPy includes checks for memory overlap to guarantee that results are
consistent with the non in-place version (e.g. a = a + a.T produces the same result as a += a.T).
Note however that this may result in the data being copied (as if using a += a.T.copy()), ultimately
resulting in more memory being used than might otherwise be expected for in-place operations!

Slicing with integers

• Everything can be represented by changing only shape, strides, and possibly adjusting the data
pointer!
• Never makes copies of the data

>>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32)


>>> y = x[::-1]
>>> y
array([6, 5, 4, 3, 2, 1], dtype=int32)
>>> y.strides
(-4,)

>>> y = x[2:]
>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0]
8
(continues on next page)

8.1. Life of ndarray 325


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

>>> x = np.zeros((10, 10, 10), dtype=float)


>>> x.strides
(800, 80, 8)
>>> x[::2,::3,::4].strides
(1600, 240, 32)

• Similarly, transposes never make copies (it just swaps strides):

>>> x = np.zeros((10, 10, 10), dtype=float)


>>> x.strides
(800, 80, 8)
>>> x.T.strides
(8, 80, 800)

But: not all reshaping operations can be represented by playing with strides:

>>> a = np.arange(6, dtype=np.int8).reshape(3, 2)


>>> b = a.T
>>> b.strides
(1, 2)

So far, so good. However:

>>> bytes(a.data)
b'\x00\x01\x02\x03\x04\x05'
>>> b
array([[0, 2, 4],
[1, 3, 5]], dtype=int8)
>>> c = b.reshape(3*2)
>>> c
array([0, 2, 4, 1, 3, 5], dtype=int8)

Here, there is no way to represent the array c given one stride and the block of memory for a. Therefore,
the reshape operation needs to make a copy here.

Example: fake dimensions with strides

Stride manipulation

>>> from numpy.lib.stride_tricks import as_strided


>>> help(as_strided)
Help on function as_strided in module numpy.lib.stride_tricks:
...

Warning: as_strided does not check that you stay inside the memory block bounds. . .

>>> x = np.array([1, 2, 3, 4], dtype=np.int16)


>>> as_strided(x, strides=(2*2, ), shape=(2, ))
array([1, 3], dtype=int16)
>>> x[::2]
array([1, 3], dtype=int16)

8.1. Life of ndarray 326


Scientific Python Lectures, Edition 2024.2rc0.dev0

See also:
stride-fakedims.py
Exercise

array([1, 2, 3, 4], dtype=np.int8)

-> array([[1, 2, 3, 4],


[1, 2, 3, 4],
[1, 2, 3, 4]], dtype=np.int8)

using only as_strided.:

Hint: byte_offset = stride[0]*index[0] + stride[1]*index[1] + ...

Spoiler
Stride can also be 0 :

>>> x = np.array([1, 2, 3, 4], dtype=np.int8)


>>> y = as_strided(x, strides=(0, 1), shape=(3, 4))
>>> y
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]], dtype=int8)
>>> y.base.base is x
True

Broadcasting

• Doing something useful with it: outer product of [1, 2, 3, 4] and [5, 6, 7]

>>> x = np.array([1, 2, 3, 4], dtype=np.int16)


>>> x2 = as_strided(x, strides=(0, 1*2), shape=(3, 4))
>>> x2
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]], dtype=int16)

>>> y = np.array([5, 6, 7], dtype=np.int16)


>>> y2 = as_strided(y, strides=(1*2, 0), shape=(3, 4))
>>> y2
array([[5, 5, 5, 5],
[6, 6, 6, 6],
[7, 7, 7, 7]], dtype=int16)

>>> x2 * y2
array([[ 5, 10, 15, 20],
[ 6, 12, 18, 24],
[ 7, 14, 21, 28]], dtype=int16)

8.1. Life of ndarray 327


Scientific Python Lectures, Edition 2024.2rc0.dev0

. . . seems somehow familiar . . .

>>> x = np.array([1, 2, 3, 4], dtype=np.int16)


>>> y = np.array([5, 6, 7], dtype=np.int16)
>>> x[np.newaxis,:] * y[:,np.newaxis]
array([[ 5, 10, 15, 20],
[ 6, 12, 18, 24],
[ 7, 14, 21, 28]], dtype=int16)

• Internally, array broadcasting is indeed implemented using 0-strides.

More tricks: diagonals

See also:
stride-diagonals.py
Challenge
• Pick diagonal entries of the matrix: (assume C memory order):

>>> x = np.array([[1, 2, 3],


... [4, 5, 6],
... [7, 8, 9]], dtype=np.int32)

>>> x_diag = as_strided(x, shape=(3,), strides=(???,))

• Pick the first super-diagonal entries [2, 6].


• And the sub-diagonals?
(Hint to the last two: slicing first moves the point where striding
starts from.)
Solution
Pick diagonals:

>>> x_diag = as_strided(x, shape=(3, ), strides=((3+1)*x.itemsize, ))


>>> x_diag
array([1, 5, 9], dtype=int32)

Slice first, to adjust the data pointer:

>>> as_strided(x[0, 1:], shape=(2, ), strides=((3+1)*x.itemsize, ))


array([2, 6], dtype=int32)

>>> as_strided(x[1:, 0], shape=(2, ), strides=((3+1)*x.itemsize, ))


array([4, 8], dtype=int32)

Note: Using np.diag

>>> y = np.diag(x, k=1)


>>> y
array([2, 6], dtype=int32)

However,

>>> y.flags.owndata
False

8.1. Life of ndarray 328


Scientific Python Lectures, Edition 2024.2rc0.dev0

See also:
stride-diagonals.py
Challenge
Compute the tensor trace:

>>> x = np.arange(5*5*5*5).reshape(5, 5, 5, 5)
>>> s = 0
>>> for i in range(5):
... for j in range(5):
... s += x[j, i, j, i]

by striding, and using sum() on the result.

>>> y = as_strided(x, shape=(5, 5), strides=(TODO, TODO))


>>> s2 = ...
>>> assert s == s2

Solution

>>> y = as_strided(x, shape=(5, 5), strides=((5*5*5 + 5)*x.itemsize,


... (5*5 + 1)*x.itemsize))
>>> s2 = y.sum()

CPU cache effects

Memory layout can affect performance:

In [1]: x = np.zeros((20000,))

In [2]: y = np.zeros((20000*67,))[::67]

In [3]: x.shape, y.shape


Out[3]: ((20000,), (20000,))

In [4]: %timeit x.sum()


5.13 us +- 14.3 ns per loop (mean +- std. dev. of 7 runs, 100,000 loops each)

In [5]: %timeit y.sum()


22.3 us +- 1.43 us per loop (mean +- std. dev. of 7 runs, 10,000 loops each)

In [6]: x.strides, y.strides


Out[6]: ((8,), (536,))

Smaller strides are faster?

8.1. Life of ndarray 329


Scientific Python Lectures, Edition 2024.2rc0.dev0

• CPU pulls data from main memory to its cache in blocks


• If many array items consecutively operated on fit in a single block (small stride):
– ⇒ fewer transfers needed
– ⇒ faster
See also:
• numexpr is designed to mitigate cache effects when evaluating array expressions.
• numba is a compiler for Python code, that is aware of numpy arrays.

8.1.5 Findings in dissection

• memory block: may be shared, .base, .data


• data type descriptor: structured data, sub-arrays, byte order, casting, viewing, .astype(), .view()
• strided indexing: strides, C/F-order, slicing w/ integers, as_strided, broadcasting, stride tricks,
diag, CPU cache coherence

8.2 Universal functions

8.2.1 What they are?

• Ufunc performs and elementwise operation on all elements of an array.


Examples:

np.add, np.subtract, scipy.special.*, ...

• Automatically support: broadcasting, casting, . . .


• The author of an ufunc only has to supply the elementwise operation, NumPy takes care of the
rest.
• The elementwise operation needs to be implemented in C (or, e.g., Cython)

8.2. Universal functions 330


Scientific Python Lectures, Edition 2024.2rc0.dev0

Parts of an Ufunc

1. Provided by user

void ufunc_loop(void **args, int *dimensions, int *steps, void *data)


{
/*
* int8 output = elementwise_function(int8 input_1, int8 input_2)
*
* This function must compute the ufunc for many values at once,
* in the way shown below.
*/
char *input_1 = (char*)args[0];
char *input_2 = (char*)args[1];
char *output = (char*)args[2];
int i;

for (i = 0; i < dimensions[0]; ++i) {


*output = elementwise_function(*input_1, *input_2);
input_1 += steps[0];
input_2 += steps[1];
output += steps[2];
}
}

2. The NumPy part, built by

char types[3]

types[0] = NPY_BYTE /* type of first input arg */


types[1] = NPY_BYTE /* type of second input arg */
types[2] = NPY_BYTE /* type of third input arg */

PyObject *python_ufunc = PyUFunc_FromFuncAndData(


ufunc_loop,
NULL,
types,
1, /* ntypes */
2, /* num_inputs */
1, /* num_outputs */
identity_element,
name,
docstring,
unused)

• A ufunc can also support multiple different input-output type combinations.

8.2. Universal functions 331


Scientific Python Lectures, Edition 2024.2rc0.dev0

Making it easier

3. ufunc_loop is of very generic form, and NumPy provides pre-made ones

PyUfunc_f_f float elementwise_func(float input_1)


PyUfunc_ff_f float elementwise_func(float input_1, float input_2)
PyUfunc_d_d double elementwise_func(double input_1)
PyUfunc_dd_d double elementwise_func(double input_1, double input_2)
PyUfunc_D_D elementwise_func(npy_cdouble *input, npy_cdouble* output)
PyUfunc_DD_D elementwise_func(npy_cdouble *in1, npy_cdouble *in2, npy_cdouble*
out)

• Only elementwise_func needs to be supplied


• . . . except when your elementwise function is not in one of the above forms

8.2.2 Exercise: building an ufunc from scratch

The Mandelbrot fractal is defined by the iteration

𝑧 ← 𝑧2 + 𝑐

where 𝑐 = 𝑥 + 𝑖𝑦 is a complex number. This iteration is repeated – if 𝑧 stays finite no matter how long
the iteration runs, 𝑐 belongs to the Mandelbrot set.
• Make ufunc called mandel(z0, c) that computes:

z = z0
for k in range(iterations):
z = z*z + c

say, 100 iterations or until z.real**2 + z.imag**2 > 1000. Use it to determine which c are in
the Mandelbrot set.
• Our function is a simple one, so make use of the PyUFunc_* helpers.
• Write it in Cython
See also:
mandel.pyx, mandelplot.py

#
# Fix the parts marked by TODO
#

#
# Compile this file by (Cython >= 0.12 required because of the complex vars)
#
# cython mandel.pyx
# python setup.py build_ext -i
#
# and try it out with, in this directory,
#
# >>> import mandel
# >>> mandel.mandel(0, 1 + 2j)
#
#

(continues on next page)

8.2. Universal functions 332


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# The elementwise function
# ------------------------

cdef void mandel_single_point(double complex *z_in,


double complex *c_in,
double complex *z_out) nogil:
#
# The Mandelbrot iteration
#

#
# Some points of note:
#
# - It's *NOT* allowed to call any Python functions here.
#
# The Ufunc loop runs with the Python Global Interpreter Lock released.
# Hence, the ``nogil``.
#
# - And so all local variables must be declared with ``cdef``
#
# - Note also that this function receives *pointers* to the data
#

cdef double complex z = z_in[0]


cdef double complex c = c_in[0]
cdef int k # the integer we use in the for loop

#
# TODO: write the Mandelbrot iteration for one point here,
# as you would write it in Python.
#
# Say, use 100 as the maximum number of iterations, and 1000
# as the cutoff for z.real**2 + z.imag**2.
#

TODO: mandelbrot iteration should go here

# Return the answer for this point


z_out[0] = z

# Boilerplate Cython definitions


#
# Pulls definitions from the NumPy C headers.
# -------------------------------------------

from numpy cimport import_array, import_ufunc


from numpy cimport (PyUFunc_FromFuncAndData,
PyUFuncGenericFunction)
from numpy cimport NPY_CDOUBLE, NP_DOUBLE, NPY_LONG

# Import all pre-defined loop functions


# you won't need all of them - keep the relevant ones

from numpy cimport (


PyUFunc_f_f_As_d_d,
(continues on next page)

8.2. Universal functions 333


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


PyUFunc_d_d,
PyUFunc_f_f,
PyUFunc_g_g,
PyUFunc_F_F_As_D_D,
PyUFunc_F_F,
PyUFunc_D_D,
PyUFunc_G_G,
PyUFunc_ff_f_As_dd_d,
PyUFunc_ff_f,
PyUFunc_dd_d,
PyUFunc_gg_g,
PyUFunc_FF_F_As_DD_D,
PyUFunc_DD_D,
PyUFunc_FF_F,
PyUFunc_GG_G)

# Required module initialization


# ------------------------------

import_array()
import_ufunc()

# The actual ufunc declaration


# ----------------------------

cdef PyUFuncGenericFunction loop_func[1]


cdef char input_output_types[3]
cdef void *elementwise_funcs[1]

#
# Reminder: some pre-made Ufunc loops:
#
# ================ =======================================================
# ``PyUfunc_f_f`` ``float elementwise_func(float input_1)``
# ``PyUfunc_ff_f`` ``float elementwise_func(float input_1, float input_2)``
# ``PyUfunc_d_d`` ``double elementwise_func(double input_1)``
# ``PyUfunc_dd_d`` ``double elementwise_func(double input_1, double input_2)``
# ``PyUfunc_D_D`` ``elementwise_func(complex_double *input, complex_double* complex_
˓→double)``

# ``PyUfunc_DD_D`` ``elementwise_func(complex_double *in1, complex_double *in2,␣


˓→complex_double* out)``

# ================ =======================================================
#
# The full list is above.
#
#
# Type codes:
#
# NPY_BOOL, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT,
# NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE,
# NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_DATETIME,
# NPY_TIMEDELTA, NPY_OBJECT, NPY_STRING, NPY_UNICODE, NPY_VOID
#

(continues on next page)

8.2. Universal functions 334


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


loop_func[0] = ... TODO: suitable PyUFunc_* ...
input_output_types[0] = ... TODO ...
... TODO: fill in rest of input_output_types ...

# This thing is passed as the ``data`` parameter for the generic


# PyUFunc_* loop, to let it know which function it should call.
elementwise_funcs[0] = <void*>mandel_single_point

# Construct the ufunc:

mandel = PyUFunc_FromFuncAndData(
loop_func,
elementwise_funcs,
input_output_types,
1, # number of supported input types
TODO, # number of input args
TODO, # number of output args
0, # `identity` element, never mind this
"mandel", # function name
"mandel(z, c) -> computes z*z + c", # docstring
0 # unused
)

Reminder: some pre-made Ufunc loops:

PyUfunc_f_f float elementwise_func(float input_1)


PyUfunc_ff_f float elementwise_func(float input_1, float input_2)
PyUfunc_d_d double elementwise_func(double input_1)
PyUfunc_dd_d double elementwise_func(double input_1, double input_2)
PyUfunc_D_D elementwise_func(complex_double *input, complex_double* output)
PyUfunc_DD_D elementwise_func(complex_double *in1, complex_double *in2,
complex_double* out)

Type codes:
NPY_BOOL, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT,
NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE,
NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_DATETIME,
NPY_TIMEDELTA, NPY_OBJECT, NPY_STRING, NPY_UNICODE, NPY_VOID

8.2.3 Solution: building an ufunc from scratch

# The elementwise function


# ------------------------

cdef void mandel_single_point(double complex *z_in,


double complex *c_in,
double complex *z_out) nogil:
#
# The Mandelbrot iteration
#

#
# Some points of note:
(continues on next page)

8.2. Universal functions 335


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


#
# - It's *NOT* allowed to call any Python functions here.
#
# The Ufunc loop runs with the Python Global Interpreter Lock released.
# Hence, the ``nogil``.
#
# - And so all local variables must be declared with ``cdef``
#
# - Note also that this function receives *pointers* to the data;
# the "traditional" solution to passing complex variables around
#

cdef double complex z = z_in[0]


cdef double complex c = c_in[0]
cdef int k # the integer we use in the for loop

# Straightforward iteration

for k in range(100):
z = z*z + c
if z.real**2 + z.imag**2 > 1000:
break

# Return the answer for this point


z_out[0] = z

# Boilerplate Cython definitions


#
# Pulls definitions from the NumPy C headers.
# -------------------------------------------

from numpy cimport import_array, import_ufunc


from numpy cimport (PyUFunc_FromFuncAndData,
PyUFuncGenericFunction)
from numpy cimport NPY_CDOUBLE
from numpy cimport PyUFunc_DD_D

# Required module initialization


# ------------------------------

import_array()
import_ufunc()

# The actual ufunc declaration


# ----------------------------

cdef PyUFuncGenericFunction loop_func[1]


cdef char input_output_types[3]
cdef void *elementwise_funcs[1]

loop_func[0] = PyUFunc_DD_D

input_output_types[0] = NPY_CDOUBLE
input_output_types[1] = NPY_CDOUBLE
(continues on next page)

8.2. Universal functions 336


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


input_output_types[2] = NPY_CDOUBLE

elementwise_funcs[0] = <void*>mandel_single_point

mandel = PyUFunc_FromFuncAndData(
loop_func,
elementwise_funcs,
input_output_types,
1, # number of supported input types
2, # number of input args
1, # number of output args
0, # `identity` element, never mind this
"mandel", # function name
"mandel(z, c) -> computes iterated z*z + c", # docstring
0 # unused
)

"""
Plot Mandelbrot
================

Plot the Mandelbrot ensemble.

"""

import numpy as np
import mandel

x = np.linspace(-1.7, 0.6, 1000)


y = np.linspace(-1.4, 1.4, 1000)
c = x[None, :] + 1j * y[:, None]
z = mandel.mandel(c, c)

import matplotlib.pyplot as plt

plt.imshow(abs(z) ** 2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4])


plt.gray()
plt.show()

Note: Most of the boilerplate could be automated by these Cython modules:

8.2. Universal functions 337


Scientific Python Lectures, Edition 2024.2rc0.dev0

https://github.com/cython/cython/wiki/MarkLodato-CreatingUfuncs

Several accepted input types

E.g. supporting both single- and double-precision versions

cdef void mandel_single_point(double complex *z_in,


double complex *c_in,
double complex *z_out) nogil:
...

cdef void mandel_single_point_singleprec(float complex *z_in,


float complex *c_in,
float complex *z_out) nogil:
...

cdef PyUFuncGenericFunction loop_funcs[2]


cdef char input_output_types[3*2]
cdef void *elementwise_funcs[1*2]

loop_funcs[0] = PyUFunc_DD_D
input_output_types[0] = NPY_CDOUBLE
input_output_types[1] = NPY_CDOUBLE
input_output_types[2] = NPY_CDOUBLE
elementwise_funcs[0] = <void*>mandel_single_point

loop_funcs[1] = PyUFunc_FF_F
input_output_types[3] = NPY_CFLOAT
input_output_types[4] = NPY_CFLOAT
input_output_types[5] = NPY_CFLOAT
elementwise_funcs[1] = <void*>mandel_single_point_singleprec

mandel = PyUFunc_FromFuncAndData(
loop_func,
elementwise_funcs,
input_output_types,
2, # number of supported input types <----------------
2, # number of input args
1, # number of output args
0, # `identity` element, never mind this
"mandel", # function name
"mandel(z, c) -> computes iterated z*z + c", # docstring
0 # unused
)

8.2. Universal functions 338


Scientific Python Lectures, Edition 2024.2rc0.dev0

8.2.4 Generalized ufuncs

ufunc
output = elementwise_function(input)
Both output and input can be a single array element only.
generalized ufunc
output and input can be arrays with a fixed number of dimensions
For example, matrix trace (sum of diag elements):

input shape = (n, n)


output shape = () i.e. scalar

(n, n) -> ()

Matrix product:

input_1 shape = (m, n)


input_2 shape = (n, p)
output shape = (m, p)

(m, n), (n, p) -> (m, p)

• This is called the “signature” of the generalized ufunc


• The dimensions on which the g-ufunc acts, are “core dimensions”

Status in NumPy

• g-ufuncs are in NumPy already . . .


• new ones can be created with PyUFunc_FromFuncAndDataAndSignature
• most linear-algebra functions are implemented as g-ufuncs to enable working with stacked arrays:

>>> import numpy as np


>>> rng = np.random.default_rng(27446968)
>>> np.linalg.det(rng.random((3, 5, 5)))
array([ 0.01829761, -0.0077266 , -0.05336566])
>>> np.linalg._umath_linalg.det.signature
'(m,m)->()'

• matrix multiplication this way could be useful for operating on many small matrices at once
• Also see tensordot and einsum

Generalized ufunc loop

Matrix multiplication (m,n),(n,p) -> (m,p)

void gufunc_loop(void **args, int *dimensions, int *steps, void *data)


{
char *input_1 = (char*)args[0]; /* these are as previously */
char *input_2 = (char*)args[1];
char *output = (char*)args[2];

int input_1_stride_m = steps[3]; /* strides for the core dimensions */


(continues on next page)

8.2. Universal functions 339


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


int input_1_stride_n = steps[4]; /* are added after the non-core */
int input_2_strides_n = steps[5]; /* steps */
int input_2_strides_p = steps[6];
int output_strides_n = steps[7];
int output_strides_p = steps[8];

int m = dimension[1]; /* core dimensions are added after */


int n = dimension[2]; /* the main dimension; order as in */
int p = dimension[3]; /* signature */

int i;

for (i = 0; i < dimensions[0]; ++i) {


matmul_for_strided_matrices(input_1, input_2, output,
strides for each array...);

input_1 += steps[0];
input_2 += steps[1];
output += steps[2];
}
}

8.3 Interoperability features

8.3.1 Sharing multidimensional, typed data

Suppose you
1. Write a library than handles (multidimensional) binary data,
2. Want to make it easy to manipulate the data with NumPy, or whatever other library,
3. . . . but would not like to have NumPy as a dependency.
Currently, 3 solutions:
1. the “old” buffer interface
2. the array interface
3. the “new” buffer interface (PEP 3118)

8.3.2 The old buffer protocol

• Only 1-D buffers


• No data type information
• C-level interface; PyBufferProcs tp_as_buffer in the type object
• But it’s integrated into Python (e.g. strings support it)
Mini-exercise using Pillow (Python Imaging Library):
See also:
pilbuffer.py

8.3. Interoperability features 340


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> from PIL import Image


>>> data = np.zeros((200, 200, 4), dtype=np.uint8)
>>> data[:, :] = [255, 0, 0, 255] # Red
>>> # In PIL, RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA]
>>> data = data.view(np.int32).squeeze()
>>> img = Image.frombuffer("RGBA", (200, 200), data, "raw", "RGBA", 0, 1)
>>> img.save('test.png')

Q:
Check what happens if data is now modified, and img saved again.

8.3.3 The old buffer protocol

"""
From buffer
============

Show how to exchange data between numpy and a library that only knows
the buffer interface.
"""

import numpy as np
import Image

# Let's make a sample image, RGBA format

x = np.zeros((200, 200, 4), dtype=np.int8)

x[:, :, 0] = 254 # red


x[:, :, 3] = 255 # opaque

data = x.view(np.int32) # Check that you understand why this is OK!

img = Image.frombuffer("RGBA", (200, 200), data)


img.save("test.png")

#
# Modify the original data, and save again.
#
# It turns out that PIL, which knows next to nothing about NumPy,
# happily shares the same data.
#

x[:, :, 1] = 254
img.save("test2.png")

8.3. Interoperability features 341


Scientific Python Lectures, Edition 2024.2rc0.dev0

8.3.4 Array interface protocol

• Multidimensional buffers
• Data type information present
• NumPy-specific approach; slowly deprecated (but not going away)
• Not integrated in Python otherwise
See also:
Documentation: https://numpy.org/doc/stable/reference/arrays.interface.html

>>> x = np.array([[1, 2], [3, 4]])


>>> x.__array_interface__
{'data': (171694552, False), # memory address of data, is readonly?
'descr': [('', '<i4')], # data type descriptor
'typestr': '<i4', # same, in another form
'strides': None, # strides; or None if in C-order
'shape': (2, 2),
'version': 3,
}

::

>>> from PIL import Image


>>> img = Image.open('data/test.png')
>>> img.__array_interface__
{'version': 3,
'data': ...,
'shape': (200, 200, 4),
(continues on next page)

8.3. Interoperability features 342


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'typestr': '|u1'}
>>> x = np.asarray(img)
>>> x.shape
(200, 200, 4)

Note: A more C-friendly variant of the array interface is also defined.

8.4 Array siblings: chararray, maskedarray

8.4.1 chararray: vectorized string operations

>>> x = np.array(['a', ' bbb', ' ccc']).view(np.chararray)


>>> x.lstrip(' ')
chararray(['a', 'bbb', 'ccc'],
dtype='...')
>>> x.upper()
chararray(['A', ' BBB', ' CCC'],
dtype='...')

Note: .view() has a second meaning: it can make an ndarray an instance of a specialized ndarray
subclass

8.4.2 masked_array missing data

Masked arrays are arrays that may have missing or invalid entries.
For example, suppose we have an array where the fourth entry is invalid:

>>> x = np.array([1, 2, 3, -99, 5])

One way to describe this is to create a masked array:

>>> mx = np.ma.masked_array(x, mask=[0, 0, 0, 1, 0])


>>> mx
masked_array(data=[1, 2, 3, --, 5],
mask=[False, False, False, True, False],
fill_value=999999)

Masked mean ignores masked data:

>>> mx.mean()
2.75
>>> np.mean(mx)
2.75

Warning: Not all NumPy functions respect masks, for instance np.dot, so check the return types.

The masked_array returns a view to the original array:

8.4. Array siblings: chararray, maskedarray 343


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> mx[1] = 9
>>> x
array([ 1, 9, 3, -99, 5])

The mask

You can modify the mask by assigning:

>>> mx[1] = np.ma.masked


>>> mx
masked_array(data=[1, --, 3, --, 5],
mask=[False, True, False, True, False],
fill_value=999999)

The mask is cleared on assignment:

>>> mx[1] = 9
>>> mx
masked_array(data=[1, 9, 3, --, 5],
mask=[False, False, False, True, False],
fill_value=999999)

The mask is also available directly:

>>> mx.mask
array([False, False, False, True, False])

The masked entries can be filled with a given value to get an usual array back:

>>> x2 = mx.filled(-1)
>>> x2
array([ 1, 9, 3, -1, 5])

The mask can also be cleared:

>>> mx.mask = np.ma.nomask


>>> mx
masked_array(data=[1, 9, 3, -99, 5],
mask=[False, False, False, False, False],
fill_value=999999)

Domain-aware functions

The masked array package also contains domain-aware functions:

>>> np.ma.log(np.array([1, 2, -1, -2, 3, -5]))


masked_array(data=[0.0, 0.693147180559..., --, --, 1.098612288668..., --],
mask=[False, False, True, True, False, True],
fill_value=1e+20)

Note: Streamlined and more seamless support for dealing with missing data in arrays is making its
way into NumPy 1.7. Stay tuned!

8.4. Array siblings: chararray, maskedarray 344


Scientific Python Lectures, Edition 2024.2rc0.dev0

Example: Masked statistics

Canadian rangers were distracted when counting hares and lynxes in 1903-1910 and 1917-1918, and
got the numbers are wrong. (Carrot farmers stayed alert, though.) Compute the mean populations
over time, ignoring the invalid numbers.
>>> data = np.loadtxt('data/populations.txt')
>>> populations = np.ma.masked_array(data[:,1:])
>>> year = data[:, 0]

>>> bad_years = (((year >= 1903) & (year <= 1910))


... | ((year >= 1917) & (year <= 1918)))
>>> # '&' means 'and' and '|' means 'or'
>>> populations[bad_years, 0] = np.ma.masked
>>> populations[bad_years, 1] = np.ma.masked

>>> populations.mean(axis=0)
masked_array(data=[40472.72727272727, 18627.272727272728, 42400.0],
mask=[False, False, False],
fill_value=1e+20)

>>> populations.std(axis=0)
masked_array(data=[21087.656489006717, 15625.799814240254, 3322.5062255844787],
mask=[False, False, False],
fill_value=1e+20)

Note that Matplotlib knows about masked arrays:


>>> plt.plot(year, populations, 'o-')
[<matplotlib.lines.Line2D object at ...>, ...]

8.4.3 recarray: purely convenience

>>> arr = np.array([('a', 1), ('b', 2)], dtype=[('x', 'S1'), ('y', int)])
>>> arr2 = arr.view(np.recarray)
>>> arr2.x
array([b'a', b'b'], dtype='|S1')
>>> arr2.y
array([1, 2])

8.4. Array siblings: chararray, maskedarray 345


Scientific Python Lectures, Edition 2024.2rc0.dev0

8.5 Summary

• Anatomy of the ndarray: data, dtype, strides.


• Universal functions: elementwise operations, how to make new ones
• Ndarray subclasses
• Various buffer interfaces for integration with other tools
• Recent additions: PEP 3118, generalized ufuncs

8.6 Contributing to NumPy/SciPy

Get this tutorial: https://www.euroscipy.org/talk/882

8.6.1 Why

• “There’s a bug?”
• “I don’t understand what this is supposed to do?”
• “I have this fancy code. Would you like to have it?”
• “I’d like to help! What can I do?”

8.6.2 Reporting bugs

• Bug tracker (prefer this)


– https://github.com/numpy/numpy/issues
– https://github.com/scipy/scipy/issues
– Click the “Sign up” link to get an account
• Mailing lists (https://numpy.org/community/)
– If you’re unsure
– No replies in a week or so? Just file a bug ticket.

Good bug report

Title: numpy.random.permutations fails for non-integer arguments

I'm trying to generate random permutations, using numpy.random.permutations

When calling numpy.random.permutation with non-integer arguments


it fails with a cryptic error message::

>>> rng.permutation(12)
array([ 2, 6, 4, 1, 8, 11, 10, 5, 9, 3, 7, 0])
>>> rng.permutation(12.) #doctest: +SKIP
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "_generator.pyx", line 4844, in numpy.random._generator.Generator.permutation
numpy.exceptions.AxisError: axis 0 is out of bounds for array of dimension 0

(continues on next page)

8.5. Summary 346


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


This also happens with long arguments, and so
np.random.permutation(X.shape[0]) where X is an array fails on 64
bit windows (where shape is a tuple of longs).

It would be great if it could cast to integer or at least raise a


proper error for non-integer types.

I'm using NumPy 1.4.1, built from the official tarball, on Windows
64 with Visual studio 2008, on Python.org 64-bit Python.

0. What are you trying to do?


1. Small code snippet reproducing the bug (if possible)
• What actually happens
• What you’d expect
2. Platform (Windows / Linux / OSX, 32/64 bits, x86/PPC, . . . )
3. Version of NumPy/SciPy

>>> print(np.__version__)
1...

Check that the following is what you expect

>>> print(np.__file__)
/...

In case you have old/broken NumPy installations lying around.


If unsure, try to remove existing NumPy installations, and reinstall. . .

8.6.3 Contributing to documentation

1. Documentation editor
• https://numpy.org/doc/stable/
• Registration
– Register an account
– Subscribe to scipy-dev mailing list (subscribers-only)
– Problem with mailing lists: you get mail
∗ But: you can turn mail delivery off
∗ “change your subscription options”, at the bottom of
https://mail.python.org/mailman3/lists/scipy-dev.python.org/
– Send a mail @ scipy-dev mailing list; ask for activation:

To: [email protected]

Hi,

I'd like to edit NumPy/SciPy docstrings. My account is XXXXX

Cheers,
N. N.

8.6. Contributing to NumPy/SciPy 347


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Check the style guide:


– https://numpy.org/doc/stable/
– Don’t be intimidated; to fix a small thing, just fix it
• Edit
2. Edit sources and send patches (as for bugs)
3. Complain on the mailing list

8.6.4 Contributing features

The contribution of features is documented on https://numpy.org/doc/stable/dev/

8.6.5 How to help, in general

• Bug fixes always welcome!


– What irks you most
– Browse the tracker
• Documentation work
– API docs: improvements to docstrings
∗ Know some SciPy module well?
– User guide
∗ https://numpy.org/doc/stable/user/
• Ask on communication channels:
– numpy-discussion list
– scipy-dev list

8.6. Contributing to NumPy/SciPy 348


CHAPTER 9
Debugging code

Author: Gaël Varoquaux


This section explores tools to understand better your code base: debugging, to find and fix bugs.
It is not specific to the scientific Python community, but the strategies that we will employ are tailored
to its needs.

Prerequisites

• NumPy
• IPython
• nosetests
• pyflakes
• gdb for the C-debugging part.

Chapter contents

• Avoiding bugs
– Coding best practices to avoid getting in trouble
– pyflakes: fast static analysis
• Debugging workflow
• Using the Python debugger
– Invoking the debugger

349
Scientific Python Lectures, Edition 2024.2rc0.dev0

– Debugger commands and interaction


• Debugging segmentation faults using gdb

9.1 Avoiding bugs

9.1.1 Coding best practices to avoid getting in trouble

Brian Kernighan

“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re
as clever as you can be when you write it, how will you ever debug it?”

• We all write buggy code. Accept it. Deal with it.


• Write your code with testing and debugging in mind.
• Keep It Simple, Stupid (KISS).
– What is the simplest thing that could possibly work?
• Don’t Repeat Yourself (DRY).
– Every piece of knowledge must have a single, unambiguous, authoritative representation within
a system.
– Constants, algorithms, etc. . .
• Try to limit interdependencies of your code. (Loose Coupling)
• Give your variables, functions and modules meaningful names (not mathematics names)

9.1.2 pyflakes: fast static analysis

They are several static analysis tools in Python; to name a few:


• pylint
• pychecker
• pyflakes
• flake8
Here we focus on pyflakes, which is the simplest tool.
• Fast, simple
• Detects syntax errors, missing imports, typos on names.
Another good recommendation is the flake8 tool which is a combination of pyflakes and pep8. Thus, in
addition to the types of errors that pyflakes catches, flake8 detects violations of the recommendation in
PEP8 style guide.
Integrating pyflakes (or flake8) in your editor or IDE is highly recommended, it does yield productivity
gains.

9.1. Avoiding bugs 350


Scientific Python Lectures, Edition 2024.2rc0.dev0

Running pyflakes on the current edited file

You can bind a key to run pyflakes in the current buffer.


• In kate Menu: ‘settings -> configure kate
– In plugins enable ‘external tools’
– In external Tools’, add pyflakes:

kdialog --title "pyflakes %f ilename" --msgbox "$(pyflakes %f ilename)"

• In TextMate
Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a shell variable:

TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes

Then Ctrl-Shift-V is binded to a pyflakes report


• In vim In your .vimrc (binds F5 to pyflakes):

autocmd FileType python let &mp = 'echo "*** running % ***" ; pyflakes %'
autocmd FileType tex,mp,rst,python imap <Esc>[15~ <C-O>:make!^M
autocmd FileType tex,mp,rst,python map <Esc>[15~ :make!^M
autocmd FileType tex,mp,rst,python set autowrite

• In emacs In your .emacs (binds F5 to pyflakes):

(defun pyflakes-thisfile () (interactive)


(compile (format "pyflakes %s " (buffer-file-name)))
)

(define-minor-mode pyflakes-mode
"Toggle pyflakes mode.
With no argument, this command toggles the mode.
Non-null prefix argument turns on the mode.
Null prefix argument turns off the mode."
;; The initial value.
nil
;; The indicator for the mode line.
" Pyflakes"
;; The minor mode bindings.
'( ([f5] . pyflakes-thisfile) )
)

(add-hook 'python-mode-hook (lambda () (pyflakes-mode t)))

A type-as-go spell-checker like integration

• In vim
– Use the pyflakes.vim plugin:
1. download the zip file from https://www.vim.org/scripts/script.php?script_id=2441
2. extract the files in ~/.vim/ftplugin/python
3. make sure your vimrc has filetype plugin indent on

9.1. Avoiding bugs 351


Scientific Python Lectures, Edition 2024.2rc0.dev0

– Alternatively: use the syntastic plugin. This can be configured to use flake8 too and also
handles on-the-fly checking for many other languages.

• In emacs
Use the flymake mode with pyflakes, documented on https://www.emacswiki.org/emacs/FlyMake
and included in Emacs 26 and more recent. To activate it, use M-x (meta-key then x) and enter
flymake-mode at the prompt. To enable it automatically when opening a Python file, add the
following line to your .emacs file:

(add-hook 'python-mode-hook '(lambda () (flymake-mode)))

9.2 Debugging workflow

If you do have a non trivial bug, this is when debugging strategies kick in. There is no silver bullet. Yet,
strategies help:
For debugging a given problem, the favorable situation is when the problem is
isolated in a small number of lines of code, outside framework or application
code, with short modify-run-fail cycles
1. Make it fail reliably. Find a test case that makes the code fail every time.
2. Divide and Conquer. Once you have a failing test case, isolate the failing code.
• Which module.
• Which function.
• Which line of code.
=> isolate a small reproducible failure: a test case
3. Change one thing at a time and re-run the failing test case.
4. Use the debugger to understand what is going wrong.
5. Take notes and be patient. It may take a while.

Note: Once you have gone through this process: isolated a tight piece of code reproducing the bug
and fix the bug using this piece of code, add the corresponding code to your test suite.

9.2. Debugging workflow 352


Scientific Python Lectures, Edition 2024.2rc0.dev0

9.3 Using the Python debugger

The python debugger, pdb: https://docs.python.org/3/library/pdb.html, allows you to inspect your code
interactively.
Specifically it allows you to:
• View the source code.
• Walk up and down the call stack.
• Inspect values of variables.
• Modify values of variables.
• Set breakpoints.

print

Yes, print statements do work as a debugging tool. However to inspect runtime, it is often more
efficient to use the debugger.

9.3.1 Invoking the debugger

Ways to launch the debugger:


1. Postmortem, launch debugger after module errors.
2. Launch the module with the debugger.
3. Call the debugger inside the module

Postmortem

Situation: You’re working in IPython and you get a traceback.


Here we debug the file index_error.py. When running it, an IndexError is raised. Type %debug and
drop into the debugger.

In [1]: %run index_error.py


---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:10
6 print(lst[len(lst)])
9 if __name__ == "__main__":
---> 10 index_error()

File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:6, in index_


˓→error()

4 def index_error():
5 lst = list("foobar")
----> 6 print(lst[len(lst)])

IndexError: list index out of range

In [2]: %debug
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
˓→py(6)index_error()

4 def index_error():
(continues on next page)

9.3. Using the Python debugger 353


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


5 lst = list("foobar")
----> 6 print(lst[len(lst)])
7
8

ipdb> list
1 """Small snippet to raise an IndexError."""
2
3
4 def index_error():
5 lst = list("foobar")
----> 6 print(lst[len(lst)])
7
8
9 if __name__ == "__main__":
10 index_error()

ipdb> len(lst)
6
ipdb> print(lst[len(lst) - 1])
r
ipdb> quit

Post-mortem debugging without IPython

In some situations you cannot use IPython, for instance to debug a script that wants to be called from
the command line. In this case, you can call the script with python -m pdb script.py:
$ python -m pdb index_error.py
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py(1)
˓→<module>()

-> """Small snippet to raise an IndexError."""


(Pdb) continue
Traceback (most recent call last):
File "/usr/lib64/python3.11/pdb.py", line 1793, in main
pdb._run(target)
File "/usr/lib64/python3.11/pdb.py", line 1659, in _run
self.run(target.code)
File "/usr/lib64/python3.11/bdb.py", line 600, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
˓→py", line 10, in <module>

index_error()
File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
˓→py", line 6, in index_error

print(lst[len(lst)])
~~~^^^^^^^^^^
IndexError: list index out of range
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
˓→py(6)index_error()

-> print(lst[len(lst)])
(Pdb)

9.3. Using the Python debugger 354


Scientific Python Lectures, Edition 2024.2rc0.dev0

Step-by-step execution

Situation: You believe a bug exists in a module but are not sure where.
For instance we are trying to debug wiener_filtering.py. Indeed the code runs, but the filtering does
not work well.
• Run the script in IPython with the debugger using %run -d wiener_filtering.py :

In [1]: %run -d wiener_filtering.py


*** Blank or comment
*** Blank or comment
*** Blank or comment
NOTE: Enter 'c' at the ipdb> prompt to continue execution.
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(1)<module>()

----> 1 """Wiener filtering a noisy raccoon face: this module is buggy"""


2
3 import numpy as np
4 import scipy as sp
5 import matplotlib.pyplot as plt

• Set a break point at line 29 using b 29:

ipdb> n
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(3)<module>()

1 """Wiener filtering a noisy raccoon face: this module is buggy"""


2
----> 3 import numpy as np
4 import scipy as sp
5 import matplotlib.pyplot as plt

ipdb> b 29
Breakpoint 1 at /home/jarrod/src/scientific-python-lectures/advanced/debugging/
˓→wiener_filtering.py:29

• Continue execution to next breakpoint with c(ont(inue)):

ipdb> c
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(29)iterated_wiener()

27 Do not use this: this is crappy code to demo bugs!


28 """
1--> 29 noisy_img = noisy_img
30 denoised_img = local_mean(noisy_img, size=size)
31 l_var = local_var(noisy_img, size=size)

• Step into code with n(ext) and s(tep): next jumps to the next statement in the current execution
context, while step will go across execution contexts, i.e. enable exploring inside function calls:

ipdb> s
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(30)iterated_wiener()

28 """
1 29 noisy_img = noisy_img
---> 30 denoised_img = local_mean(noisy_img, size=size)
31 l_var = local_var(noisy_img, size=size)
32 for i in range(3):
(continues on next page)

9.3. Using the Python debugger 355


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

ipdb> n
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(31)iterated_wiener()

1 29 noisy_img = noisy_img
30 denoised_img = local_mean(noisy_img, size=size)
---> 31 l_var = local_var(noisy_img, size=size)
32 for i in range(3):
33 res = noisy_img - denoised_img

• Step a few lines and explore the local variables:


ipdb> n
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(32)iterated_wiener()

30 denoised_img = local_mean(noisy_img, size=size)


31 l_var = local_var(noisy_img, size=size)
---> 32 for i in range(3):
33 res = noisy_img - denoised_img
34 noise = (res**2).sum() / res.size

ipdb> print(l_var)
[[2571 2782 3474 ... 3008 2922 3141]
[2105 708 475 ... 469 354 2884]
[1697 420 645 ... 273 236 2517]
...
[2437 345 432 ... 413 387 4188]
[2598 179 247 ... 367 441 3909]
[2808 2525 3117 ... 4413 4454 4385]]
ipdb> print(l_var.min())
0

Oh dear, nothing but integers, and 0 variation. Here is our bug, we are doing integer arithmetic.

Raising exception on numerical errors

When we run the wiener_filtering.py file, the following warnings are raised:
In [2]: %run wiener_filtering.py
/home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.
˓→py:35: RuntimeWarning: divide by zero encountered in divide

noise_level = 1 - noise / l_var

We can turn these warnings in exception, which enables us to do post-mortem debugging on them,
and find our problem more quickly:
In [3]: np.seterr(all='raise')
Out[3]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

In [4]: %run wiener_filtering.py


---------------------------------------------------------------------------
FloatingPointError Traceback (most recent call last)
File ~/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:52
49 plt.matshow(face[cut], cmap=plt.cm.gray)
50 plt.matshow(noisy_face[cut], cmap=plt.cm.gray)
---> 52 denoised_face = iterated_wiener(noisy_face)
53 plt.matshow(denoised_face[cut], cmap=plt.cm.gray)
55 plt.show()

9.3. Using the Python debugger 356


Scientific Python Lectures, Edition 2024.2rc0.dev0

File ~/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:35, in␣


˓→iterated_wiener(noisy_img, size)

33 res = noisy_img - denoised_img


34 noise = (res**2).sum() / res.size
---> 35 noise_level = 1 - noise / l_var
36 noise_level[noise_level < 0] = 0
37 denoised_img = np.int64(noise_level * res)

FloatingPointError: divide by zero encountered in divide

Other ways of starting a debugger

• Raising an exception as a poor man break point


If you find it tedious to note the line number to set a break point, you can simply raise an exception
at the point that you want to inspect and use IPython’s %debug. Note that in this case you cannot
step or continue the execution.
• Debugging test failures using nosetests
You can run nosetests --pdb to drop in post-mortem debugging on exceptions, and nosetests
--pdb-failure to inspect test failures using the debugger.
In addition, you can use the IPython interface for the debugger in nose by installing the nose plugin
ipdbplugin. You can than pass --ipdb and --ipdb-failure options to nosetests.
• Calling the debugger explicitly
Insert the following line where you want to drop in the debugger:

import pdb; pdb.set_trace()

Warning: When running nosetests, the output is captured, and thus it seems that the debugger
does not work. Simply run the nosetests with the -s flag.

Graphical debuggers and alternatives

• pudb is a good semi-graphical debugger with a text user interface in the console.
• The Visual Studio Code integrated development environment includes a debugging mode.
• The Mu editor is a simple Python editor that includes a debugging mode.

9.3.2 Debugger commands and interaction

l(list) Lists the code at the current position


u(p) Walk up the call stack
d(own) Walk down the call stack
n(ext) Execute the next line (does not go down in new functions)
s(tep) Execute the next statement (goes down in new functions)
bt Print the call stack
a Print the local variables
!command Execute the given Python command (by opposition to pdb commands

9.3. Using the Python debugger 357


Scientific Python Lectures, Edition 2024.2rc0.dev0

Warning: Debugger commands are not Python code


You cannot name the variables the way you want. For instance, if in you cannot override the variables
in the current frame with the same name: use different names than your local variable when
typing code in the debugger.

Getting help when in the debugger

Type h or help to access the interactive help:

ipdb> help

Documented commands (type help <topic>):


========================================
EOF commands enable ll pp s until
a condition exceptions longlist psource skip_hidden up
alias cont exit n q skip_predicates w
args context h next quit source whatis
b continue help p r step where
break d ignore pdef restart tbreak
bt debug j pdoc return u
c disable jump pfile retval unalias
cl display l pinfo run undisplay
clear down list pinfo2 rv unt

Miscellaneous help topics:


==========================
exec pdb

Undocumented commands:
======================
interact

9.4 Debugging segmentation faults using gdb

If you have a segmentation fault, you cannot debug it with pdb, as it crashes the Python interpreter
before it can drop in the debugger. Similarly, if you have a bug in C code embedded in Python, pdb is
useless. For this we turn to the gnu debugger, gdb, available on Linux.
Before we start with gdb, let us add a few Python-specific tools to it. For this we add a few macros to
our ~/.gdbinit. The optimal choice of macro depends on your Python version and your gdb version. I
have added a simplified version in gdbinit, but feel free to read DebuggingWithGdb.
To debug with gdb the Python script segfault.py, we can run the script in gdb as follows

$ gdb python
...
(gdb) run segfault.py
Starting program: /usr/bin/python segfault.py
[Thread debugging using libthread_db enabled]

Program received signal SIGSEGV, Segmentation fault.


_strided_byte_copy (dst=0x8537478 "\360\343G", outstrides=4, src=
0x86c0690 <Address 0x86c0690 out of bounds>, instrides=32, N=3,
elsize=4)
(continues on next page)

9.4. Debugging segmentation faults using gdb 358


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


at numpy/core/src/multiarray/ctors.c:365
365 _FAST_MOVE(Int32);
(gdb)

We get a segfault, and gdb captures it for post-mortem debugging in the C level stack (not the Python
call stack). We can debug the C call stack using gdb’s commands:

(gdb) up
#1 0x004af4f5 in _copy_from_same_shape (dest=<value optimized out>,
src=<value optimized out>, myfunc=0x496780 <_strided_byte_copy>,
swap=0)
at numpy/core/src/multiarray/ctors.c:748
748 myfunc(dit->dataptr, dest->strides[maxaxis],

As you can see, right now, we are in the C code of numpy. We would like to know what is the Python
code that triggers this segfault, so we go up the stack until we hit the Python execution loop:

(gdb) up
#8 0x080ddd23 in call_function (f=
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/
˓→core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote␣

˓→0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0)

at ../Python/ceval.c:3750
3750 ../Python/ceval.c: No such file or directory.
in ../Python/ceval.c

(gdb) up
#9 PyEval_EvalFrameEx (f=
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/
˓→core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote␣

˓→0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0)

at ../Python/ceval.c:2412
2412 in ../Python/ceval.c
(gdb)

Once we are in the Python execution loop, we can use our special Python helper function. For instance
we can find the corresponding Python code:

(gdb) pyframe
/home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py (158): _
˓→leading_trailing

(gdb)

This is numpy code, we need to go up until we find code that we have written:

(gdb) up
...
(gdb) up
#34 0x080dc97a in PyEval_EvalFrameEx (f=
Frame 0x82f064c, for file segfault.py, line 11, in print_big_array (small_array=
˓→<numpy.ndarray at remote 0x853ecf0>, big_array=<numpy.ndarray at remote 0x853ed20>),

˓→ throwflag=0) at ../Python/ceval.c:1630

1630 ../Python/ceval.c: No such file or directory.


in ../Python/ceval.c
(gdb) pyframe
segfault.py (12): print_big_array

The corresponding code is:

9.4. Debugging segmentation faults using gdb 359


Scientific Python Lectures, Edition 2024.2rc0.dev0

def make_big_array(small_array):
big_array = stride_tricks.as_strided(
small_array, shape=(int(2e6), int(2e6)), strides=(32, 32)
)
return big_array

Thus the segfault happens when printing big_array[-10:]. The reason is simply that big_array has
been allocated with its end outside the program memory.

Note: For a list of Python-specific commands defined in the gdbinit, read the source of this file.

Wrap up exercise

The following script is well documented and hopefully legible. It seeks to answer a problem of actual
interest for numerical computing, but it does not work. . . Can you debug it?
Python source code: to_debug.py

9.4. Debugging segmentation faults using gdb 360


CHAPTER 10
Optimizing code

Donald Knuth

“Premature optimization is the root of all evil”

Author: Gaël Varoquaux


This chapter deals with strategies to make Python code go faster.

Prerequisites

• line_profiler

Chapters contents

• Optimization workflow
• Profiling Python code
– Timeit
– Profiler
– Line-profiler
• Making code go faster
– Algorithmic optimization
∗ Example of the SVD

361
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Writing faster numerical code


– Additional Links

10.1 Optimization workflow

1. Make it work: write the code in a simple legible ways.


2. Make it work reliably: write automated test cases, make really sure that your algorithm is right
and that if you break it, the tests will capture the breakage.
3. Optimize the code by profiling simple use-cases to find the bottlenecks and speeding up these
bottleneck, finding a better algorithm or implementation. Keep in mind that a trade off should
be found between profiling on a realistic example and the simplicity and speed of execution of the
code. For efficient work, it is best to work with profiling runs lasting around 10s.

10.2 Profiling Python code

No optimization without measuring!

• Measure: profiling, timing


• You’ll have surprises: the fastest code is not always what you think

10.2.1 Timeit

In IPython, use timeit (https://docs.python.org/3/library/timeit.html) to time elementary operations:

In [1]: import numpy as np

In [2]: a = np.arange(1000)

In [3]: %timeit a ** 2
867 ns +- 2.86 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)

In [4]: %timeit a ** 2.1


15.3 us +- 24.9 ns per loop (mean +- std. dev. of 7 runs, 100,000 loops each)

In [5]: %timeit a * a
978 ns +- 13.9 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)

Use this to guide your choice between strategies.

Note: For long running calls, using %time instead of %timeit; it is less precise but faster

10.1. Optimization workflow 362


Scientific Python Lectures, Edition 2024.2rc0.dev0

10.2.2 Profiler

Useful when you have a large program to profile, for example the following file:

# For this example to run, you also need the 'ica.py' file

import numpy as np
import scipy as sp

from ica import fastica

# @profile # uncomment this line to run with line_profiler


def test():
rng = np.random.default_rng()
data = rng.random((5000, 100))
u, s, v = sp.linalg.svd(data)
pca = u[:, :10].T @ data
results = fastica(pca.T, whiten=False)

if __name__ == "__main__":
test()

Note: This is a combination of two unsupervised learning techniques, principal component analysis
(PCA) and independent component analysis (ICA). PCA is a technique for dimensionality reduction,
i.e. an algorithm to explain the observed variance in your data using less dimensions. ICA is a source
separation technique, for example to unmix multiple signals that have been recorded through multiple
sensors. Doing a PCA first and then an ICA can be useful if you have more sensors than signals. For
more information see: the FastICA example from scikits-learn.

To run it, you also need to download the ica module. In IPython we can time the script:

In [6]: %run -t demo.py


IPython CPU timings (estimated):
User : 14.3929 s.
System: 0.256016 s.

and profile it:

In [7]: %run -p demo.py


916 function calls in 14.551 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno (function)
1 14.457 14.457 14.479 14.479 decomp.py:849 (svd)
1 0.054 0.054 0.054 0.054 {method 'random_sample' of 'mtrand.
˓→RandomState' objects}

1 0.017 0.017 0.021 0.021 function_base.py:645 (asarray_chkfinite)


54 0.011 0.000 0.011 0.000 {numpy.core._dotblas.dot}
2 0.005 0.002 0.005 0.002 {method 'any' of 'numpy.ndarray' objects}
6 0.001 0.000 0.001 0.000 ica.py:195 (gprime)
6 0.001 0.000 0.001 0.000 ica.py:192 (g)
14 0.001 0.000 0.001 0.000 {numpy.linalg.lapack_lite.dsyevd}
19 0.001 0.000 0.001 0.000 twodim_base.py:204 (diag)
1 0.001 0.001 0.008 0.008 ica.py:69 (_ica_par)
1 0.001 0.001 14.551 14.551 {execfile}
(continues on next page)

10.2. Profiling Python code 363


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


107 0.000 0.000 0.001 0.000 defmatrix.py:239 (__array_finalize__)
7 0.000 0.000 0.004 0.001 ica.py:58 (_sym_decorrelation)
7 0.000 0.000 0.002 0.000 linalg.py:841 (eigh)
172 0.000 0.000 0.000 0.000 {isinstance}
1 0.000 0.000 14.551 14.551 demo.py:1 (<module>)
29 0.000 0.000 0.000 0.000 numeric.py:180 (asarray)
35 0.000 0.000 0.000 0.000 defmatrix.py:193 (__new__)
35 0.000 0.000 0.001 0.000 defmatrix.py:43 (asmatrix)
21 0.000 0.000 0.001 0.000 defmatrix.py:287 (__mul__)
41 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros}
28 0.000 0.000 0.000 0.000 {method 'transpose' of 'numpy.ndarray'␣
˓→objects}

1 0.000 0.000 0.008 0.008 ica.py:97 (fastica)


...

Clearly the svd (in decomp.py) is what takes most of our time, a.k.a. the bottleneck. We have to find a
way to make this step go faster, or to avoid this step (algorithmic optimization). Spending time on the
rest of the code is useless.

Profiling outside of IPython, running ``cProfile``

Similar profiling can be done outside of IPython, simply calling the built-in Python profilers cProfile
and profile.
$ python -m cProfile -o demo.prof demo.py

Using the -o switch will output the profiler results to the file demo.prof to view with an external tool.
This can be useful if you wish to process the profiler output with a visualization tool.

10.2.3 Line-profiler

The profiler tells us which function takes most of the time, but not where it is called.
For this, we use the line_profiler: in the source file, we decorate a few functions that we want to inspect
with @profile (no need to import it)

@profile
def test():
rng = np.random.default_rng()
data = rng.random((5000, 100))
u, s, v = linalg.svd(data)
pca = u[:, :10] @ data
results = fastica(pca.T, whiten=False)

Then we run the script using the kernprof command, with switches -l, --line-by-line and -v,
--view to use the line-by-line profiler and view the results in addition to saving them:

$ kernprof -l -v demo.py

Wrote profile results to demo.py.lprof


Timer unit: 1e-06 s

Total time: 1.27874 s


File: demo.py
Function: test at line 9
(continues on next page)

10.2. Profiling Python code 364


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

Line # Hits Time Per Hit % Time Line Contents


==============================================================
9 @profile
10 def test():
11 1 69.0 69.0 0.0 rng = np.random.default_rng()
12 1 2453.0 2453.0 0.2 data = rng.random((5000, 100))
13 1 1274715.0 1274715.0 99.7 u, s, v = sp.linalg.svd(data)
14 1 413.0 413.0 0.0 pca = u[:, :10].T @ data
15 1 1094.0 1094.0 0.1 results = fastica(pca.T,␣
˓→whiten=False)

The SVD is taking all the time. We need to optimise this line.

10.3 Making code go faster

Once we have identified the bottlenecks, we need to make the corresponding code go faster.

10.3.1 Algorithmic optimization

The first thing to look for is algorithmic optimization: are there ways to compute less, or better?
For a high-level view of the problem, a good understanding of the maths behind the algorithm helps.
However, it is not uncommon to find simple changes, like moving computation or memory allocation
outside a for loop, that bring in big gains.

Example of the SVD

In both examples above, the SVD - Singular Value Decomposition - is what takes most of the time.
Indeed, the computational cost of this algorithm is roughly 𝑛3 in the size of the input matrix.
However, in both of these example, we are not using all the output of the SVD, but only the first few rows
of its first return argument. If we use the svd implementation of SciPy, we can ask for an incomplete
version of the SVD. Note that implementations of linear algebra in SciPy are richer then those in NumPy
and should be preferred.

In [8]: %timeit np.linalg.svd(data)


1 loops, best of 3: 14.5 s per loop

In [9]: import scipy as sp

In [10]: %timeit sp.linalg.svd(data)


1 loops, best of 3: 14.2 s per loop

In [11]: %timeit sp.linalg.svd(data, full_matrices=False)


1 loops, best of 3: 295 ms per loop

In [12]: %timeit np.linalg.svd(data, full_matrices=False)


1 loops, best of 3: 293 ms per loop

We can then use this insight to optimize the previous code:

def test():
rng = np.random.default_rng()
(continues on next page)

10.3. Making code go faster 365


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


data = rng.random((5000, 100))
u, s, v = sp.linalg.svd(data, full_matrices=False)
pca = u[:, :10].T @ data
results = fastica(pca.T, whiten=False)

In [13]: import demo

In [14]: %timeit demo.


demo.fastica demo.np demo.prof.pdf demo.py demo.pyc
demo.linalg demo.prof demo.prof.png demo.py.lprof demo.test

In [15]: %timeit demo.test()


ica.py:65: RuntimeWarning: invalid value encountered in sqrt
W = (u * np.diag(1.0/np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W
1 loops, best of 3: 17.5 s per loop

In [16]: import demo_opt

In [17]: %timeit demo_opt.test()


1 loops, best of 3: 208 ms per loop

Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can be computed with arpack,
available in scipy.sparse.linalg.eigsh.

Computational linear algebra

For certain algorithms, many of the bottlenecks will be linear algebra computations. In this case,
using the right function to solve the right problem is key. For instance, an eigenvalue problem with
a symmetric matrix is easier to solve than with a general matrix. Also, most often, you can avoid
inverting a matrix and use a less costly (and more numerically stable) operation.
Know your computational linear algebra. When in doubt, explore scipy.linalg, and use %timeit to
try out different alternatives on your data.

10.4 Writing faster numerical code

A complete discussion on advanced use of NumPy is found in chapter Advanced NumPy, or in the article
The NumPy array: a structure for efficient numerical computation by van der Walt et al. Here we discuss
only some commonly encountered tricks to make code faster.
• Vectorizing for loops
Find tricks to avoid for loops using NumPy arrays. For this, masks and indices arrays can be
useful.
• Broadcasting
Use broadcasting to do operations on arrays as small as possible before combining them.
• In place operations

In [18]: a = np.zeros(1e7)

In [19]: %timeit global a ; a = 0*a


10 loops, best of 3: 111 ms per loop

(continues on next page)

10.4. Writing faster numerical code 366


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


In [20]: %timeit global a ; a *= 0
10 loops, best of 3: 48.4 ms per loop

note: we need global a in the timeit so that it work, as it is assigning to a, and thus considers it
as a local variable.
• Be easy on the memory: use views, and not copies
Copying big arrays is as costly as making simple numerical operations on them:

In [21]: a = np.zeros(1e7)

In [22]: %timeit a.copy()


10 loops, best of 3: 124 ms per loop

In [23]: %timeit a + 1
10 loops, best of 3: 112 ms per loop

• Beware of cache effects


Memory access is cheaper when it is grouped: accessing a big array in a continuous way is much
faster than random access. This implies amongst other things that smaller strides are faster
(see CPU cache effects):

In [24]: c = np.zeros((1e4, 1e4), order='C')

In [25]: %timeit c.sum(axis=0)


1 loops, best of 3: 3.89 s per loop

In [26]: %timeit c.sum(axis=1)


1 loops, best of 3: 188 ms per loop

In [27]: c.strides
Out[27]: (80000, 8)

This is the reason why Fortran ordering or C ordering may make a big difference on operations:

In [28]: rng = np.random.default_rng()

In [29]: a = rng.random((20, 2**18))

In [30]: b = rng.random((20, 2**18))

In [31]: %timeit b @ a.T


8.1 ms +- 14.6 us per loop (mean +- std. dev. of 7 runs, 100 loops each)

In [32]: c = np.ascontiguousarray(a.T)

In [33]: %timeit b @ c
8.04 ms +- 23.8 us per loop (mean +- std. dev. of 7 runs, 100 loops each)

Note that copying the data to work around this effect may not be worth it:

In [34]: %timeit c = np.ascontiguousarray(a.T)


16.5 ms +- 192 us per loop (mean +- std. dev. of 7 runs, 100 loops each)

Using numexpr can be useful to automatically optimize code for such effects.
• Use compiled code

10.4. Writing faster numerical code 367


Scientific Python Lectures, Edition 2024.2rc0.dev0

The last resort, once you are sure that all the high-level optimizations have been explored, is to
transfer the hot spots, i.e. the few lines or functions in which most of the time is spent, to compiled
code. For compiled code, the preferred option is to use Cython: it is easy to transform exiting
Python code in compiled code, and with a good use of the NumPy support yields efficient code on
NumPy arrays, for instance by unrolling loops.

Warning: For all the above: profile and time your choices. Don’t base your optimization on
theoretical considerations.

10.4.1 Additional Links

• If you need to profile memory usage, you could try the memory_profiler
• If you need to profile down into C extensions, you could try using gperftools from Python with
yep.
• If you would like to track performance of your code across time, i.e. as you make new commits to
your repository, you could try: asv
• If you need some interactive visualization why not try RunSnakeRun

10.4. Writing faster numerical code 368


CHAPTER 11
Sparse Arrays in SciPy

Author: Robert Cimrman

11.1 Introduction

(dense) matrix is:


• mathematical object
• data structure for storing a 2D array of values
important features:
• memory allocated once for all items
– usually a contiguous chunk, think NumPy ndarray
• fast access to individual items (*)

369
Scientific Python Lectures, Edition 2024.2rc0.dev0

11.1.1 Why Sparse Matrices?

• the memory grows like n**2 for dense matrix


• small example (double precision matrix):

>>> import numpy as np


>>> import matplotlib.pyplot as plt
>>> x = np.linspace(0, 1e6, 10)
>>> plt.plot(x, 8.0 * (x**2) / 1e6, lw=5)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel('size n')
Text(...'size n')
>>> plt.ylabel('memory [MB]')
Text(...'memory [MB]')

11.1.2 Sparse Matrices vs. Sparse Matrix Storage Schemes

• sparse matrix is a matrix, which is almost empty


• storing all the zeros is wasteful -> store only nonzero items
• think compression
• pros: huge memory savings
• cons: slow access to individual items, but it depends on actual storage scheme.

11.1.3 Typical Applications

• solution of partial differential equations (PDEs)


– the finite element method
– mechanical engineering, electrotechnics, physics, . . .
• graph theory
– nonzero at (i, j) means that node i is connected to node j
• natural language processing
– nonzero at (i, j) means that the document i contains the word j
• ...

11.1.4 Prerequisites

• numpy
• scipy
• matplotlib (optional)
• ipython (the enhancements come handy)

11.1. Introduction 370


Scientific Python Lectures, Edition 2024.2rc0.dev0

11.1.5 Sparsity Structure Visualization

• spy() from matplotlib


• example plots:

11.1. Introduction 371


Scientific Python Lectures, Edition 2024.2rc0.dev0

11.2 Storage Schemes

• seven sparse array types in scipy.sparse:


1. csr_array: Compressed Sparse Row format
2. csc_array: Compressed Sparse Column format
3. bsr_array: Block Sparse Row format
4. lil_array: List of Lists format
5. dok_array: Dictionary of Keys format
6. coo_array: COOrdinate format (aka IJV, triplet format)
7. dia_array: DIAgonal format
• each suitable for some tasks
• many employ sparsetools C++ module by Nathan Bell
• assume the following is imported:

>>> import numpy as np


>>> import scipy as sp
>>> import matplotlib.pyplot as plt

• warning for Numpy users:


– passing a sparse array object to NumPy functions that expect ndarray/matrix does not
work. Use sparse functions.
– the older csr_matrix classes use ‘*’ for matrix multiplication (dot product) and
‘A.multiply(B)’ for elementwise multiplication.
– the newer csr_array uses ‘@’ for dot product and ‘*’ for elementwise multiplication
– sparse arrays can be 1D or 2D, but not nD for n > 2 (unlike Numpy arrays).

11.2.1 Common Methods

• all scipy.sparse array classes are subclasses of sparray


– default implementation of arithmetic operations
∗ always converts to CSR
∗ subclasses override for efficiency
– shape, data type, set/get
– indices of nonzero values in the array
– format conversion, interaction with NumPy (toarray())
– ...
• attributes:
– mtx.T - transpose (same as mtx.transpose())
– mtx.real - real part of complex matrix
– mtx.imag - imaginary part of complex matrix
– mtx.size - the number of nonzeros (same as self.getnnz())
– mtx.shape - the number of rows and columns (tuple)

11.2. Storage Schemes 372


Scientific Python Lectures, Edition 2024.2rc0.dev0

• data and indices usually stored in 1D NumPy arrays

11.2.2 Sparse Array Classes

Diagonal Format (DIA)

• very simple scheme


• diagonals in dense NumPy array of shape (n_diag, length)
– fixed length -> waste space a bit when far from main diagonal
– subclass of _data_matrix (sparse array classes with .data attribute)
• offset for each diagonal
– 0 is the main diagonal
– negative offset = below
– positive offset = above
• fast matrix * vector (sparsetools)
• fast and easy item-wise operations
– manipulate data array directly (fast NumPy machinery)
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty array)
– (data, offsets) tuple
• no slicing, no individual item access
• use:
– rather specialized
– solving PDEs by finite differences
– with an iterative solver

Examples

• create some DIA arrays:

>>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)


>>> data
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
>>> offsets = np.array([0, -1, 2])
>>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4))
>>> mtx
<4x4 sparse array of type '<... 'numpy.int64'>'
with 9 stored elements (3 diagonals) in DIAgonal format>
>>> mtx.toarray()
array([[1, 0, 3, 0],
[1, 2, 0, 4],
(continues on next page)

11.2. Storage Schemes 373


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[0, 2, 3, 0],
[0, 0, 3, 4]])

>>> data = np.arange(12).reshape((3, 4)) + 1


>>> data
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4))
>>> mtx.data
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> mtx.offsets
array([ 0, -1, 2], dtype=int32)
>>> print(mtx)
(0, 0) 1
(1, 1) 2
(2, 2) 3
(3, 3) 4
(1, 0) 5
(2, 1) 6
(3, 2) 7
(0, 2) 11
(1, 3) 12
>>> mtx.toarray()
array([[ 1, 0, 11, 0],
[ 5, 2, 0, 12],
[ 0, 6, 3, 0],
[ 0, 0, 7, 4]])

• explanation with a scheme:

offset: row

2: 9
1: --10------
0: 1 . 11 .
-1: 5 2 . 12
-2: . 6 3 .
-3: . . 7 4
---------8

• matrix-vector multiplication

>>> vec = np.ones((4, ))


>>> vec
array([1., 1., 1., 1.])
>>> mtx @ vec
array([12., 19., 9., 11.])
>>> (mtx * vec).toarray()
array([[ 1., 0., 11., 0.],
[ 5., 2., 0., 12.],
[ 0., 6., 3., 0.],
[ 0., 0., 7., 4.]])

11.2. Storage Schemes 374


Scientific Python Lectures, Edition 2024.2rc0.dev0

List of Lists Format (LIL)

• row-based linked list


– each row is a Python list (sorted) of column indices of non-zero elements
– rows stored in a NumPy array (dtype=np.object)
– non-zero values data stored analogously
• efficient for constructing sparse arrays incrementally
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty array)
• flexible slicing, changing sparsity structure is efficient
• slow arithmetic, slow column slicing due to being row-based
• use:
– when sparsity pattern is not known apriori or changes
– example: reading a sparse array from a text file

Examples

• create an empty LIL array:

>>> mtx = sp.sparse.lil_array((4, 5))

• prepare random data:

>>> rng = np.random.default_rng(27446968)


>>> data = np.round(rng.random((2, 3)))
>>> data
array([[1., 0., 1.],
[0., 0., 1.]])

• assign the data using fancy indexing:

>>> mtx[:2, [1, 2, 3]] = data


>>> mtx
<4x5 sparse array of type '<... 'numpy.float64'>'
with 3 stored elements in List of Lists format>
>>> print(mtx)
(0, 1) 1.0
(0, 3) 1.0
(1, 3) 1.0
>>> mtx.toarray()
array([[0., 1., 0., 1., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> mtx.toarray()
array([[0., 1., 0., 1., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])

11.2. Storage Schemes 375


Scientific Python Lectures, Edition 2024.2rc0.dev0

• more slicing and indexing:

>>> mtx = sp.sparse.lil_array([[0, 1, 2, 0], [3, 0, 1, 0], [1, 0, 0, 1]])


>>> mtx.toarray()
array([[0, 1, 2, 0],
[3, 0, 1, 0],
[1, 0, 0, 1]]...)
>>> print(mtx)
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 2) 1
(2, 0) 1
(2, 3) 1
>>> mtx[:2, :]
<2x4 sparse array of type '<... 'numpy.int64'>'
with 4 stored elements in List of Lists format>
>>> mtx[:2, :].toarray()
array([[0, 1, 2, 0],
[3, 0, 1, 0]]...)
>>> mtx[1:2, [0,2]].toarray()
array([[3, 1]]...)
>>> mtx.toarray()
array([[0, 1, 2, 0],
[3, 0, 1, 0],
[1, 0, 0, 1]]...)

Dictionary of Keys Format (DOK)

• subclass of Python dict


– keys are (row, column) index tuples (no duplicate entries allowed)
– values are corresponding non-zero values
• efficient for constructing sparse arrays incrementally
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty array)
• efficient O(1) access to individual elements
• flexible slicing, changing sparsity structure is efficient
• can be efficiently converted to a coo_array once constructed
• slow arithmetic (for loops with dict.items())
• use:
– when sparsity pattern is not known apriori or changes

11.2. Storage Schemes 376


Scientific Python Lectures, Edition 2024.2rc0.dev0

Examples

• create a DOK array element by element:

>>> mtx = sp.sparse.dok_array((5, 5), dtype=np.float64)


>>> mtx
<5x5 sparse array of type '<... 'numpy.float64'>'
with 0 stored elements in Dictionary Of Keys format>
>>> for ir in range(5):
... for ic in range(5):
... mtx[ir, ic] = 1.0 * (ir != ic)
>>> mtx
<5x5 sparse array of type '<... 'numpy.float64'>'
with 20 stored elements in Dictionary Of Keys format>
>>> mtx.toarray()
array([[0., 1., 1., 1., 1.],
[1., 0., 1., 1., 1.],
[1., 1., 0., 1., 1.],
[1., 1., 1., 0., 1.],
[1., 1., 1., 1., 0.]])

• slicing and indexing:

>>> mtx[1, 1]
0.0
>>> mtx[[1], 1:3]
<1x2 sparse array of type '<... 'numpy.float64'>'
with 1 stored elements in Dictionary Of Keys format>
>>> mtx[[1], 1:3].toarray()
array([[0., 1.]])
>>> mtx[[2, 1], 1:3].toarray()
array([[1., 0.],
[0., 1.]])

Coordinate Format (COO)

• also known as the ‘ijv’ or ‘triplet’ format


– three NumPy arrays: row, col, data.
– attribute coords is the tuple (row, col)
– data[i] is value at (row[i], col[i]) position
– permits duplicate entries
– subclass of _data_matrix (sparse matrix classes with .data attribute)
• fast format for constructing sparse arrays
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty matrix)
– (data, coords) tuple
• very fast conversion to and from CSR/CSC formats

11.2. Storage Schemes 377


Scientific Python Lectures, Edition 2024.2rc0.dev0

• fast matrix * vector (sparsetools)


• fast and easy item-wise operations
– manipulate data array directly (fast NumPy machinery)
• no slicing, no arithmetic (directly, converts to CSR)
• use:
– facilitates fast conversion among sparse formats
– when converting to other format (usually CSR or CSC), duplicate entries are summed
together
∗ facilitates efficient construction of finite element matrices

Examples

• create empty COO array:

>>> mtx = sp.sparse.coo_array((3, 4), dtype=np.int8)


>>> mtx.toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)

• create using (data, ij) tuple:

>>> row = np.array([0, 3, 1, 0])


>>> col = np.array([0, 3, 1, 2])
>>> data = np.array([4, 5, 7, 9])
>>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4))
>>> mtx
<4x4 sparse array of type '<... 'numpy.int64'>'
with 4 stored elements in COOrdinate format>
>>> mtx.toarray()
array([[4, 0, 9, 0],
[0, 7, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 5]])

• duplicates entries are summed together:

>>> row = np.array([0, 0, 1, 3, 1, 0, 0])


>>> col = np.array([0, 2, 1, 3, 1, 0, 0])
>>> data = np.array([1, 1, 1, 1, 1, 1, 1])
>>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4))
>>> mtx.toarray()
array([[3, 0, 1, 0],
[0, 2, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]])

• no slicing. . . :

>>> mtx[2, 3]
Traceback (most recent call last):
...
TypeError: 'coo_array' object ...

11.2. Storage Schemes 378


Scientific Python Lectures, Edition 2024.2rc0.dev0

Compressed Sparse Row Format (CSR)

• row oriented
– three NumPy arrays: indices, indptr, data
∗ indices is array of column indices
∗ data is array of corresponding nonzero values
∗ indptr points to row starts in indices and data
∗ length of indptr is n_row + 1, last item = number of values = length of both
indices and data
∗ nonzero values of the i-th row are data[indptr[i]:indptr[i + 1]] with column indices
indices[indptr[i]:indptr[i + 1]]
∗ item (i, j) can be accessed as data[indptr[i] + k], where k is position of j in in-
dices[indptr[i]:indptr[i + 1]]
– subclass of _cs_matrix (common CSR/CSC functionality)
∗ subclass of _data_matrix (sparse array classes with .data attribute)
• fast matrix vector products and other arithmetic (sparsetools)
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty array)
– (data, coords) tuple
– (data, indices, indptr) tuple
• efficient row slicing, row-oriented operations
• slow column slicing, expensive changes to the sparsity structure
• use:
– actual computations (most linear solvers support this format)

Examples

• create empty CSR array:


>>> mtx = sp.sparse.csr_array((3, 4), dtype=np.int8)
>>> mtx.toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)

• create using (data, coords) tuple:

>>> row = np.array([0, 0, 1, 2, 2, 2])


>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> mtx = sp.sparse.csr_array((data, (row, col)), shape=(3, 3))
>>> mtx
<3x3 sparse array of type '<... 'numpy.int64'>'
with 6 stored elements in Compressed Sparse Row format>
>>> mtx.toarray()
(continues on next page)

11.2. Storage Schemes 379


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]]...)
>>> mtx.data
array([1, 2, 3, 4, 5, 6]...)
>>> mtx.indices
array([0, 2, 2, 0, 1, 2])
>>> mtx.indptr
array([0, 2, 3, 6])

• create using (data, indices, indptr) tuple:

>>> data = np.array([1, 2, 3, 4, 5, 6])


>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> indptr = np.array([0, 2, 3, 6])
>>> mtx = sp.sparse.csr_array((data, indices, indptr), shape=(3, 3))
>>> mtx.toarray()
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])

Compressed Sparse Column Format (CSC)

• column oriented
– three NumPy arrays: indices, indptr, data
∗ indices is array of row indices
∗ data is array of corresponding nonzero values
∗ indptr points to column starts in indices and data
∗ length is n_col + 1, last item = number of values = length of both indices and
data
∗ nonzero values of the i-th column are data[indptr[i]:indptr[i+1]] with row indices
indices[indptr[i]:indptr[i+1]]
∗ item (i, j) can be accessed as data[indptr[j]+k], where k is position of i in in-
dices[indptr[j]:indptr[j+1]]
– subclass of _cs_matrix (common CSR/CSC functionality)
∗ subclass of _data_matrix (sparse array classes with .data attribute)
• fast matrix vector products and other arithmetic (sparsetools)
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty array)
– (data, coords) tuple
– (data, indices, indptr) tuple
• efficient column slicing, column-oriented operations
• slow row slicing, expensive changes to the sparsity structure

11.2. Storage Schemes 380


Scientific Python Lectures, Edition 2024.2rc0.dev0

• use:
– actual computations (most linear solvers support this format)

Examples

• create empty CSC array:

>>> mtx = sp.sparse.csc_array((3, 4), dtype=np.int8)


>>> mtx.toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)

• create using (data, coords) tuple:

>>> row = np.array([0, 0, 1, 2, 2, 2])


>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> mtx = sp.sparse.csc_array((data, (row, col)), shape=(3, 3))
>>> mtx
<3x3 sparse array of type '<... 'numpy.int64'>'
with 6 stored elements in Compressed Sparse Column format>
>>> mtx.toarray()
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]]...)
>>> mtx.data
array([1, 4, 5, 2, 3, 6]...)
>>> mtx.indices
array([0, 2, 2, 0, 1, 2])
>>> mtx.indptr
array([0, 2, 3, 6])

• create using (data, indices, indptr) tuple:

>>> data = np.array([1, 4, 5, 2, 3, 6])


>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> indptr = np.array([0, 2, 3, 6])
>>> mtx = sp.sparse.csc_array((data, indices, indptr), shape=(3, 3))
>>> mtx.toarray()
array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]])

Block Compressed Row Format (BSR)

• basically a CSR with dense sub-matrices of fixed shape instead of scalar items
– block size (R, C) must evenly divide the shape of the matrix (M, N)
– three NumPy arrays: indices, indptr, data
∗ indices is array of column indices for each block
∗ data is array of corresponding nonzero values of shape (nnz, R, C)
∗ ...

11.2. Storage Schemes 381


Scientific Python Lectures, Edition 2024.2rc0.dev0

– subclass of _cs_matrix (common CSR/CSC functionality)


∗ subclass of _data_matrix (sparse matrix classes with .data attribute)
• fast matrix vector products and other arithmetic (sparsetools)
• constructor accepts:
– dense array/matrix
– sparse array/matrix
– shape tuple (create empty array)
– (data, coords) tuple
– (data, indices, indptr) tuple
• many arithmetic operations considerably more efficient than CSR for sparse matrices with dense
sub-matrices
• use:
– like CSR
– vector-valued finite element discretizations

Examples

• create empty BSR array with (1, 1) block size (like CSR. . . ):

>>> mtx = sp.sparse.bsr_array((3, 4), dtype=np.int8)


>>> mtx
<3x4 sparse array of type '<... 'numpy.int8'>'
with 0 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> mtx.toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)

• create empty BSR array with (3, 2) block size:

>>> mtx = sp.sparse.bsr_array((3, 4), blocksize=(3, 2), dtype=np.int8)


>>> mtx
<3x4 sparse array of type '<... 'numpy.int8'>'
with 0 stored elements (blocksize = 3x2) in Block Sparse Row format>
>>> mtx.toarray()
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)

– a bug?
• create using (data, coords) tuple with (1, 1) block size (like CSR. . . ):

>>> row = np.array([0, 0, 1, 2, 2, 2])


>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> mtx = sp.sparse.bsr_array((data, (row, col)), shape=(3, 3))
>>> mtx
<3x3 sparse array of type '<... 'numpy.int64'>'
with 6 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> mtx.toarray()
(continues on next page)

11.2. Storage Schemes 382


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


array([[1, 0, 2],
[0, 0, 3],
[4, 5, 6]]...)
>>> mtx.data
array([[[1]],

[[2]],

[[3]],

[[4]],

[[5]],

[[6]]]...)
>>> mtx.indices
array([0, 2, 2, 0, 1, 2])
>>> mtx.indptr
array([0, 2, 3, 6])

• create using (data, indices, indptr) tuple with (2, 2) block size:

>>> indptr = np.array([0, 2, 3, 6])


>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
>>> mtx = sp.sparse.bsr_array((data, indices, indptr), shape=(6, 6))
>>> mtx.toarray()
array([[1, 1, 0, 0, 2, 2],
[1, 1, 0, 0, 2, 2],
[0, 0, 0, 0, 3, 3],
[0, 0, 0, 0, 3, 3],
[4, 4, 5, 5, 6, 6],
[4, 4, 5, 5, 6, 6]])
>>> data
array([[[1, 1],
[1, 1]],

[[2, 2],
[2, 2]],

[[3, 3],
[3, 3]],

[[4, 4],
[4, 4]],

[[5, 5],
[5, 5]],

[[6, 6],
[6, 6]]])

11.2. Storage Schemes 383


Scientific Python Lectures, Edition 2024.2rc0.dev0

11.2.3 Summary

Table 1: Summary of storage schemes.


format matrix get fancy set item fancy solvers note
* vector item get set
CSR sparse- yes yes slow . any has data array, fast row-wise
tools ops
CSC sparse- yes yes slow . any has data array, fast column-
tools wise ops
BSR sparse- . . . . special- has data array, specialized
tools ized
COO sparse- . . . . itera- has data array, facilitates
tools tive fast conversion
DIA sparse- . . . . itera- has data array, specialized
tools tive
LIL via yes yes yes yes itera- arithmetic via CSR, incre-
CSR tive mental construction
DOK python yes one yes yes itera- O(1) item access, incremen-
axis tive tal construction, slow arith-
only metic

11.3 Linear System Solvers

• sparse matrix/eigenvalue problem solvers live in scipy.sparse.linalg


• the submodules:
– dsolve: direct factorization methods for solving linear systems
– isolve: iterative methods for solving linear systems
– eigen: sparse eigenvalue problem solvers
• all solvers are accessible from:

>>> import scipy as sp


>>> sp.sparse.linalg.__all__
['ArpackError', 'ArpackNoConvergence', ..., 'use_solver']

11.3.1 Sparse Direct Solvers

• default solver: SuperLU


– included in SciPy
– real and complex systems
– both single and double precision
• optional: umfpack
– real and complex systems
– double precision only
– recommended for performance

11.3. Linear System Solvers 384


Scientific Python Lectures, Edition 2024.2rc0.dev0

– wrappers now live in scikits.umfpack


– check-out the new scikits.suitesparse by Nathaniel Smith

Examples

• import the whole module, and see its docstring:

>>> help(sp.sparse.linalg.spsolve)
Help on function spsolve in module scipy.sparse.linalg._dsolve.linsolve:
...

• both superlu and umfpack can be used (if the latter is installed) as follows:
– prepare a linear system:

>>> import numpy as np


>>> mtx = sp.sparse.spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5,␣
˓→5, "csc")

>>> mtx.toarray()
array([[ 1, 5, 0, 0, 0],
[ 0, 2, 8, 0, 0],
[ 0, 0, 3, 9, 0],
[ 0, 0, 0, 4, 10],
[ 0, 0, 0, 0, 5]])
>>> rhs = np.array([1, 2, 3, 4, 5], dtype=np.float32)

– solve as single precision real:

>>> mtx1 = mtx.astype(np.float32)


>>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False)
>>> print(x)
[106. -21. 5.5 -1.5 1. ]
>>> print("Error: %s " % (mtx1 * x - rhs))
Error: [0. 0. 0. 0. 0.]

– solve as double precision real:

>>> mtx2 = mtx.astype(np.float64)


>>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True)
>>> print(x)
[106. -21. 5.5 -1.5 1. ]
>>> print("Error: %s " % (mtx2 * x - rhs))
Error: [0. 0. 0. 0. 0.]

– solve as single precision complex:

>>> mtx1 = mtx.astype(np.complex64)


>>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False)
>>> print(x)
[106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j]
>>> print("Error: %s " % (mtx1 * x - rhs))
Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]

– solve as double precision complex:

>>> mtx2 = mtx.astype(np.complex128)


>>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True)
>>> print(x)
(continues on next page)

11.3. Linear System Solvers 385


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j]
>>> print("Error: %s " % (mtx2 * x - rhs))
Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]

"""
Solve a linear system
=======================

Construct a 1000x1000 lil_array and add some values to it, convert it


to CSR format and solve A x = b for x:and solve a linear system with a
direct solver.
"""

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

mtx = sp.sparse.lil_array((1000, 1000), dtype=np.float64)


mtx[0, :100] = rng.random(100)
mtx[1, 100:200] = mtx[0, :100]
mtx.setdiag(rng.random(1000))

plt.clf()
plt.spy(mtx, marker=".", markersize=2)
plt.show()

mtx = mtx.tocsr()
rhs = rng.random(1000)

x = sp.sparse.linalg.spsolve(mtx, rhs)

print(f"residual: { np.linalg.norm(mtx * x - rhs)!r} ")

• examples/direct_solve.py

11.3.2 Iterative Solvers

• the isolve module contains the following solvers:


– bicg (BIConjugate Gradient)
– bicgstab (BIConjugate Gradient STABilized)
– cg (Conjugate Gradient) - symmetric positive definite matrices only
– cgs (Conjugate Gradient Squared)
– gmres (Generalized Minimal RESidual)
– minres (MINimum RESidual)
– qmr (Quasi-Minimal Residual)

11.3. Linear System Solvers 386


Scientific Python Lectures, Edition 2024.2rc0.dev0

Common Parameters

• mandatory:
A
[{sparse array/matrix, dense array/matrix, LinearOperator}] The N-by-N matrix of the linear
system.
b
[{array, matrix}] Right hand side of the linear system. Has shape (N,) or (N,1).
• optional:
x0
[{array, matrix}] Starting guess for the solution.
tol
[float] Relative tolerance to achieve before terminating.
maxiter
[integer] Maximum number of iterations. Iteration will stop after maxiter steps even if the
specified tolerance has not been achieved.
M
[{sparse array/matrix, dense array/matrix, LinearOperator}] Preconditioner for A. The pre-
conditioner should approximate the inverse of A. Effective preconditioning dramatically im-
proves the rate of convergence, which implies that fewer iterations are needed to reach a given
error tolerance.
callback
[function] User-supplied function to call after each iteration. It is called as callback(xk), where
xk is the current solution vector.

LinearOperator Class

• common interface for performing matrix vector products


• useful abstraction that enables using dense and sparse matrices within the solvers, as well as
matrix-free solutions
• has shape and matvec() (+ some optional parameters)
• example:

>>> import numpy as np


>>> import scipy as sp
>>> def mv(v):
... return np.array([2 * v[0], 3 * v[1]])
...
>>> A = sp.sparse.linalg.LinearOperator((2, 2), matvec=mv)
>>> A
<2x2 _CustomLinearOperator with dtype=float64>
>>> A.matvec(np.ones(2))
array([2., 3.])
>>> A * np.ones(2)
array([2., 3.])

11.3. Linear System Solvers 387


Scientific Python Lectures, Edition 2024.2rc0.dev0

A Few Notes on Preconditioning

• problem specific
• often hard to develop
• if not sure, try ILU
– available in scipy.sparse.linalg as spilu()

11.3.3 Eigenvalue Problem Solvers

The eigen module

• arpack * a collection of Fortran77 subroutines designed to solve large scale eigenvalue problems
• lobpcg (Locally Optimal Block Preconditioned Conjugate Gradient Method) * works very well in
combination with PyAMG * example by Nathan Bell:

"""
Compute eigenvectors and eigenvalues using a preconditioned eigensolver
=======================================================================

In this example Smoothed Aggregation (SA) is used to precondition


the LOBPCG eigensolver on a two-dimensional Poisson problem with
Dirichlet boundary conditions.
"""

import scipy as sp
import matplotlib.pyplot as plt

from pyamg import smoothed_aggregation_solver


from pyamg.gallery import poisson

N = 100
K = 9
A = poisson((N, N), format="csr")

# create the AMG hierarchy


ml = smoothed_aggregation_solver(A)

# initial approximation to the K eigenvectors


X = sp.rand(A.shape[0], K)

# preconditioner based on ml
M = ml.aspreconditioner()

# compute eigenvalues and eigenvectors with LOBPCG


W, V = sp.sparse.linalg.lobpcg(A, X, M=M, tol=1e-8, largest=False)

# plot the eigenvectors


plt.figure(figsize=(9, 9))

for i in range(K):
plt.subplot(3, 3, i + 1)
plt.title("Eigenvector %d " % i)
plt.pcolor(V[:, i].reshape(N, N))
(continues on next page)

11.3. Linear System Solvers 388


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.axis("equal")
plt.axis("off")
plt.show()

– examples/pyamg_with_lobpcg.py
• example by Nils Wagner:
– examples/lobpcg_sakurai.py
• output:

$ python examples/lobpcg_sakurai.py
Results by LOBPCG for n=2500

[ 0.06250083 0.06250028 0.06250007]

Exact eigenvalues

[ 0.06250005 0.0625002 0.06250044]

Elapsed time 7.01

11.3. Linear System Solvers 389


Scientific Python Lectures, Edition 2024.2rc0.dev0

11.4 Other Interesting Packages

• PyAMG
– algebraic multigrid solvers
– https://github.com/pyamg/pyamg
• Pysparse
– own sparse matrix classes
– matrix and eigenvalue problem solvers
– https://pysparse.sourceforge.net/

11.4. Other Interesting Packages 390


CHAPTER 12
Image manipulation and processing
using NumPy and SciPy

Authors: Emmanuelle Gouillart, Gaël Varoquaux


This section addresses basic image manipulation and processing using the core scientific modules NumPy
and SciPy. Some of the operations covered by this tutorial may be useful for other kinds of multidimen-
sional array processing than image processing. In particular, the submodule scipy.ndimage provides
functions operating on n-dimensional NumPy arrays.
See also:
For more advanced image processing and image-specific routines, see the tutorial scikit-image: image
processing, dedicated to the skimage module.

Image = 2-D numerical array

(or 3-D: CT, MRI, 2D + time; 4-D, . . . )


Here, image == NumPy array np.array

Tools used in this tutorial:


• numpy: basic array manipulation
• scipy: scipy.ndimage submodule dedicated to image processing (n-dimensional images). See the
documentation:

>>> import scipy as sp

Common tasks in image processing:

391
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Input/Output, displaying images


• Basic manipulations: cropping, flipping, rotating, . . .
• Image filtering: denoising, sharpening
• Image segmentation: labeling pixels corresponding to different objects
• Classification
• Feature extraction
• Registration
• ...

Chapters contents

• Opening and writing to image files


• Displaying images
• Basic manipulations
– Statistical information
– Geometrical transformations
• Image filtering
– Blurring/smoothing
– Sharpening
– Denoising
– Mathematical morphology
• Feature extraction
– Edge detection
– Segmentation
• Measuring objects properties: scipy.ndimage.measurements
• Full code examples
• Examples for the image processing chapter

12.1 Opening and writing to image files

Writing an array to a file:

import scipy as sp
import imageio.v3 as iio

f = sp.datasets.face()
iio.imwrite("face.png", f) # uses the Image module (PIL)

import matplotlib.pyplot as plt

plt.imshow(f)
plt.show()

12.1. Opening and writing to image files 392


Scientific Python Lectures, Edition 2024.2rc0.dev0

Creating a NumPy array from an image file:

>>> import imageio.v3 as iio


>>> face = sp.datasets.face()
>>> iio.imwrite('face.png', face) # First we need to create the PNG file

>>> face = iio.imread('face.png')


>>> type(face)
<class 'numpy.ndarray'>
>>> face.shape, face.dtype
((768, 1024, 3), dtype('uint8'))

dtype is uint8 for 8-bit images (0-255)


Opening raw files (camera, 3-D images)

>>> face.tofile('face.raw') # Create raw file


>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
>>> face_from_raw.shape
(2359296,)
>>> face_from_raw.shape = (768, 1024, 3)

Need to know the shape and dtype of the image (how to separate data bytes).
For large data, use np.memmap for memory mapping:

>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))

(data are read from the file, and not loaded into memory)
Working on a list of image files

>>> rng = np.random.default_rng(27446968)


>>> for i in range(10):
... im = rng.integers(0, 256, 10000, dtype=np.uint8).reshape((100, 100))
(continues on next page)

12.1. Opening and writing to image files 393


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


... iio.imwrite(f'random_{ i: 02d} .png', im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()

12.2 Displaying images

Use matplotlib and imshow to display an image inside a matplotlib figure:

>>> f = sp.datasets.face(gray=True) # retrieve a grayscale image


>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)
<matplotlib.image.AxesImage object at 0x...>

Increase contrast by setting min and max values:

>>> plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200)


<matplotlib.image.AxesImage object at 0x...>
>>> # Remove axes and ticks
>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5)

Draw contour lines:

>>> plt.contour(f, [50, 200])


<matplotlib.contour.QuadContourSet ...>

For smooth intensity variations, use interpolation='bilinear'. For fine inspection of intensity varia-
tions, use interpolation='nearest':

>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='bilinear')


<matplotlib.image.AxesImage object at 0x...>
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest')
<matplotlib.image.AxesImage object at 0x...>

See also:
More interpolation methods are in Matplotlib’s examples.

12.2. Displaying images 394


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.3 Basic manipulations

Images are arrays: use the whole numpy machinery.

>>> face = sp.datasets.face(gray=True)


>>> face[0, 40]
127
>>> # Slicing
>>> face[10:13, 20:23]
array([[141, 153, 145],
[133, 134, 125],
[ 96, 92, 94]], dtype=uint8)
>>> face[100:120] = 255
>>>
>>> lx, ly = face.shape
>>> X, Y = np.ogrid[0:lx, 0:ly]
(continues on next page)

12.3. Basic manipulations 395


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4
>>> # Masks
>>> face[mask] = 0
>>> # Fancy indexing
>>> face[range(400), range(400)] = 255

12.3.1 Statistical information

>>> face = sp.datasets.face(gray=True)


>>> face.mean()
113.48026784261067
>>> face.max(), face.min()
(250, 0)

np.histogram

Exercise

• Open as an array the scikit-image logo (https://scikit-image.org/_static/img/logo.png), or


an image that you have on your computer.
• Crop a meaningful part of the image, for example the python circle in the logo.
• Display the image array using matplotlib. Change the interpolation method and zoom to see
the difference.
• Transform your image to greyscale
• Increase the contrast of the image by changing its minimum and maximum values. Optional:
use scipy.stats.scoreatpercentile (read the docstring!) to saturate 5% of the darkest pixels
and 5% of the lightest pixels.
• Save the array to two different file formats (png, jpg, tiff)

12.3. Basic manipulations 396


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.3.2 Geometrical transformations

>>> face = sp.datasets.face(gray=True)


>>> lx, ly = face.shape
>>> # Cropping
>>> crop_face = face[lx // 4: - lx // 4, ly // 4: - ly // 4]
>>> # up <-> down flip
>>> flip_ud_face = np.flipud(face)
>>> # rotation
>>> rotate_face = sp.ndimage.rotate(face, 45)
>>> rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False)

12.4 Image filtering

Local filters: replace the value of pixels by a function of the values of neighboring pixels.
Neighbourhood: square (choose size), disk, or more complicated structuring element.

12.4.1 Blurring/smoothing

Gaussian filter from scipy.ndimage:

>>> face = sp.datasets.face(gray=True)


>>> blurred_face = sp.ndimage.gaussian_filter(face, sigma=3)
>>> very_blurred = sp.ndimage.gaussian_filter(face, sigma=5)

Uniform filter

>>> local_mean = sp.ndimage.uniform_filter(face, size=11)

12.4. Image filtering 397


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.4.2 Sharpening

Sharpen a blurred image:

>>> face = sp.datasets.face(gray=True).astype(float)


>>> blurred_f = sp.ndimage.gaussian_filter(face, 3)

increase the weight of edges by adding an approximation of the Laplacian:

>>> filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1)


>>> alpha = 30
>>> sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)

12.4.3 Denoising

Noisy face:

>>> f = sp.datasets.face(gray=True)
>>> f = f[230:290, 220:320]
>>> rng = np.random.default_rng()
>>> noisy = f + 0.4 * f.std() * rng.random(f.shape)

A Gaussian filter smoothes the noise out. . . and the edges as well:

>>> gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2)

Most local linear isotropic filters blur the image (scipy.ndimage.uniform_filter)


A median filter preserves better the edges:

12.4. Image filtering 398


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> med_denoised = sp.ndimage.median_filter(noisy, 3)

Median filter: better result for straight boundaries (low curvature):

>>> im = np.zeros((20, 20))


>>> im[5:-5, 5:-5] = 1
>>> im = sp.ndimage.distance_transform_bf(im)
>>> rng = np.random.default_rng()
>>> im_noise = im + 0.2 * rng.standard_normal(im.shape)
>>> im_med = sp.ndimage.median_filter(im_noise, 3)

Other rank filter: scipy.ndimage.maximum_filter, scipy.ndimage.percentile_filter


Other local non-linear filters: Wiener (scipy.signal.wiener), etc.
Non-local filters

Exercise: denoising

• Create a binary image (of 0s and 1s) with several objects (circles, ellipses, squares, or random
shapes).
• Add some noise (e.g., 20% of noise)
• Try two different denoising methods for denoising the image: gaussian filtering and median
filtering.
• Compare the histograms of the two different denoised images. Which one is the closest to the
histogram of the original (noise-free) image?

See also:
More denoising filters are available in skimage.denoising, see the scikit-image: image processing tuto-
rial.

12.4. Image filtering 399


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.4.4 Mathematical morphology

See wikipedia for a definition of mathematical morphology.


Probe an image with a simple shape (a structuring element), and modify this image according to how
the shape locally fits or misses the image.
Structuring element:

>>> el = sp.ndimage.generate_binary_structure(2, 1)
>>> el
array([[False, True, False],
[ True, True, True],
[False, True, False]])
>>> el.astype(int)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])

Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring
element.:

>>> a = np.zeros((7,7), dtype=int)


>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> sp.ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> # Erosion removes objects smaller than the structure
>>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
(continues on next page)

12.4. Image filtering 400


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])

Dilation: maximum filter:

>>> a = np.zeros((5, 5))


>>> a[2, 2] = 1
>>> a
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> sp.ndimage.binary_dilation(a).astype(a.dtype)
array([[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.]])

Also works for grey-valued images:

>>> rng = np.random.default_rng(27446968)


>>> im = np.zeros((64, 64))
>>> x, y = (63*rng.random((2, 8))).astype(int)
>>> im[x, y] = np.arange(8)

>>> bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5,␣


˓→5)))

>>> square = np.zeros((16, 16))


>>> square[4:-4, 4:-4] = 1
>>> dist = sp.ndimage.distance_transform_bf(square)
>>> dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), \
... structure=np.ones((3, 3)))

Opening: erosion + dilation:

>>> a = np.zeros((5,5), dtype=int)


>>> a[1:4, 1:4] = 1; a[4, 4] = 1
>>> a
array([[0, 0, 0, 0, 0],
(continues on next page)

12.4. Image filtering 401


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 1]])
>>> # Opening removes small objects
>>> sp.ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int)
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]])
>>> # Opening can also smooth corners
>>> sp.ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])

Application: remove noise:

>>> square = np.zeros((32, 32))


>>> square[10:-10, 10:-10] = 1
>>> rng = np.random.default_rng(27446968)
>>> x, y = (32*rng.random((2, 20))).astype(int)
>>> square[x, y] = 1

>>> open_square = sp.ndimage.binary_opening(square)

>>> eroded_square = sp.ndimage.binary_erosion(square)


>>> reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square)

Closing: dilation + erosion


Many other mathematical morphology operations: hit and miss transform, tophat, etc.

12.4. Image filtering 402


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.5 Feature extraction

12.5.1 Edge detection

Synthetic data:

>>> im = np.zeros((256, 256))


>>> im[64:-64, 64:-64] = 1
>>>
>>> im = sp.ndimage.rotate(im, 15, mode='constant')
>>> im = sp.ndimage.gaussian_filter(im, 8)

Use a gradient operator (Sobel) to find high intensity variations:

>>> sx = sp.ndimage.sobel(im, axis=0, mode='constant')


>>> sy = sp.ndimage.sobel(im, axis=1, mode='constant')
>>> sob = np.hypot(sx, sy)

12.5.2 Segmentation

• Histogram-based segmentation (no spatial information)

>>> n = 10
>>> l = 256
>>> im = np.zeros((l, l))
>>> rng = np.random.default_rng(27446968)
>>> points = l*rng.random((2, n**2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n))

>>> mask = (im > im.mean()).astype(float)


>>> mask += 0.1 * im
>>> img = mask + 0.2*rng.standard_normal(mask.shape)

>>> hist, bin_edges = np.histogram(img, bins=60)


>>> bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:])

>>> binary_img = img > 0.5

Use mathematical morphology to clean up the result:

>>> # Remove small white regions


>>> open_img = sp.ndimage.binary_opening(binary_img)
(continues on next page)

12.5. Feature extraction 403


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> # Remove small black hole
>>> close_img = sp.ndimage.binary_closing(open_img)

Exercise

Check that reconstruction operations (erosion + propagation) produce a better result than open-
ing/closing:
>>> eroded_img = sp.ndimage.binary_erosion(binary_img)
>>> reconstruct_img = sp.ndimage.binary_propagation(eroded_img, mask=binary_img)
>>> tmp = np.logical_not(reconstruct_img)
>>> eroded_tmp = sp.ndimage.binary_erosion(tmp)
>>> reconstruct_final = np.logical_not(sp.ndimage.binary_propagation(eroded_tmp,␣
˓→mask=tmp))

>>> np.abs(mask - close_img).mean()


0.00640699...
>>> np.abs(mask - reconstruct_final).mean()
0.00082232...

Exercise

Check how a first denoising step (e.g. with a median filter) modifies the histogram, and check that
the resulting histogram-based segmentation is more accurate.

See also:
More advanced segmentation algorithms are found in the scikit-image: see scikit-image: image pro-
cessing.

12.5. Feature extraction 404


Scientific Python Lectures, Edition 2024.2rc0.dev0

See also:
Other Scientific Packages provide algorithms that can be useful for image processing. In this example,
we use the spectral clustering function of the scikit-learn in order to segment glued objects.

>>> from sklearn.feature_extraction import image


>>> from sklearn.cluster import spectral_clustering

>>> l = 100
>>> x, y = np.indices((l, l))

>>> center1 = (28, 24)


>>> center2 = (40, 50)
>>> center3 = (67, 58)
>>> center4 = (24, 70)
>>> radius1, radius2, radius3, radius4 = 16, 14, 15, 14

>>> circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2


>>> circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2
>>> circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2
>>> circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2

>>> # 4 circles
>>> img = circle1 + circle2 + circle3 + circle4
>>> mask = img.astype(bool)
>>> img = img.astype(float)

>>> rng = np.random.default_rng()


>>> img += 1 + 0.2*rng.standard_normal(img.shape)
>>> # Convert the image into a graph with the value of the gradient on
>>> # the edges.
>>> graph = image.img_to_graph(img, mask=mask)

>>> # Take a decreasing function of the gradient: we take it weakly


>>> # dependent from the gradient the segmentation is close to a voronoi
>>> graph.data = np.exp(-graph.data/graph.data.std())

>>> labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack')


>>> label_im = -np.ones(mask.shape)
>>> label_im[mask] = labels

12.5. Feature extraction 405


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.6 Measuring objects properties: scipy.ndimage.measurements

Synthetic data:

>>> n = 10
>>> l = 256
>>> im = np.zeros((l, l))
>>> rng = np.random.default_rng(27446968)
>>> points = l * rng.random((2, n**2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n))
>>> mask = im > im.mean()

• Analysis of connected components


Label connected components: scipy.dimage.label:

>>> label_im, nb_labels = sp.ndimage.label(mask)


>>> nb_labels # how many regions?
28
>>> plt.imshow(label_im)
<matplotlib.image.AxesImage object at 0x...>

Compute size, mean_value, etc. of each region:

>>> sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))


>>> mean_vals = sp.ndimage.sum(im, label_im, range(1, nb_labels + 1))

Clean up small connect components:

>>> mask_size = sizes < 1000


>>> remove_pixel = mask_size[label_im]
>>> remove_pixel.shape
(256, 256)
>>> label_im[remove_pixel] = 0
>>> plt.imshow(label_im)
<matplotlib.image.AxesImage object at 0x...>

Now reassign labels with np.searchsorted:

>>> labels = np.unique(label_im)


>>> label_im = np.searchsorted(labels, label_im)

Find region of interest enclosing object:

12.6. Measuring objects properties: scipy.ndimage.measurements 406


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> slice_x, slice_y = sp.ndimage.find_objects(label_im)[3]


>>> roi = im[slice_x, slice_y]
>>> plt.imshow(roi)
<matplotlib.image.AxesImage object at 0x...>

Other spatial measures: scipy.ndimage.center_of_mass, scipy.ndimage.maximum_position, etc.


Can be used outside the limited scope of segmentation applications.
Example: block mean:

>>> f = sp.datasets.face(gray=True)
>>> sx, sy = f.shape
>>> X, Y = np.ogrid[0:sx, 0:sy]
>>> regions = (sy//6) * (X//4) + (Y//6) # note that we use broadcasting
>>> block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1,
... regions.max() +1))
>>> block_mean.shape = (sx // 4, sy // 6)

When regions are regular blocks, it is more efficient to use stride tricks (Example: fake dimensions with
strides).
Non-regularly-spaced blocks: radial mean:

12.6. Measuring objects properties: scipy.ndimage.measurements 407


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> sx, sy = f.shape


>>> X, Y = np.ogrid[0:sx, 0:sy]
>>> r = np.hypot(X - sx/2, Y - sy/2)
>>> rbin = (20* r/r.max()).astype(int)
>>> radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1))

• Other measures
Correlation function, Fourier/wavelet spectrum, etc.
One example with mathematical morphology: granulometry

12.6. Measuring objects properties: scipy.ndimage.measurements 408


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> def disk_structure(n):


... struct = np.zeros((2 * n + 1, 2 * n + 1))
... x, y = np.indices((2 * n + 1, 2 * n + 1))
... mask = (x - n)**2 + (y - n)**2 <= n**2
... struct[mask] = 1
... return struct.astype(bool)
...
>>>
>>> def granulometry(data, sizes=None):
... s = max(data.shape)
... if sizes is None:
... sizes = range(1, s/2, 2)
... granulo = [sp.ndimage.binary_opening(data, \
... structure=disk_structure(n)).sum() for n in sizes]
... return granulo
...
>>>
>>> rng = np.random.default_rng(27446968)
>>> n = 10
>>> l = 256
>>> im = np.zeros((l, l))
>>> points = l*rng.random((2, n**2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n))
>>>
>>> mask = im > im.mean()
>>>
>>> granulo = granulometry(mask, sizes=np.arange(2, 19, 4))

12.7 Full code examples

12.8 Examples for the image processing chapter

12.8.1 Displaying a Raccoon Face

Small example to plot a raccoon face.

12.7. Full code examples 409


Scientific Python Lectures, Edition 2024.2rc0.dev0

import scipy as sp
import imageio.v3 as iio

f = sp.datasets.face()
iio.imwrite("face.png", f) # uses the Image module (PIL)

import matplotlib.pyplot as plt

plt.imshow(f)
plt.show()

Total running time of the script: (0 minutes 0.549 seconds)

12.8. Examples for the image processing chapter 410


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.2 Image interpolation

The example demonstrates image interpolation on a Raccoon face.

import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True)

plt.figure(figsize=(8, 4))

plt.subplot(1, 2, 1)
plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray)
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.156 seconds)

12.8. Examples for the image processing chapter 411


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.3 Plot the block mean of an image

An example showing how to use broad-casting to plot the mean of blocks of an image.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True)
sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy]

regions = sy // 6 * (X // 4) + Y // 6
block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1))
block_mean.shape = (sx // 4, sy // 6)

plt.figure(figsize=(5, 5))
plt.imshow(block_mean, cmap=plt.cm.gray)
plt.axis("off")

plt.show()

Total running time of the script: (0 minutes 0.180 seconds)

12.8. Examples for the image processing chapter 412


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.4 Image manipulation and NumPy arrays

This example shows how to do image manipulation using common NumPy arrays tricks.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

face = sp.datasets.face(gray=True)
face[10:13, 20:23]
face[100:120] = 255

lx, ly = face.shape
X, Y = np.ogrid[0:lx, 0:ly]
mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4
face[mask] = 0
face[range(400), range(400)] = 255

plt.figure(figsize=(3, 3))
plt.axes([0, 0, 1, 1])
plt.imshow(face, cmap=plt.cm.gray)
plt.axis("off")

plt.show()

Total running time of the script: (0 minutes 0.161 seconds)

12.8. Examples for the image processing chapter 413


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.5 Radial mean

This example shows how to do a radial mean with scikit-image.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True)
sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy]

r = np.hypot(X - sx / 2, Y - sy / 2)

rbin = (20 * r / r.max()).astype(int)


radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1))

plt.figure(figsize=(5, 5))
plt.axes([0, 0, 1, 1])
plt.imshow(rbin, cmap=plt.cm.nipy_spectral)
plt.axis("off")

plt.show()

Total running time of the script: (0 minutes 0.175 seconds)

12.8. Examples for the image processing chapter 414


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.6 Display a Raccoon Face

An example that displays a raccoon face with matplotlib.

import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True)

plt.figure(figsize=(10, 3.6))

plt.subplot(131)
plt.imshow(f, cmap=plt.cm.gray)

plt.subplot(132)
plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200)
plt.axis("off")

plt.subplot(133)
plt.imshow(f, cmap=plt.cm.gray)
plt.contour(f, [50, 200])
plt.axis("off")

plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.


˓→99)

plt.show()

Total running time of the script: (0 minutes 0.370 seconds)

12.8. Examples for the image processing chapter 415


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.7 Image sharpening

This example shows how to sharpen an image in noiseless situation by applying the filter inverse to the
blur.

import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True).astype(float)
blurred_f = sp.ndimage.gaussian_filter(f, 3)

filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1)

alpha = 30
sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)

plt.figure(figsize=(12, 4))

plt.subplot(131)
plt.imshow(f, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(132)
plt.imshow(blurred_f, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(133)
plt.imshow(sharpened, cmap=plt.cm.gray)
plt.axis("off")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.443 seconds)

12.8. Examples for the image processing chapter 416


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.8 Blurring of images

An example showing various processes that blur an image.

import scipy as sp
import matplotlib.pyplot as plt

face = sp.datasets.face(gray=True)
blurred_face = sp.ndimage.gaussian_filter(face, sigma=3)
very_blurred = sp.ndimage.gaussian_filter(face, sigma=5)
local_mean = sp.ndimage.uniform_filter(face, size=11)

plt.figure(figsize=(9, 3))
plt.subplot(131)
plt.imshow(blurred_face, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(132)
plt.imshow(very_blurred, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(133)
plt.imshow(local_mean, cmap=plt.cm.gray)
plt.axis("off")

plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.


˓→99)

plt.show()

Total running time of the script: (0 minutes 0.275 seconds)

12.8. Examples for the image processing chapter 417


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.9 Synthetic data

The example generates and displays simple synthetic data.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = im > im.mean()

label_im, nb_labels = sp.ndimage.label(mask)

plt.figure(figsize=(9, 3))

plt.subplot(131)
plt.imshow(im)
plt.axis("off")
plt.subplot(132)
plt.imshow(mask, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(133)
plt.imshow(label_im, cmap=plt.cm.nipy_spectral)
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.075 seconds)

12.8. Examples for the image processing chapter 418


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.10 Opening, erosion, and propagation

This example shows simple operations of mathematical morphology.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

square = np.zeros((32, 32))


square[10:-10, 10:-10] = 1
rng = np.random.default_rng(27446968)
x, y = (32 * rng.random((2, 20))).astype(int)
square[x, y] = 1

open_square = sp.ndimage.binary_opening(square)

eroded_square = sp.ndimage.binary_erosion(square)
reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square)

plt.figure(figsize=(9.5, 3))
plt.subplot(131)
plt.imshow(square, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")
plt.subplot(132)
plt.imshow(open_square, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")
plt.subplot(133)
plt.imshow(reconstruction, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.


˓→99)

plt.show()

Total running time of the script: (0 minutes 0.039 seconds)

12.8. Examples for the image processing chapter 419


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.11 Image denoising

This example demoes image denoising on a Raccoon face.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

f = sp.datasets.face(gray=True)
f = f[230:290, 220:320]

noisy = f + 0.4 * f.std() * rng.random(f.shape)

gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2)
med_denoised = sp.ndimage.median_filter(noisy, 3)

plt.figure(figsize=(12, 2.8))

plt.subplot(131)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis("off")
plt.title("noisy", fontsize=20)
plt.subplot(132)
plt.imshow(gauss_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis("off")
plt.title("Gaussian filter", fontsize=20)
plt.subplot(133)
plt.imshow(med_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis("off")
plt.title("Median filter", fontsize=20)

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.212 seconds)

12.8. Examples for the image processing chapter 420


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.12 Geometrical transformations

This examples demos some simple geometrical transformations on a Raccoon face.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

face = sp.datasets.face(gray=True)
lx, ly = face.shape
# Cropping
crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4]
# up <-> down flip
flip_ud_face = np.flipud(face)
# rotation
rotate_face = sp.ndimage.rotate(face, 45)
rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False)

plt.figure(figsize=(12.5, 2.5))

plt.subplot(151)
plt.imshow(face, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(152)
plt.imshow(crop_face, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(153)
plt.imshow(flip_ud_face, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(154)
plt.imshow(rotate_face, cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(155)
plt.imshow(rotate_face_noreshape, cmap=plt.cm.gray)
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)

plt.show()

Total running time of the script: (0 minutes 0.460 seconds)

12.8. Examples for the image processing chapter 421


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.13 Find the bounding box of an object

This example shows how to extract the bounding box of the largest object

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = im > im.mean()

label_im, nb_labels = sp.ndimage.label(mask)

# Find the largest connected component


sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))
mask_size = sizes < 1000
remove_pixel = mask_size[label_im]
label_im[remove_pixel] = 0
labels = np.unique(label_im)
label_im = np.searchsorted(labels, label_im)

# Now that we have only one connected component, extract it's bounding box
slice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0]
roi = im[slice_x, slice_y]

plt.figure(figsize=(4, 2))
plt.axes([0, 0, 1, 1])
plt.imshow(roi)
plt.axis("off")

plt.show()

Total running time of the script: (0 minutes 0.018 seconds)

12.8. Examples for the image processing chapter 422


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.14 Measurements from images

This examples shows how to measure quantities from various images.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = im > im.mean()

label_im, nb_labels = sp.ndimage.label(mask)

sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))


mask_size = sizes < 1000
remove_pixel = mask_size[label_im]
label_im[remove_pixel] = 0
labels = np.unique(label_im)
label_clean = np.searchsorted(labels, label_im)

plt.figure(figsize=(6, 3))

plt.subplot(121)
plt.imshow(label_im, cmap=plt.cm.nipy_spectral)
plt.axis("off")
plt.subplot(122)
plt.imshow(label_clean, vmax=nb_labels, cmap=plt.cm.nipy_spectral)
plt.axis("off")

plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1)


plt.show()

12.8. Examples for the image processing chapter 423


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.040 seconds)

12.8.15 Total Variation denoising

This example demoes Total-Variation (TV) denoising on a Raccoon face.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

from skimage.restoration import denoise_tv_chambolle

rng = np.random.default_rng(27446968)

f = sp.datasets.face(gray=True)
f = f[230:290, 220:320]

noisy = f + 0.4 * f.std() * rng.random(f.shape)

tv_denoised = denoise_tv_chambolle(noisy, weight=10)

plt.figure(figsize=(12, 2.8))

plt.subplot(131)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis("off")
plt.title("noisy", fontsize=20)
plt.subplot(132)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis("off")
plt.title("TV denoising", fontsize=20)

tv_denoised = denoise_tv_chambolle(noisy, weight=50)


plt.subplot(133)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis("off")
plt.title("(more) TV denoising", fontsize=20)

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.220 seconds)

12.8. Examples for the image processing chapter 424


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.16 Denoising an image with the median filter

This example shows the original image, the noisy image, the denoised one (with the median filter) and
the difference between the two.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

im = np.zeros((20, 20))
im[5:-5, 5:-5] = 1
im = sp.ndimage.distance_transform_bf(im)
im_noise = im + 0.2 * rng.normal(size=im.shape)

im_med = sp.ndimage.median_filter(im_noise, 3)

plt.figure(figsize=(16, 5))

plt.subplot(141)
plt.imshow(im, interpolation="nearest")
plt.axis("off")
plt.title("Original image", fontsize=20)
plt.subplot(142)
plt.imshow(im_noise, interpolation="nearest", vmin=0, vmax=5)
plt.axis("off")
plt.title("Noisy image", fontsize=20)
plt.subplot(143)
plt.imshow(im_med, interpolation="nearest", vmin=0, vmax=5)
plt.axis("off")
plt.title("Median filter", fontsize=20)
plt.subplot(144)
plt.imshow(np.abs(im - im_med), cmap=plt.cm.hot, interpolation="nearest")
plt.axis("off")
plt.title("Error", fontsize=20)

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)

plt.show()

Total running time of the script: (0 minutes 0.144 seconds)

12.8. Examples for the image processing chapter 425


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.17 Histogram segmentation

This example does simple histogram analysis to perform segmentation.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = (im > im.mean()).astype(float)

mask += 0.1 * im

img = mask + 0.2 * rng.normal(size=mask.shape)

hist, bin_edges = np.histogram(img, bins=60)


bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])

binary_img = img > 0.5

plt.figure(figsize=(11, 4))

plt.subplot(131)
plt.imshow(img)
plt.axis("off")
plt.subplot(132)
plt.plot(bin_centers, hist, lw=2)
plt.axvline(0.5, color="r", ls="--", lw=2)
plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes)
plt.yticks([])
plt.subplot(133)
plt.imshow(binary_img, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)


plt.show()

12.8. Examples for the image processing chapter 426


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.132 seconds)

12.8.18 Greyscale dilation

This example illustrates greyscale mathematical morphology.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

im = np.zeros((64, 64))
rng = np.random.default_rng(27446968)
x, y = (63 * rng.random((2, 8))).astype(int)
im[x, y] = np.arange(8)

bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5)))

square = np.zeros((16, 16))


square[4:-4, 4:-4] = 1
dist = sp.ndimage.distance_transform_bf(square)
dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3)))

plt.figure(figsize=(12.5, 3))
plt.subplot(141)
plt.imshow(im, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.axis("off")
plt.subplot(142)
plt.imshow(bigger_points, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.axis("off")
plt.subplot(143)
plt.imshow(dist, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.axis("off")
plt.subplot(144)
plt.imshow(dilate_dist, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.axis("off")

plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.


˓→99)

plt.show()

Total running time of the script: (0 minutes 0.053 seconds)

12.8. Examples for the image processing chapter 427


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.19 Finding edges with Sobel filters

The Sobel filter is one of the simplest way of finding edges.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

im = np.zeros((256, 256))
im[64:-64, 64:-64] = 1

im = sp.ndimage.rotate(im, 15, mode="constant")


im = sp.ndimage.gaussian_filter(im, 8)

sx = sp.ndimage.sobel(im, axis=0, mode="constant")


sy = sp.ndimage.sobel(im, axis=1, mode="constant")
sob = np.hypot(sx, sy)

plt.figure(figsize=(16, 5))
plt.subplot(141)
plt.imshow(im, cmap=plt.cm.gray)
plt.axis("off")
plt.title("square", fontsize=20)
plt.subplot(142)
plt.imshow(sx)
plt.axis("off")
plt.title("Sobel (x direction)", fontsize=20)
plt.subplot(143)
plt.imshow(sob)
plt.axis("off")
plt.title("Sobel filter", fontsize=20)

im += 0.07 * rng.random(im.shape)

sx = sp.ndimage.sobel(im, axis=0, mode="constant")


sy = sp.ndimage.sobel(im, axis=1, mode="constant")
sob = np.hypot(sx, sy)

plt.subplot(144)
plt.imshow(sob)
plt.axis("off")
plt.title("Sobel for noisy image", fontsize=20)

(continues on next page)

12.8. Examples for the image processing chapter 428


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9)

plt.show()

Total running time of the script: (0 minutes 0.219 seconds)

12.8.20 Cleaning segmentation with mathematical morphology

An example showing how to clean segmentation with mathematical morphology: removing small regions
and holes.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = (im > im.mean()).astype(float)

img = mask + 0.3 * rng.normal(size=mask.shape)

binary_img = img > 0.5

# Remove small white regions


open_img = sp.ndimage.binary_opening(binary_img)
# Remove small black hole
close_img = sp.ndimage.binary_closing(open_img)

plt.figure(figsize=(12, 3))

l = 128

plt.subplot(141)
plt.imshow(binary_img[:l, :l], cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(142)
(continues on next page)

12.8. Examples for the image processing chapter 429


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.imshow(open_img[:l, :l], cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(143)
plt.imshow(close_img[:l, :l], cmap=plt.cm.gray)
plt.axis("off")
plt.subplot(144)
plt.imshow(mask[:l, :l], cmap=plt.cm.gray)
plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r")
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)

plt.show()

Total running time of the script: (0 minutes 0.078 seconds)

12.8.21 Segmentation with Gaussian mixture models

This example performs a Gaussian mixture model analysis of the image histogram to find the right
thresholds for separating foreground from background.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = (im > im.mean()).astype(float)

img = mask + 0.3 * rng.normal(size=mask.shape)

(continues on next page)

12.8. Examples for the image processing chapter 430


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


hist, bin_edges = np.histogram(img, bins=60)
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])

classif = GaussianMixture(n_components=2)
classif.fit(img.reshape((img.size, 1)))

threshold = np.mean(classif.means_)
binary_img = img > threshold

plt.figure(figsize=(11, 4))

plt.subplot(131)
plt.imshow(img)
plt.axis("off")
plt.subplot(132)
plt.plot(bin_centers, hist, lw=2)
plt.axvline(0.5, color="r", ls="--", lw=2)
plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes)
plt.yticks([])
plt.subplot(133)
plt.imshow(binary_img, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.747 seconds)

12.8.22 Watershed segmentation

This example shows how to do segmentation with watershed.

import numpy as np
from skimage.segmentation import watershed
from skimage.feature import peak_local_max
import matplotlib.pyplot as plt
import scipy as sp
(continues on next page)

12.8. Examples for the image processing chapter 431


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# Generate an initial image with two overlapping circles


x, y = np.indices((80, 80))
x1, y1, x2, y2 = 28, 28, 44, 52
r1, r2 = 16, 20
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2
image = np.logical_or(mask_circle1, mask_circle2)
# Now we want to separate the two objects in image
# Generate the markers as local maxima of the distance
# to the background
distance = sp.ndimage.distance_transform_edt(image)
peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)
peak_mask = np.zeros_like(distance, dtype=bool)
peak_mask[tuple(peak_idx.T)] = True
markers = sp.ndimage.label(peak_mask)[0]
labels = watershed(-distance, markers, mask=image)

plt.figure(figsize=(9, 3.5))
plt.subplot(131)
plt.imshow(image, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(132)
plt.imshow(-distance, interpolation="nearest")
plt.axis("off")
plt.subplot(133)
plt.imshow(labels, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.059 seconds)

12.8.23 Granulometry

This example performs a simple granulometry analysis.

import numpy as np
import scipy as sp
(continues on next page)

12.8. Examples for the image processing chapter 432


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


import matplotlib.pyplot as plt

def disk_structure(n):
struct = np.zeros((2 * n + 1, 2 * n + 1))
x, y = np.indices((2 * n + 1, 2 * n + 1))
mask = (x - n) ** 2 + (y - n) ** 2 <= n**2
struct[mask] = 1
return struct.astype(bool)

def granulometry(data, sizes=None):


s = max(data.shape)
if sizes is None:
sizes = range(1, s / 2, 2)
granulo = [
sp.ndimage.binary_opening(data, structure=disk_structure(n)).sum()
for n in sizes
]
return granulo

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = im > im.mean()

granulo = granulometry(mask, sizes=np.arange(2, 19, 4))

plt.figure(figsize=(6, 2.2))

plt.subplot(121)
plt.imshow(mask, cmap=plt.cm.gray)
opened = sp.ndimage.binary_opening(mask, structure=disk_structure(10))
opened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14))
plt.contour(opened, [0.5], colors="b", linewidths=2)
plt.contour(opened_more, [0.5], colors="r", linewidths=2)
plt.axis("off")
plt.subplot(122)
plt.plot(np.arange(2, 19, 4), granulo, "ok", ms=8)

plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.


˓→95)

plt.show()

Total running time of the script: (0 minutes 0.251 seconds)

12.8. Examples for the image processing chapter 433


Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.24 Segmentation with spectral clustering

This example uses spectral clustering to do segmentation.

import numpy as np
import matplotlib.pyplot as plt

from sklearn.feature_extraction import image


from sklearn.cluster import spectral_clustering

l = 100
x, y = np.indices((l, l))

center1 = (28, 24)


center2 = (40, 50)
center3 = (67, 58)
center4 = (24, 70)

radius1, radius2, radius3, radius4 = 16, 14, 15, 14

circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2


circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2

4 circles

img = circle1 + circle2 + circle3 + circle4


mask = img.astype(bool)
img = img.astype(float)

rng = np.random.default_rng(27446968)
img += 1 + 0.2 * rng.normal(size=img.shape)

# Convert the image into a graph with the value of the gradient on the
# edges.
graph = image.img_to_graph(img, mask=mask)

# Take a decreasing function of the gradient: we take it weakly


# dependent from the gradient the segmentation is close to a voronoi
graph.data = np.exp(-graph.data / graph.data.std())

# Force the solver to be arpack, since amg is numerically


# unstable on this example
labels = spectral_clustering(graph, n_clusters=4)
label_im = -np.ones(mask.shape)
label_im[mask] = labels

plt.figure(figsize=(6, 3))
plt.subplot(121)
plt.imshow(img, cmap=plt.cm.nipy_spectral, interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(label_im, cmap=plt.cm.nipy_spectral, interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.


(continues on next page)

12.8. Examples for the image processing chapter 434


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


˓→99)

plt.show()

Total running time of the script: (0 minutes 0.403 seconds)

See also:
More on image-processing:
• The chapter on Scikit-image
• Other, more powerful and complete modules: OpenCV (Python bindings), CellProfiler, ITK with
Python bindings

12.8. Examples for the image processing chapter 435


CHAPTER 13
Mathematical optimization: finding
minima of functions

Authors: Gaël Varoquaux


Mathematical optimization deals with the problem of finding numerically minimums (or maximums or
zeros) of a function. In this context, the function is called cost function, or objective function, or energy.
Here, we are interested in using scipy.optimize for black-box optimization: we do not rely on the
mathematical expression of the function that we are optimizing. Note that this expression can often be
used for more efficient, non black-box, optimization.

Prerequisites

• NumPy
• SciPy
• Matplotlib

See also:
References
Mathematical optimization is very . . . mathematical. If you want performance, it really pays to read
the books:
• Convex Optimization by Boyd and Vandenberghe (pdf available free online).
• Numerical Optimization, by Nocedal and Wright. Detailed reference on gradient descent methods.
• Practical Methods of Optimization by Fletcher: good at hand-waving explanations.

436
Scientific Python Lectures, Edition 2024.2rc0.dev0

Chapters contents

• Knowing your problem


– Convex versus non-convex optimization
– Smooth and non-smooth problems
– Noisy versus exact cost functions
– Constraints
• A review of the different optimizers
– Getting started: 1D optimization
– Gradient based methods
– Newton and quasi-newton methods
• Full code examples
• Examples for the mathematical optimization chapter
– Gradient-less methods
– Global optimizers
• Practical guide to optimization with SciPy
– Choosing a method
– Making your optimizer faster
– Computing gradients
– Synthetic exercices
• Special case: non-linear least-squares
– Minimizing the norm of a vector function
– Curve fitting
• Optimization with constraints
– Box bounds
– General constraints
• Full code examples
• Examples for the mathematical optimization chapter

13.1 Knowing your problem

Not all optimization problems are equal. Knowing your problem enables you to choose the right tool.

Dimensionality of the problem

The scale of an optimization problem is pretty much set by the dimensionality of the problem, i.e. the
number of scalar variables on which the search is performed.

13.1. Knowing your problem 437


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.1.1 Convex versus non-convex optimization

A convex function: A non-convex function


• f is above all its tangents.
• equivalently, for two point A, B, f(C) lies
below the segment [f(A), f(B])], if A < C <
B

Optimizing convex functions is easy. Optimizing non-convex functions can be very hard.

Note: It can be proven that for a convex function a local minimum is also a global minimum. Then,
in some sense, the minimum is unique.

13.1.2 Smooth and non-smooth problems

A smooth function: A non-smooth function


The gradient is defined everywhere, and is a continuous function

Optimizing smooth functions is easier (true in the context of black-box optimization, otherwise Lin-
ear Programming is an example of methods which deal very efficiently with piece-wise linear functions).

13.1. Knowing your problem 438


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.1.3 Noisy versus exact cost functions

Noisy (blue) and non-noisy (green) functions

Noisy gradients

Many optimization methods rely on gradients of the objective function. If the gradient function is not
given, they are computed numerically, which induces errors. In such situation, even if the objective
function is not noisy, a gradient-based optimization may be a noisy optimization.

13.1.4 Constraints

Optimizations under constraints


Here:
−1 < 𝑥1 < 1
−1 < 𝑥2 < 1

13.1. Knowing your problem 439


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.2 A review of the different optimizers

13.2.1 Getting started: 1D optimization

Let’s get started by finding the minimum of the scalar function 𝑓 (𝑥) = exp[(𝑥−0.7)2 ]. scipy.optimize.
minimize_scalar() uses Brent’s method to find the minimum of a function:

>>> import numpy as np


>>> import scipy as sp
>>> def f(x):
... return -np.exp(-(x - 0.5)**2)
>>> result = sp.optimize.minimize_scalar(f)
>>> result.success # check if solver was successful
True
>>> x_min = result.x
>>> x_min
0.50...
>>> x_min - 0.5
5.8...e-09

Table 1: Brent’s method on a quadratic function: it converges


in 3 iterations, as the quadratic approximation is then exact.

Table 2: Brent’s method on a non-convex function: note that


the fact that the optimizer avoided the local minimum is a matter
of luck.

13.2. A review of the different optimizers 440


Scientific Python Lectures, Edition 2024.2rc0.dev0

Note: You can use different solvers using the parameter method.

Note: scipy.optimize.minimize_scalar() can also be used for optimization constrained to an


interval using the parameter bounds.

13.2.2 Gradient based methods

Some intuitions about gradient descent

Here we focus on intuitions, not code. Code will follow.


Gradient descent basically consists in taking small steps in the direction of the gradient, that is the
direction of the steepest descent.

Table 3: Fixed step gradient descent

A well-conditioned
quadratic function.

An ill-conditioned
quadratic function.
The core problem of gradient-
methods on ill-conditioned
problems is that the gradient
tends not to point in the direc-
tion of the minimum.

We can see that very anisotropic (ill-conditioned) functions are harder to optimize.

Take home message: conditioning number and preconditioning

If you know natural scaling for your variables, prescale them so that they behave similarly. This is
related to preconditioning.

Also, it clearly can be advantageous to take bigger steps. This is done in gradient descent code using a
line search.

13.2. A review of the different optimizers 441


Scientific Python Lectures, Edition 2024.2rc0.dev0

Table 4: Adaptive step gradient descent

A well-conditioned quadratic
function.

An ill-conditioned quadratic
function.

An ill-conditioned non-
quadratic function.

An ill-conditioned very non-


quadratic function.

The more a function looks like a quadratic function (elliptic iso-curves), the easier it is to optimize.

13.2. A review of the different optimizers 442


Scientific Python Lectures, Edition 2024.2rc0.dev0

Conjugate gradient descent

The gradient descent algorithms above are toys not to be used on real problems.
As can be seen from the above experiments, one of the problems of the simple gradient descent algorithms,
is that it tends to oscillate across a valley, each time following the direction of the gradient, that makes
it cross the valley. The conjugate gradient solves this problem by adding a friction term: each step
depends on the two last values of the gradient and sharp turns are reduced.

Table 5: Conjugate gradient descent

An ill-conditioned non-
quadratic function.

An ill-conditioned very non-


quadratic function.

SciPy provides scipy.optimize.minimize() to find the minimum of scalar functions of one or more
variables. The simple conjugate gradient method can be used by setting the parameter method to CG

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> sp.optimize.minimize(f, [2, -1], method="CG")
message: Optimization terminated successfully.
success: True
status: 0
fun: 1.650...e-11
x: [ 1.000e+00 1.000e+00]
nit: 13
jac: [-6.15...e-06 2.53...e-07]
nfev: 81
njev: 27

Gradient methods need the Jacobian (gradient) of the function. They can compute it numerically, but
will perform better if you can pass them the gradient:

>>> def jacobian(x):


... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2, 1], method="CG", jac=jacobian)


message: Optimization terminated successfully.
(continues on next page)

13.2. A review of the different optimizers 443


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


success: True
status: 0
fun: 2.95786...e-14
x: [ 1.000e+00 1.000e+00]
nit: 8
jac: [ 7.183e-07 -2.990e-07]
nfev: 16
njev: 16

Note that the function has only been evaluated 27 times, compared to 108 without the gradient.

13.2.3 Newton and quasi-newton methods

Newton methods: using the Hessian (2nd differential)

Newton methods use a local quadratic approximation to compute the jump direction. For this purpose,
they rely on the 2 first derivative of the function: the gradient and the Hessian.

13.2. A review of the different optimizers 444


Scientific Python Lectures, Edition 2024.2rc0.dev0

An ill-conditioned
quadratic function:
Note that, as the quadratic ap-
proximation is exact, the New-
ton method is blazing fast

An ill-conditioned non-
quadratic function:
Here we are optimizing a Gaus-
sian, which is always below its
quadratic approximation. As a
result, the Newton method over-
shoots and leads to oscillations.

An ill-conditioned very non-


quadratic function:

In SciPy, you can use the Newton method by setting method to Newton-CG in scipy.optimize.
minimize(). Here, CG refers to the fact that an internal inversion of the Hessian is performed by
conjugate gradient

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def jacobian(x):
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian)


message: Optimization terminated successfully.
success: True
status: 0
fun: 1.5601357400786612e-15
(continues on next page)

13.2. A review of the different optimizers 445


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


x: [ 1.000e+00 1.000e+00]
nit: 10
jac: [ 1.058e-07 -7.483e-08]
nfev: 11
njev: 33
nhev: 0

Note that compared to a conjugate gradient (above), Newton’s method has required less function evalua-
tions, but more gradient evaluations, as it uses it to approximate the Hessian. Let’s compute the Hessian
and pass it to the algorithm:

>>> def hessian(x): # Computed with sympy


... return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
>>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian, hess=hessian)
message: Optimization terminated successfully.
success: True
status: 0
fun: 1.6277298383706738e-15
x: [ 1.000e+00 1.000e+00]
nit: 10
jac: [ 1.110e-07 -7.781e-08]
nfev: 11
njev: 11
nhev: 10

Note: At very high-dimension, the inversion of the Hessian can be costly and unstable (large scale >
250).

Note: Newton optimizers should not to be confused with Newton’s root finding method, based on the
same principles, scipy.optimize.newton().

Quasi-Newton methods: approximating the Hessian on the fly

BFGS: BFGS (Broyden-Fletcher-Goldfarb-Shanno algorithm) refines at each step an approximation of


the Hessian.

13.3 Full code examples

13.4 Examples for the mathematical optimization chapter

13.4.1 Noisy optimization problem

Draws a figure explaining noisy vs non-noisy optimization

13.3. Full code examples 446


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

x = np.linspace(-5, 5, 101)
x_ = np.linspace(-5, 5, 31)

def f(x):
return -np.exp(-(x**2))

# A smooth function
plt.figure(1, figsize=(3, 2.5))
plt.clf()

plt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2)


plt.plot(x, f(x), linewidth=2)

plt.ylim(ymin=-1.3)
plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.019 seconds)

13.4. Examples for the mathematical optimization chapter 447


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.2 Smooth vs non-smooth

Draws a figure to explain smooth versus non smooth optimization.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1.5, 1.5, 101)

# A smooth function
plt.figure(1, figsize=(3, 2.5))
plt.clf()

plt.plot(x, np.sqrt(0.2 + x**2), linewidth=2)


plt.text(-1, 0, "$f$", size=20)

plt.ylim(ymin=-0.2)
plt.axis("off")
plt.tight_layout()

# A non-smooth function
plt.figure(2, figsize=(3, 2.5))
plt.clf()
plt.plot(x, np.abs(x), linewidth=2)
plt.text(-1, 0, "$f$", size=20)

(continues on next page)

13.4. Examples for the mathematical optimization chapter 448


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.ylim(ymin=-0.2)
plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.047 seconds)

13.4.3 Curve fitting

A curve fitting example

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

# Our test function


def f(t, omega, phi):
return np.cos(omega * t + phi)

# Our x and y data


x = np.linspace(0, 3, 50)
(continues on next page)

13.4. Examples for the mathematical optimization chapter 449


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


y = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50)

# Fit the model: the parameters omega and phi can be found in the
# `params` vector
params, params_cov = sp.optimize.curve_fit(f, x, y)

# plot the data and the fitted curve


t = np.linspace(0, 3, 1000)

plt.figure(1)
plt.clf()
plt.plot(x, y, "bx")
plt.plot(t, f(t, *params), "r-")
plt.show()

Total running time of the script: (0 minutes 0.066 seconds)

13.4.4 Convex function

A figure showing the definition of a convex function

13.4. Examples for the mathematical optimization chapter 450


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1, 2)

plt.figure(1, figsize=(3, 2.5))


plt.clf()

# A convex function
plt.plot(x, x**2, linewidth=2)
plt.text(-0.7, -(0.6**2), "$f$", size=20)

# The tangent in one point


plt.plot(x, 2 * x - 1)
plt.plot(1, 1, "k+")
plt.text(0.3, -0.75, "Tangent to $f$", size=15)
plt.text(1, 1 - 0.5, "C", size=15)

# Convexity as barycenter
plt.plot([0.35, 1.85], [0.35**2, 1.85**2])
plt.plot([0.35, 1.85], [0.35**2, 1.85**2], "k+")
plt.text(0.35 - 0.2, 0.35**2 + 0.1, "A", size=15)
plt.text(1.85 - 0.2, 1.85**2, "B", size=15)

plt.ylim(ymin=-1)
plt.axis("off")
plt.tight_layout()

# Convexity as barycenter
plt.figure(2, figsize=(3, 2.5))
plt.clf()
plt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2)
plt.text(-0.7, -(0.6**2), "$f$", size=20)

plt.ylim(ymin=-1)
plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.055 seconds)

13.4.5 Finding a minimum in a flat neighborhood

An exercise of finding minimum. This exercise is hard because the function is very flat around the
minimum (all its derivatives are zero). Thus gradient information is unreliable.
The function admits a minimum in [0, 0]. The challenge is to get within 1e-7 of this minimum, starting
at x0 = [1, 1].
The solution that we adopt here is to give up on using gradient or information based on local differences,
and to rely on the Powell algorithm. With 162 function evaluations, we get to 1e-8 of the solution.
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

(continues on next page)

13.4. Examples for the mathematical optimization chapter 451


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

def f(x):
return np.exp(-1 / (0.01 * x[0] ** 2 + x[1] ** 2))

# A well-conditionned version of f:
def g(x):
return f([10 * x[0], x[1]])

# The gradient of g. We won't use it here for the optimization.


def g_prime(x):
r = np.sqrt(x[0] ** 2 + x[1] ** 2)
return 2 / r**3 * g(x) * x / r

result = sp.optimize.minimize(g, [1, 1], method="Powell", tol=1e-10)


x_min = result.x

Some pretty plotting

plt.figure(0)
plt.clf()
t = np.linspace(-1.1, 1.1, 100)
plt.plot(t, f([0, t]))

plt.figure(1)
plt.clf()
X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j]
plt.imshow(
f([X, Y]).T, cmap=plt.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], origin="lower"
)
plt.contour(X, Y, f([X, Y]), cmap=plt.cm.gnuplot)

# Plot the gradient


dX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]])
# Adjust for our preconditioning
dX *= 0.1
plt.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color=".5")

# Plot our solution


plt.plot(x_min[0], x_min[1], "r+", markersize=15)

plt.show()

13.4. Examples for the mathematical optimization chapter 452


Scientific Python Lectures, Edition 2024.2rc0.dev0


Total running time of the script: (0 minutes 0.143 seconds)

13.4. Examples for the mathematical optimization chapter 453


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.6 Optimization with constraints

An example showing how to do optimization with general constraints using SLSQP and cobyla.

import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04]
x = x.T
y = y.T

plt.figure(1, figsize=(3, 2.5))


plt.clf()
plt.axes([0, 0, 1, 1])

contours = plt.contour(
np.sqrt((x - 3) ** 2 + (y - 2) ** 2),
extent=[-2.03, 4.2, -1.6, 3.2],
cmap=plt.cm.gnuplot,
)
plt.clabel(contours, inline=1, fmt="%1.1f ", fontsize=14)
plt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], "k", linewidth=2)
plt.fill_between([-1.5, 0, 1.5], [0, -1.5, 0], [0, 1.5, 0], color=".8")
plt.axvline(0, color="k")
plt.axhline(0, color="k")

plt.text(-0.9, 2.8, "$x_2$", size=20)


plt.text(3.6, -0.6, "$x_1$", size=20)
plt.axis("tight")
plt.axis("off")

# And now plot the optimization path


accumulator = []

def f(x):
# Store the list of function calls
accumulator.append(x)
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)

(continues on next page)

13.4. Examples for the mathematical optimization chapter 454


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


def constraint(x):
return np.atleast_1d(1.5 - np.sum(np.abs(x)))

sp.optimize.minimize(
f, np.array([0, 0]), method="SLSQP", constraints={"fun": constraint, "type": "ineq
˓→"}

accumulated = np.array(accumulator)
plt.plot(accumulated[:, 0], accumulated[:, 1])

plt.show()

Total running time of the script: (0 minutes 0.055 seconds)

13.4.7 Brent’s method

Illustration of 1D optimization: Brent’s method

13.4. Examples for the mathematical optimization chapter 455


Scientific Python Lectures, Edition 2024.2rc0.dev0

Converged at 6
Converged at 23

import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

x = np.linspace(-1, 3, 100)
x_0 = np.exp(-1)

def f(x):
return (x - x_0) ** 2 + epsilon * np.exp(-5 * (x - 0.5 - x_0) ** 2)

for epsilon in (0, 1):


plt.figure(figsize=(3, 2.5))
plt.axes([0, 0, 1, 1])
(continues on next page)

13.4. Examples for the mathematical optimization chapter 456


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# A convex function
plt.plot(x, f(x), linewidth=2)

# Apply brent method. To have access to the iteration, do this in an


# artificial way: allow the algorithm to iter only once
all_x = []
all_y = []
for iter in range(30):
result = sp.optimize.minimize_scalar(
f,
bracket=(-5, 2.9, 4.5),
method="Brent",
options={"maxiter": iter},
tol=np.finfo(1.0).eps,
)
if result.success:
print("Converged at ", iter)
break

this_x = result.x
all_x.append(this_x)
all_y.append(f(this_x))
if iter < 6:
plt.text(
this_x - 0.05 * np.sign(this_x) - 0.05,
f(this_x) + 1.2 * (0.3 - iter % 2),
iter + 1,
size=12,
)

plt.plot(all_x[:10], all_y[:10], "k+", markersize=12, markeredgewidth=2)

plt.plot(all_x[-1], all_y[-1], "rx", markersize=12)


plt.axis("off")
plt.ylim(ymin=-1, ymax=8)

plt.figure(figsize=(4, 3))
plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2)
plt.ylabel("Error on f(x)")
plt.xlabel("Iteration")
plt.tight_layout()

plt.show()

Total running time of the script: (0 minutes 0.285 seconds)

13.4. Examples for the mathematical optimization chapter 457


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.8 Constraint optimization: visualizing the geometry

A small figure explaining optimization with constraints

import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05]
x = x.T
y = y.T

for i in (1, 2):


# Create 2 figure: only the second one will have the optimization
# path
plt.figure(i, figsize=(3, 2.5))
plt.clf()
plt.axes([0, 0, 1, 1])

contours = plt.contour(
np.sqrt((x - 3) ** 2 + (y - 2) ** 2),
extent=[-3, 6, -2.5, 5],
cmap=plt.cm.gnuplot,
)
plt.clabel(contours, inline=1, fmt="%1.1f ", fontsize=14)
plt.plot(
(continues on next page)

13.4. Examples for the mathematical optimization chapter 458


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[-1.5, -1.5, 1.5, 1.5, -1.5], [-1.5, 1.5, 1.5, -1.5, -1.5], "k", linewidth=2
)
plt.fill_between([-1.5, 1.5], [-1.5, -1.5], [1.5, 1.5], color=".8")
plt.axvline(0, color="k")
plt.axhline(0, color="k")

plt.text(-0.9, 4.4, "$x_2$", size=20)


plt.text(5.6, -0.6, "$x_1$", size=20)
plt.axis("equal")
plt.axis("off")

# And now plot the optimization path


accumulator = []

def f(x):
# Store the list of function calls
accumulator.append(x)
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)

# We don't use the gradient, as with the gradient, L-BFGS is too fast,
# and finds the optimum without showing us a pretty path
def f_prime(x):
r = np.sqrt((x[0] - 3) ** 2 + (x[0] - 2) ** 2)
return np.array(((x[0] - 3) / r, (x[0] - 2) / r))

sp.optimize.minimize(
f, np.array([0, 0]), method="L-BFGS-B", bounds=((-1.5, 1.5), (-1.5, 1.5))
)

accumulated = np.array(accumulator)
plt.plot(accumulated[:, 0], accumulated[:, 1])

plt.show()

Total running time of the script: (0 minutes 0.102 seconds)

13.4.9 Alternating optimization

The challenge here is that Hessian of the problem is a very ill-conditioned matrix. This can easily be
seen, as the Hessian of the first term in simply 2 * K.T @ K. Thus the conditioning of the problem can
be judged from looking at the conditioning of K.

import time

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

K = rng.normal(size=(100, 100))
(continues on next page)

13.4. Examples for the mathematical optimization chapter 459


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

def f(x):
return np.sum((K @ (x - 1)) ** 2) + np.sum(x**2) ** 2

def f_prime(x):
return 2 * K.T @ K @ (x - 1) + 4 * np.sum(x**2) * x

def hessian(x):
H = 2 * K.T @ K + 4 * 2 * x * x[:, np.newaxis]
return H + 4 * np.eye(H.shape[0]) * np.sum(x**2)

Some pretty plotting

plt.figure(1)
plt.clf()
Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j]
# Complete in the additional dimensions with zeros
Z = np.reshape(Z, (2, -1)).copy()
Z.resize((100, Z.shape[-1]))
Z = np.apply_along_axis(f, 0, Z)
Z = np.reshape(Z, X.shape)
plt.imshow(Z.T, cmap=plt.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], origin="lower")
plt.contour(X, Y, Z, cmap=plt.cm.gnuplot)

# A reference but slow solution:


t0 = time.time()
x_ref = sp.optimize.minimize(f, K[0], method="Powell").x
print(f" Powell: time { time.time() - t0: .2f} s")
f_ref = f(x_ref)

# Compare different approaches


t0 = time.time()
x_bfgs = sp.optimize.minimize(f, K[0], method="BFGS").x
print(
f" BFGS: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_bfgs -␣
˓→x_ref) ** 2)): .2f} , f error { f(x_bfgs) - f_ref: .2f} "

t0 = time.time()
x_l_bfgs = sp.optimize.minimize(f, K[0], method="L-BFGS-B").x
print(
f" L-BFGS: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_l_bfgs -
˓→ x_ref) ** 2)): .2f} , f error { f(x_l_bfgs) - f_ref: .2f} "

t0 = time.time()
x_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="BFGS").x
print(
f" BFGS w f': time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_bfgs -␣
˓→x_ref) ** 2)): .2f} , f error { f(x_bfgs) - f_ref: .2f} "

(continues on next page)

13.4. Examples for the mathematical optimization chapter 460


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


t0 = time.time()
x_l_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="L-BFGS-B").x
print(
f"L-BFGS w f': time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_l_bfgs -
˓→ x_ref) ** 2)): .2f} , f error { f(x_l_bfgs) - f_ref: .2f} "

t0 = time.time()
x_newton = sp.optimize.minimize(
f, K[0], jac=f_prime, hess=hessian, method="Newton-CG"
).x
print(
f" Newton: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_newton -
˓→ x_ref) ** 2)): .2f} , f error { f(x_newton) - f_ref: .2f} "

plt.show()

Powell: time 0.20s


BFGS: time 0.90s, x error 0.02, f error -0.03
L-BFGS: time 0.07s, x error 0.02, f error -0.03
BFGS w f': time 0.06s, x error 0.02, f error -0.03
L-BFGS w f': time 0.00s, x error 0.02, f error -0.03
Newton: time 0.00s, x error 0.02, f error -0.03

Total running time of the script: (0 minutes 1.533 seconds)

13.4. Examples for the mathematical optimization chapter 461


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.10 Plotting the comparison of optimizers

Plots the results from the comparison of optimizers.

import pickle
import sys

import numpy as np
import matplotlib.pyplot as plt

results = pickle.load(
open(f"helper/compare_optimizers_py{ sys.version_info[0]} .pkl", "rb")
)
n_methods = len(list(results.values())[0]["Rosenbrock "])
n_dims = len(results)

symbols = "o>*Ds"

plt.figure(1, figsize=(10, 4))


plt.clf()

colors = plt.cm.nipy_spectral(np.linspace(0, 1, n_dims))[:, :3]

method_names = list(list(results.values())[0]["Rosenbrock "].keys())


method_names.sort(key=lambda x: x[::-1], reverse=True)

for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate(


zip(sorted(results.items()), colors, strict=True)
):
for (cost_name, cost_bench), symbol in zip(
sorted(n_dim_bench.items()), symbols, strict=True
):
for (
method_index,
method_name,
) in enumerate(method_names):
this_bench = cost_bench[method_name]
bench = np.mean(this_bench)
plt.semilogy(
[
method_index + 0.1 * n_dim_index,
],
(continues on next page)

13.4. Examples for the mathematical optimization chapter 462


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[
bench,
],
marker=symbol,
color=color,
)

# Create a legend for the problem type


for cost_name, symbol in zip(sorted(n_dim_bench.keys()), symbols, strict=True):
plt.semilogy(
[
-10,
],
[
0,
],
symbol,
color=".5",
label=cost_name,
)

plt.xticks(np.arange(n_methods), method_names, size=11)


plt.xlim(-0.2, n_methods - 0.5)
plt.legend(loc="best", numpoints=1, handletextpad=0, prop={"size": 12}, frameon=False)
plt.ylabel("# function calls (a.u.)")

# Create a second legend for the problem dimensionality


plt.twinx()

for n_dim, color in zip(sorted(results.keys()), colors, strict=True):


plt.plot(
[
-10,
],
[
0,
],
"o",
color=color,
label="# dim: %i " % n_dim,
)
plt.legend(
loc=(0.47, 0.07),
numpoints=1,
handletextpad=0,
prop={"size": 12},
frameon=False,
ncol=2,
)
plt.xlim(-0.2, n_methods - 0.5)

plt.xticks(np.arange(n_methods), method_names)
plt.yticks(())

plt.tight_layout()
plt.show()

13.4. Examples for the mathematical optimization chapter 463


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.621 seconds)

13.4.11 Gradient descent

An example demoing gradient descent by creating figures that trace the evolution of the optimizer.
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp

import sys
import os

sys.path.append(os.path.abspath("helper"))
from cost_functions import (
mk_quad,
mk_gauss,
rosenbrock,
rosenbrock_prime,
rosenbrock_hessian,
LoggingFunction,
CountingFunction,
)

x_min, x_max = -1, 2


y_min, y_max = 2.25 / 3 * x_min - 0.2, 2.25 / 3 * x_max - 0.2

A formatter to print values on contours


def super_fmt(value):
if value > 1:
if np.abs(int(value) - value) < 0.1:
out = f"$10^{{{ int(value): d}}} $"
else:
out = f"$10^{{{ value: .1f}}} $"
else:
value = np.exp(value - 0.01)
if value > 0.1:
out = f"{ value: 1.1f} "
elif value > 0.01:
out = f"{ value: .2f} "
else:
out = f"{ value: .2e} "
return out

A gradient descent algorithm do not use: its a toy, use scipy’s optimize.fmin_cg
def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False):
x_i, y_i = x0
all_x_i = []
all_y_i = []
all_f_i = []

for i in range(1, 100):


all_x_i.append(x_i)
all_y_i.append(y_i)
(continues on next page)

13.4. Examples for the mathematical optimization chapter 464


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


all_f_i.append(f([x_i, y_i]))
dx_i, dy_i = f_prime(np.asarray([x_i, y_i]))
if adaptative:
# Compute a step size using a line_search to satisfy the Wolf
# conditions
step = sp.optimize.line_search(
f,
f_prime,
np.r_[x_i, y_i],
-np.r_[dx_i, dy_i],
np.r_[dx_i, dy_i],
c2=0.05,
)
step = step[0]
if step is None:
step = 0
else:
step = 1
x_i += -step * dx_i
y_i += -step * dy_i
if np.abs(all_f_i[-1]) < 1e-16:
break
return all_x_i, all_y_i, all_f_i

def gradient_descent_adaptative(x0, f, f_prime, hessian=None):


return gradient_descent(x0, f, f_prime, adaptative=True)

def conjugate_gradient(x0, f, f_prime, hessian=None):


all_x_i = [x0[0]]
all_y_i = [x0[1]]
all_f_i = [f(x0)]

def store(X):
x, y = X
all_x_i.append(x)
all_y_i.append(y)
all_f_i.append(f(X))

sp.optimize.minimize(
f, x0, jac=f_prime, method="CG", callback=store, options={"gtol": 1e-12}
)
return all_x_i, all_y_i, all_f_i

def newton_cg(x0, f, f_prime, hessian):


all_x_i = [x0[0]]
all_y_i = [x0[1]]
all_f_i = [f(x0)]

def store(X):
x, y = X
all_x_i.append(x)
all_y_i.append(y)
all_f_i.append(f(X))
(continues on next page)

13.4. Examples for the mathematical optimization chapter 465


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

sp.optimize.minimize(
f,
x0,
method="Newton-CG",
jac=f_prime,
hess=hessian,
callback=store,
options={"xtol": 1e-12},
)
return all_x_i, all_y_i, all_f_i

def bfgs(x0, f, f_prime, hessian=None):


all_x_i = [x0[0]]
all_y_i = [x0[1]]
all_f_i = [f(x0)]

def store(X):
x, y = X
all_x_i.append(x)
all_y_i.append(y)
all_f_i.append(f(X))

sp.optimize.minimize(
f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-12}
)
return all_x_i, all_y_i, all_f_i

def powell(x0, f, f_prime, hessian=None):


all_x_i = [x0[0]]
all_y_i = [x0[1]]
all_f_i = [f(x0)]

def store(X):
x, y = X
all_x_i.append(x)
all_y_i.append(y)
all_f_i.append(f(X))

sp.optimize.minimize(
f, x0, method="Powell", callback=store, options={"ftol": 1e-12}
)
return all_x_i, all_y_i, all_f_i

def nelder_mead(x0, f, f_prime, hessian=None):


all_x_i = [x0[0]]
all_y_i = [x0[1]]
all_f_i = [f(x0)]

def store(X):
x, y = X
all_x_i.append(x)
all_y_i.append(y)
(continues on next page)

13.4. Examples for the mathematical optimization chapter 466


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


all_f_i.append(f(X))

sp.optimize.minimize(
f, x0, method="Nelder-Mead", callback=store, options={"ftol": 1e-12}
)
return all_x_i, all_y_i, all_f_i

Run different optimizers on these problems

levels = {}

for index, ((f, f_prime, hessian), optimizer) in enumerate(


(
(mk_quad(0.7), gradient_descent),
(mk_quad(0.7), gradient_descent_adaptative),
(mk_quad(0.02), gradient_descent),
(mk_quad(0.02), gradient_descent_adaptative),
(mk_gauss(0.02), gradient_descent_adaptative),
(
(rosenbrock, rosenbrock_prime, rosenbrock_hessian),
gradient_descent_adaptative,
),
(mk_gauss(0.02), conjugate_gradient),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), conjugate_gradient),
(mk_quad(0.02), newton_cg),
(mk_gauss(0.02), newton_cg),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), newton_cg),
(mk_quad(0.02), bfgs),
(mk_gauss(0.02), bfgs),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), bfgs),
(mk_quad(0.02), powell),
(mk_gauss(0.02), powell),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), powell),
(mk_gauss(0.02), nelder_mead),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), nelder_mead),
)
):
# Compute a gradient-descent
x_i, y_i = 1.6, 1.1
counting_f_prime = CountingFunction(f_prime)
counting_hessian = CountingFunction(hessian)
logging_f = LoggingFunction(f, counter=counting_f_prime.counter)
all_x_i, all_y_i, all_f_i = optimizer(
np.array([x_i, y_i]), logging_f, counting_f_prime, hessian=counting_hessian
)

# Plot the contour plot


if not max(all_y_i) < y_max:
x_min *= 1.2
x_max *= 1.2
y_min *= 1.2
y_max *= 1.2
x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j]
x = x.T
y = y.T

(continues on next page)

13.4. Examples for the mathematical optimization chapter 467


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.figure(index, figsize=(3, 2.5))
plt.clf()
plt.axes([0, 0, 1, 1])

X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0)


z = np.apply_along_axis(f, 0, X)
log_z = np.log(z + 0.01)
plt.imshow(
log_z,
extent=[x_min, x_max, y_min, y_max],
cmap=plt.cm.gray_r,
origin="lower",
vmax=log_z.min() + 1.5 * log_z.ptp(),
)
contours = plt.contour(
log_z,
levels=levels.get(f),
extent=[x_min, x_max, y_min, y_max],
cmap=plt.cm.gnuplot,
origin="lower",
)
levels[f] = contours.levels
plt.clabel(contours, inline=1, fmt=super_fmt, fontsize=14)

plt.plot(all_x_i, all_y_i, "b-", linewidth=2)


plt.plot(all_x_i, all_y_i, "k+")

plt.plot(logging_f.all_x_i, logging_f.all_y_i, "k.", markersize=2)

plt.plot([0], [0], "rx", markersize=12)

plt.xticks(())
plt.yticks(())
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.draw()

plt.figure(index + 100, figsize=(4, 3))


plt.clf()
plt.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, label="# iterations
˓→")

plt.ylabel("Error on f(x)")
plt.semilogy(
logging_f.counts,
np.maximum(np.abs(logging_f.all_f_i), 1e-30),
linewidth=2,
color="g",
label="# function calls",
)
plt.legend(
loc="upper right",
frameon=True,
prop={"size": 11},
borderaxespad=0,
handlelength=1.5,
handletextpad=0.5,
(continues on next page)

13.4. Examples for the mathematical optimization chapter 468


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


)
plt.tight_layout()
plt.draw()

13.4. Examples for the mathematical optimization chapter 469


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 470


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 471


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 472


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 473


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 474


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 475


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 476


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 477


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 478


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 479


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4. Examples for the mathematical optimization chapter 480


Scientific Python Lectures, Edition 2024.2rc0.dev0

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/scipy/optimize/_
˓→linesearch.py:313: LineSearchWarning: The line search algorithm did not converge

alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2(


/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
˓→mathematical_optimization/examples/plot_gradient_descent.py:69: LineSearchWarning:␣

˓→The line search algorithm did not converge

step = sp.optimize.line_search(
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
˓→mathematical_optimization/examples/plot_gradient_descent.py:233: RuntimeWarning:␣

˓→More than 20 figures have been opened. Figures created through the pyplot interface␣

˓→(`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume␣

˓→too much memory. (To control this warning, see the rcParam `figure.max_open_

˓→warning`). Consider using `matplotlib.pyplot.close()`.

plt.figure(index, figsize=(3, 2.5))


/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
˓→mathematical_optimization/examples/plot_gradient_descent.py:178: OptimizeWarning:␣

˓→Unknown solver options: ftol

sp.optimize.minimize(

Total running time of the script: (0 minutes 7.792 seconds)

13.4. Examples for the mathematical optimization chapter 481


Scientific Python Lectures, Edition 2024.2rc0.dev0

An ill-conditioned
quadratic function:
On a exactly quadratic function,
BFGS is not as fast as Newton’s
method, but still very fast.

An ill-conditioned non-
quadratic function:
Here BFGS does better than
Newton, as its empirical esti-
mate of the curvature is better
than that given by the Hessian.

An ill-conditioned very non-


quadratic function:

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def jacobian(x):
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2, -1], method="BFGS", jac=jacobian)


message: Optimization terminated successfully.
success: True
status: 0
fun: 2.630637192365927e-16
x: [ 1.000e+00 1.000e+00]
nit: 8
jac: [ 6.709e-08 -3.222e-08]
(continues on next page)

13.4. Examples for the mathematical optimization chapter 482


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


hess_inv: [[ 9.999e-01 2.000e+00]
[ 2.000e+00 4.499e+00]]
nfev: 10
njev: 10

L-BFGS: Limited-memory BFGS Sits between BFGS and conjugate gradient: in very high dimensions
(> 250) the Hessian matrix is too costly to compute and invert. L-BFGS keeps a low-rank version. In
addition, box bounds are also supported by L-BFGS-B:

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def jacobian(x):
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2, 2], method="L-BFGS-B", jac=jacobian)


message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL
success: True
status: 0
fun: 1.4417677473...e-15
x: [ 1.000e+00 1.000e+00]
nit: 16
jac: [ 1.023e-07 -2.593e-08]
nfev: 17
njev: 17
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>

13.4.12 Gradient-less methods

A shooting method: the Powell algorithm

Almost a gradient approach

13.4. Examples for the mathematical optimization chapter 483


Scientific Python Lectures, Edition 2024.2rc0.dev0

An ill-conditioned
quadratic function:
Powell’s method isn’t too sensi-
tive to local ill-conditionning in
low dimensions

An ill-conditioned very non-


quadratic function:

Simplex method: the Nelder-Mead

The Nelder-Mead algorithms is a generalization of dichotomy approaches to high-dimensional spaces. The


algorithm works by refining a simplex, the generalization of intervals and triangles to high-dimensional
spaces, to bracket the minimum.
Strong points: it is robust to noise, as it does not rely on computing gradients. Thus it can work
on functions that are not locally smooth such as experimental data points, as long as they display a
large-scale bell-shape behavior. However it is slower than gradient-based methods on smooth, non-noisy
functions.

13.4. Examples for the mathematical optimization chapter 484


Scientific Python Lectures, Edition 2024.2rc0.dev0

An ill-conditioned non-
quadratic function:

An ill-conditioned very non-


quadratic function:

Using the Nelder-Mead solver in scipy.optimize.minimize():

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> sp.optimize.minimize(f, [2, -1], method="Nelder-Mead")
message: Optimization terminated successfully.
success: True
status: 0
fun: 1.11527915993744e-10
x: [ 1.000e+00 1.000e+00]
nit: 58
nfev: 111
final_simplex: (array([[ 1.000e+00, 1.000e+00],
[ 1.000e+00, 1.000e+00],
[ 1.000e+00, 1.000e+00]]), array([ 1.115e-10, 1.537e-10, 4.
˓→988e-10]))

13.4.13 Global optimizers

If your problem does not admit a unique local minimum (which can be hard to test unless the function
is convex), and you do not have prior information to initialize the optimization close to the solution, you
may need a global optimizer.

13.4. Examples for the mathematical optimization chapter 485


Scientific Python Lectures, Edition 2024.2rc0.dev0

Brute force: a grid search

scipy.optimize.brute() evaluates the function on a given grid of parameters and returns the param-
eters corresponding to the minimum value. The parameters are specified with ranges given to numpy.
mgrid. By default, 20 steps are taken in each direction:

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> sp.optimize.brute(f, ((-1, 2), (-1, 2)))
array([1.0000..., 1.0000...])

13.5 Practical guide to optimization with SciPy

13.5.1 Choosing a method

All methods are exposed as the method argument of scipy.optimize.minimize().

Without knowledge of the gradient


• In general, prefer BFGS or L-BFGS, even if you have to approximate numerically
gradients. These are also the default if you omit the parameter method - depending
if the problem has constraints or bounds
• On well-conditioned problems, Powell and Nelder-Mead, both gradient-free
methods, work well in high dimension, but they collapse for ill-conditioned problems.
With knowledge of the gradient
• BFGS or L-BFGS.
• Computational overhead of BFGS is larger than that L-BFGS, itself larger than
that of conjugate gradient. On the other side, BFGS usually needs less function
evaluations than CG. Thus conjugate gradient method is better than BFGS at
optimizing computationally cheap functions.
With the Hessian
• If you can compute the Hessian, prefer the Newton method (Newton-CG or TCG).
If you have noisy measurements
• Use Nelder-Mead or Powell.

13.5. Practical guide to optimization with SciPy 486


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.5.2 Making your optimizer faster

• Choose the right method (see above), do compute analytically the gradient and Hessian, if you
can.
• Use preconditionning when possible.
• Choose your initialization points wisely. For instance, if you are running many similar optimiza-
tions, warm-restart one with the results of another.
• Relax the tolerance if you don’t need precision using the parameter tol.

13.5.3 Computing gradients

Computing gradients, and even more Hessians, is very tedious but worth the effort. Symbolic computa-
tion with Sympy may come in handy.

Warning: A very common source of optimization not converging well is human error in the com-
putation of the gradient. You can use scipy.optimize.check_grad() to check that your gradient
is correct. It returns the norm of the different between the gradient given, and a gradient computed
numerically:
>>> sp.optimize.check_grad(f, jacobian, [2, -1])
2.384185791015625e-07

See also scipy.optimize.approx_fprime() to find your errors.

13.5.4 Synthetic exercices

Exercice: A simple (?) quadratic function

Optimize the following function, using K[0] as a starting point:


rng = np.random.default_rng(27446968)
K = rng.normal(size=(100, 100))

def f(x):
return np.sum((K @ (x - 1))**2) + np.sum(x**2)**2

Time your approach. Find the fastest approach. Why is BFGS not working well?

Exercice: A locally flat minimum

13.5. Practical guide to optimization with SciPy 487


Scientific Python Lectures, Edition 2024.2rc0.dev0

Consider the function exp(-1/(.1*x**2 + y**2). This function admits a minimum in (0, 0). Starting
from an initialization at (1, 1), try to get within 1e-8 of this minimum point.

13.6 Special case: non-linear least-squares

13.6.1 Minimizing the norm of a vector function

Least square problems, minimizing the norm of a vector function, have a specific structure that can be
used in the Levenberg–Marquardt algorithm implemented in scipy.optimize.leastsq().
Lets try to minimize the norm of the following vectorial function:

>>> def f(x):


... return np.arctan(x) - np.arctan(np.linspace(0, 1, len(x)))

>>> x0 = np.zeros(10)
>>> sp.optimize.leastsq(f, x0)
(array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ]), 2)

This took 67 function evaluations (check it with ‘full_output=1’). What if we compute the norm
ourselves and use a good generic optimizer (BFGS):

>>> def g(x):


... return np.sum(f(x)**2)
>>> result = sp.optimize.minimize(g, x0, method="BFGS")
(continues on next page)

13.6. Special case: non-linear least-squares 488


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> result.fun
2.6940...e-11

BFGS needs more function calls, and gives a less precise result.

Note: leastsq is interesting compared to BFGS only if the dimensionality of the output vector is large,
and larger than the number of parameters to optimize.

Warning: If the function is linear, this is a linear-algebra problem, and should be solved with
scipy.linalg.lstsq().

13.6.2 Curve fitting

Least square problems occur often when fitting a non-linear to data. While it is possible to construct our
optimization problem ourselves, SciPy provides a helper function for this purpose: scipy.optimize.
curve_fit():

>>> def f(t, omega, phi):


... return np.cos(omega * t + phi)

>>> x = np.linspace(0, 3, 50)


>>> rng = np.random.default_rng(27446968)
>>> y = f(x, 1.5, 1) + .1*rng.normal(size=50)

>>> sp.optimize.curve_fit(f, x, y)
(array([1.4812..., 0.9999...]), array([[ 0.0003..., -0.0004...],
[-0.0004..., 0.0010...]]))

Exercise

Do the same with omega = 3. What is the difficulty?

13.6. Special case: non-linear least-squares 489


Scientific Python Lectures, Edition 2024.2rc0.dev0

13.7 Optimization with constraints

13.7.1 Box bounds

Box bounds correspond to limiting each of the individual parameters of the optimization. Note that
some problems that are not originally written as box bounds can be rewritten as such via change of vari-
ables. Both scipy.optimize.minimize_scalar() and scipy.optimize.minimize() support bound
constraints with the parameter bounds:

>>> def f(x):


... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2)
>>> sp.optimize.minimize(f, np.array([0, 0]), bounds=((-1.5, 1.5), (-1.5, 1.5)))
message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL
success: True
status: 0
fun: 1.5811388300841898
x: [ 1.500e+00 1.500e+00]
nit: 2
jac: [-9.487e-01 -3.162e-01]
nfev: 9
njev: 3
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>

13.7.2 General constraints

Equality and inequality constraints specified as functions: 𝑓 (𝑥) = 0 and 𝑔(𝑥) < 0.
• scipy.optimize.fmin_slsqp() Sequential least square programming: equality and inequality con-
straints:

>>> def f(x):


... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2)
(continues on next page)

13.7. Optimization with constraints 490


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

>>> def constraint(x):


... return np.atleast_1d(1.5 - np.sum(np.abs(x)))

>>> x0 = np.array([0, 0])


>>> sp.optimize.minimize(f, x0, constraints={"fun": constraint, "type": "ineq"})
message: Optimization terminated successfully
success: True
status: 0
fun: 2.47487373504...
x: [ 1.250e+00 2.500e-01]
nit: 5
jac: [-7.071e-01 -7.071e-01]
nfev: 15
njev: 5

Warning: The above problem is known as the Lasso problem in statistics, and there exist very
efficient solvers for it (for instance in scikit-learn). In general do not use generic solvers when specific
ones exist.

Lagrange multipliers

If you are ready to do a bit of math, many constrained optimization problems can be converted to
non-constrained optimization problems using a mathematical trick known as Lagrange multipliers.

13.8 Full code examples

13.9 Examples for the mathematical optimization chapter

See also:
Other Software
SciPy tries to include the best well-established, general-use, and permissively-licensed optimization al-
gorithms available. However, even better options for a given task may be available in other libraries;
please also see IPOPT and PyGMO.

13.8. Full code examples 491


CHAPTER 14
Interfacing with C

Author: Valentin Haenel


This chapter contains an introduction to the many different routes for making your native code (primarily
C/C++) available from Python, a process commonly referred to wrapping. The goal of this chapter is to
give you a flavour of what technologies exist and what their respective merits and shortcomings are, so
that you can select the appropriate one for your specific needs. In any case, once you do start wrapping,
you almost certainly will want to consult the respective documentation for your selected technique.

Chapters contents

• Introduction
• Python-C-Api
• Ctypes
• SWIG
• Cython
• Summary
• Further Reading and References
• Exercises

492
Scientific Python Lectures, Edition 2024.2rc0.dev0

14.1 Introduction

This chapter covers the following techniques:


• Python-C-Api
• Ctypes
• SWIG (Simplified Wrapper and Interface Generator)
• Cython
These four techniques are perhaps the most well known ones, of which Cython is probably the most
advanced one and the one you should consider using first. The others are also important, if you want to
understand the wrapping problem from different angles. Having said that, there are other alternatives
out there, but having understood the basics of the ones above, you will be in a position to evaluate the
technique of your choice to see if it fits your needs.
The following criteria may be useful when evaluating a technology:
• Are additional libraries required?
• Is the code autogenerated?
• Does it need to be compiled?
• Is there good support for interacting with NumPy arrays?
• Does it support C++?
Before you set out, you should consider your use case. When interfacing with native code, there are
usually two use-cases that come up:
• Existing code in C/C++ that needs to be leveraged, either because it already exists, or because it
is faster.
• Python code too slow, push inner loops to native code
Each technology is demonstrated by wrapping the cos function from math.h. While this is a mostly a
trivial example, it should serve us well to demonstrate the basics of the wrapping solution. Since each
technique also includes some form of NumPy support, this is also demonstrated using an example where
the cosine is computed on some kind of array.
Last but not least, two small warnings:
• All of these techniques may crash (segmentation fault) the Python interpreter, which is (usually)
due to bugs in the C code.
• All the examples have been done on Linux, they should be possible on other operating systems.
• You will need a C compiler for most of the examples.

14.2 Python-C-Api

The Python-C-API is the backbone of the standard Python interpreter (a.k.a CPython). Using this API
it is possible to write Python extension module in C and C++. Obviously, these extension modules can,
by virtue of language compatibility, call any function written in C or C++.
When using the Python-C-API, one usually writes much boilerplate code, first to parse the arguments
that were given to a function, and later to construct the return type.
Advantages
• Requires no additional libraries
• Lots of low-level control
• Entirely usable from C++

14.1. Introduction 493


Scientific Python Lectures, Edition 2024.2rc0.dev0

Disadvantages
• May require a substantial amount of effort
• Much overhead in the code
• Must be compiled
• High maintenance cost
• No forward compatibility across Python versions as C-API changes
• Reference count bugs are easy to create and very hard to track down.

Note: The Python-C-Api example here serves mainly for didactic reasons. Many of the other techniques
actually depend on this, so it is good to have a high-level understanding of how it works. In 99% of the
use-cases you will be better off, using an alternative technique.

Note: Since reference counting bugs are easy to create and hard to track down, anyone really needing
to use the Python C-API should read the section about objects, types and reference counts from the
official python documentation. Additionally, there is a tool by the name of cpychecker which can help
discover common errors with reference counting.

14.2.1 Example

The following C-extension module, make the cos function from the standard math library available to
Python:

/* Example of wrapping cos function from math.h with the Python-C-API. */

# include <Python.h>
# include <math.h>

/* wrapped cosine function */


static PyObject* cos_func(PyObject* self, PyObject* args)
{
double value;
double answer;

/* parse the input, from python float to c double */


if (!PyArg_ParseTuple(args, "d", &value))
return NULL;
/* if the above function returns -1, an appropriate Python exception will
* have been set, and the function simply returns NULL
*/

/* call cos from libm */


answer = cos(value);

/* construct the output from cos, from c double to python float */


return Py_BuildValue("f", answer);
}

/* define functions in module */


static PyMethodDef CosMethods[] =
{
{"cos_func", cos_func, METH_VARARGS, "evaluate the cosine"},
(continues on next page)

14.2. Python-C-Api 494


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


{NULL, NULL, 0, NULL}
};

# if PY_MAJOR_VERSION >= 3
/* module initialization */
/* Python version 3*/
static struct PyModuleDef cModPyDem =
{
PyModuleDef_HEAD_INIT,
"cos_module", "Some documentation",
-1,
CosMethods
};

PyMODINIT_FUNC
PyInit_cos_module(void)
{
return PyModule_Create(&cModPyDem);
}

# else

/* module initialization */
/* Python version 2 */
PyMODINIT_FUNC
initcos_module(void)
{
(void) Py_InitModule("cos_module", CosMethods);
}

# endif

As you can see, there is much boilerplate, both to «massage» the arguments and return types into
place and for the module initialisation. Although some of this is amortised, as the extension grows, the
boilerplate required for each function(s) remains.
The standard python build system distutils supports compiling C-extensions from a setup.py, which
is rather convenient:

from distutils.core import setup, Extension

# define the extension module


cos_module = Extension("cos_module", sources=["cos_module.c"])

# run the setup


setup(ext_modules=[cos_module])

This can be compiled:

$ cd advanced/interfacing_with_c/python_c_api

$ ls
cos_module.c setup.py

$ python setup.py build_ext --inplace


running build_ext
building 'cos_module' extension
(continues on next page)

14.2. Python-C-Api 495


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


creating build
creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/

˓→temp.linux-x86_64-2.7/cos_module.o

gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/


˓→lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/

˓→interfacing_with_c/python_c_api/cos_module.so

$ ls
build/ cos_module.c cos_module.so setup.py

• build_ext is to build extension modules


• --inplace will output the compiled extension module into the current directory
The file cos_module.so contains the compiled extension, which we can now load in the IPython inter-
preter:

Note: In Python 3, the filename for compiled modules includes metadata on the Python interpreter
(see PEP 3149) and is thus longer. The import statement is not affected by this.

In [1]: import cos_module

In [2]: cos_module?
Type: module
String Form:<module 'cos_module' from 'cos_module.so'>
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_
˓→with_c/python_c_api/cos_module.so

Docstring: <no docstring>

In [3]: dir(cos_module)
Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func']

In [4]: cos_module.cos_func(1.0)
Out[4]: 0.5403023058681398

In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0

In [6]: cos_module.cos_func(3.14159265359)
Out[6]: -1.0

Now let’s see how robust this is:

In [7]: cos_module.cos_func('foo')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
TypeError: a float is required

14.2. Python-C-Api 496


Scientific Python Lectures, Edition 2024.2rc0.dev0

14.2.2 NumPy Support

Analog to the Python-C-API, NumPy, which is itself implemented as a C-extension, comes with the
NumPy-C-API. This API can be used to create and manipulate NumPy arrays from C, when writing a
custom C-extension. See also: Advanced NumPy.

Note: If you do ever need to use the NumPy C-API refer to the documentation about Arrays and
Iterators.

The following example shows how to pass NumPy arrays as arguments to functions and how to iterate
over NumPy arrays using the (old) NumPy-C-API. It simply takes an array as argument applies the
cosine function from the math.h and returns a resulting new array.

/* Example of wrapping the cos function from math.h using the NumPy-C-API. */

# include <Python.h>
# include <numpy/arrayobject.h>
# include <math.h>

/* wrapped cosine function */


static PyObject* cos_func_np(PyObject* self, PyObject* args)
{
PyArrayObject *arrays[2]; /* holds input and output array */
PyObject *ret;
NpyIter *iter;
npy_uint32 op_flags[2];
npy_uint32 iterator_flags;
PyArray_Descr *op_dtypes[2];

NpyIter_IterNextFunc *iternext;

/* parse single NumPy array argument */


if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &arrays[0])) {
return NULL;
}

arrays[1] = NULL; /* The result will be allocated by the iterator */

/* Set up and create the iterator */


iterator_flags = (NPY_ITER_ZEROSIZE_OK |
/*
* Enable buffering in case the input is not behaved
* (native byte order or not aligned),
* disabling may speed up some cases when it is known to
* be unnecessary.
*/
NPY_ITER_BUFFERED |
/* Manually handle innermost iteration for speed: */
NPY_ITER_EXTERNAL_LOOP |
NPY_ITER_GROWINNER);

op_flags[0] = (NPY_ITER_READONLY |
/*
* Required that the arrays are well behaved, since the cos
* call below requires this.
(continues on next page)

14.2. Python-C-Api 497


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


*/
NPY_ITER_NBO |
NPY_ITER_ALIGNED);

/* Ask the iterator to allocate an array to write the output to */


op_flags[1] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE;

/*
* Ensure the iteration has the correct type, could be checked
* specifically here.
*/
op_dtypes[0] = PyArray_DescrFromType(NPY_DOUBLE);
op_dtypes[1] = op_dtypes[0];

/* Create the NumPy iterator object: */


iter = NpyIter_MultiNew(2, arrays, iterator_flags,
/* Use input order for output and iteration */
NPY_KEEPORDER,
/* Allow only byte-swapping of input */
NPY_EQUIV_CASTING, op_flags, op_dtypes);
Py_DECREF(op_dtypes[0]); /* The second one is identical. */

if (iter == NULL)
return NULL;

iternext = NpyIter_GetIterNext(iter, NULL);


if (iternext == NULL) {
NpyIter_Deallocate(iter);
return NULL;
}

/* Fetch the output array which was allocated by the iterator: */


ret = (PyObject *)NpyIter_GetOperandArray(iter)[1];
Py_INCREF(ret);

if (NpyIter_GetIterSize(iter) == 0) {
/*
* If there are no elements, the loop cannot be iterated.
* This check is necessary with NPY_ITER_ZEROSIZE_OK.
*/
NpyIter_Deallocate(iter);
return ret;
}

/* The location of the data pointer which the iterator may update */
char **dataptr = NpyIter_GetDataPtrArray(iter);
/* The location of the stride which the iterator may update */
npy_intp *strideptr = NpyIter_GetInnerStrideArray(iter);
/* The location of the inner loop size which the iterator may update */
npy_intp *innersizeptr = NpyIter_GetInnerLoopSizePtr(iter);

/* iterate over the arrays */


do {
npy_intp stride = strideptr[0];
npy_intp count = *innersizeptr;
/* out is always contiguous, so use double */
(continues on next page)

14.2. Python-C-Api 498


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


double *out = (double *)dataptr[1];
char *in = dataptr[0];

/* The output is allocated and guaranteed contiguous (out++ works): */


assert(strideptr[1] == sizeof(double));

/*
* For optimization it can make sense to add a check for
* stride == sizeof(double) to allow the compiler to optimize for that.
*/
while (count--) {
*out = cos(*(double *)in);
out++;
in += stride;
}
} while (iternext(iter));

/* Clean up and return the result */


NpyIter_Deallocate(iter);
return ret;
}

/* define functions in module */


static PyMethodDef CosMethods[] =
{
{"cos_func_np", cos_func_np, METH_VARARGS,
"evaluate the cosine on a NumPy array"},
{NULL, NULL, 0, NULL}
};

# if PY_MAJOR_VERSION >= 3
/* module initialization */
/* Python version 3*/
static struct PyModuleDef cModPyDem = {
PyModuleDef_HEAD_INIT,
"cos_module", "Some documentation",
-1,
CosMethods
};
PyMODINIT_FUNC PyInit_cos_module_np(void) {
PyObject *module;
module = PyModule_Create(&cModPyDem);
if(module==NULL) return NULL;
/* IMPORTANT: this must be called */
import_array();
if (PyErr_Occurred()) return NULL;
return module;
}

# else
/* module initialization */
/* Python version 2 */
PyMODINIT_FUNC initcos_module_np(void) {
PyObject *module;
(continues on next page)

14.2. Python-C-Api 499


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


module = Py_InitModule("cos_module_np", CosMethods);
if(module==NULL) return;
/* IMPORTANT: this must be called */
import_array();
return;
}

# endif

To compile this we can use distutils again. However we need to be sure to include the NumPy headers
by using numpy.get_include().

from distutils.core import setup, Extension


import numpy

# define the extension module


cos_module_np = Extension(
"cos_module_np", sources=["cos_module_np.c"], include_dirs=[numpy.get_include()]
)

# run the setup


setup(ext_modules=[cos_module_np])

To convince ourselves if this does actually works, we run the following test script:

import cos_module_np
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 2 * np.pi, 0.1)


y = cos_module_np.cos_func_np(x)
plt.plot(x, y)
plt.show()

# Below are more specific tests for less common usage


# ---------------------------------------------------

# The function is OK with `x` not having any elements:


x_empty = np.array([], dtype=np.float64)
y_empty = cos_module_np.cos_func_np(x_empty)
assert np.array_equal(y_empty, np.array([], dtype=np.float64))

# The function can handle arbitrary dimensions and non-contiguous data.


# `x_2d` contains the same values, but has a different shape.
# Note: `x_2d.flags` shows it is not contiguous and `x2.ravel() == x`
x_2d = x.repeat(2)[::2].reshape(-1, 3)
y_2d = cos_module_np.cos_func_np(x_2d)
# When reshaped back, the same result is given:
assert np.array_equal(y_2d.ravel(), y)

# The function handles incorrect byte-order fine:


x_not_native_byteorder = x.astype(x.dtype.newbyteorder())
y_not_native_byteorder = cos_module_np.cos_func_np(x_not_native_byteorder)
assert np.array_equal(y_not_native_byteorder, y)

(continues on next page)

14.2. Python-C-Api 500


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# The function fails if the data type is incorrect:
x_incorrect_dtype = x.astype(np.float32)
try:
cos_module_np.cos_func_np(x_incorrect_dtype)
assert 0, "This cannot be reached."
except TypeError:
# A TypeError will be raised, this can be changed by changing the
# casting rule.
pass

And this should result in the following figure:

14.3 Ctypes

Ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling
functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
Advantages
• Part of the Python standard library
• Does not need to be compiled
• Wrapping code entirely in Python
Disadvantages
• Requires code to be wrapped to be available as a shared library (roughly speaking *.dll in Windows
*.so in Linux and *.dylib in Mac OSX.)
• No good support for C++

14.3.1 Example

As advertised, the wrapper code is in pure Python.

"""Example of wrapping cos function from math.h using ctypes."""

import ctypes

# find and load the library

# OSX or linux
from ctypes.util import find_library

(continues on next page)

14.3. Ctypes 501


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


libm = ctypes.cdll.LoadLibrary(find_library("m"))

# Windows
# from ctypes import windll
# libm = cdll.msvcrt

# set the argument type


libm.cos.argtypes = [ctypes.c_double]
# set the return type
libm.cos.restype = ctypes.c_double

def cos_func(arg):
"""Wrapper for cos from math.h"""
return libm.cos(arg)

• Finding and loading the library may vary depending on your operating system, check the docu-
mentation for details
• This may be somewhat deceptive, since the math library exists in compiled form on the system
already. If you were to wrap a in-house library, you would have to compile it first, which may or
may not require some additional effort.
We may now use this, as before:

In [8]: import cos_module

In [9]: cos_module?
Type: module
String Form:<module 'cos_module' from 'cos_module.py'>
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_
˓→with_c/ctypes/cos_module.py

Docstring: <no docstring>

In [10]: dir(cos_module)
Out[10]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'cos_func',
'ctypes',
'find_library',
'libm']

In [11]: cos_module.cos_func(1.0)
Out[11]: 0.5403023058681398

In [12]: cos_module.cos_func(0.0)
Out[12]: 1.0

In [13]: cos_module.cos_func(3.14159265359)
Out[13]: -1.0

As with the previous example, this code is somewhat robust, although the error message is not quite as
helpful, since it does not tell us what the type should be.

14.3. Ctypes 502


Scientific Python Lectures, Edition 2024.2rc0.dev0

In [14]: cos_module.cos_func('foo')
---------------------------------------------------------------------------
ArgumentError Traceback (most recent call last)
<ipython-input-7-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
/home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/ctypes/
˓→cos_module.py in cos_func(arg)

12 def cos_func(arg):
13 ''' Wrapper for cos from math.h '''
---> 14 return libm.cos(arg)
ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type

14.3.2 NumPy Support

NumPy contains some support for interfacing with ctypes. In particular there is support for exporting
certain attributes of a NumPy array as ctypes data-types and there are functions to convert from C
arrays to NumPy arrays and back.
For more information, consult the corresponding section in the NumPy Cookbook and the API docu-
mentation for numpy.ndarray.ctypes and numpy.ctypeslib.
For the following example, let’s consider a C function in a library that takes an input and an output
array, computes the cosine of the input array and stores the result in the output array.
The library consists of the following header file (although this is not strictly needed for this example, we
list it for completeness):

void cos_doubles(double * in_array, double * out_array, int size);

The function implementation resides in the following C source file:

# include <math.h>

/* Compute the cosine of each element in in_array, storing the result in


* out_array. */
void cos_doubles(double * in_array, double * out_array, int size){
int i;
for(i=0;i<size;i++){
out_array[i] = cos(in_array[i]);
}
}

And since the library is pure C, we can’t use distutils to compile it, but must use a combination of
make and gcc:

m.PHONY : clean

libcos_doubles.so : cos_doubles.o
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o

cos_doubles.o : cos_doubles.c
gcc -c -fPIC cos_doubles.c -o cos_doubles.o

clean :
-rm -vf libcos_doubles.so cos_doubles.o cos_doubles.pyc

We can then compile this (on Linux) into the shared library libcos_doubles.so:

14.3. Ctypes 503


Scientific Python Lectures, Edition 2024.2rc0.dev0

$ ls
cos_doubles.c cos_doubles.h cos_doubles.py makefile test_cos_doubles.py
$ make
gcc -c -fPIC cos_doubles.c -o cos_doubles.o
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o
$ ls
cos_doubles.c cos_doubles.o libcos_doubles.so* test_cos_doubles.py
cos_doubles.h cos_doubles.py makefile

Now we can proceed to wrap this library via ctypes with direct support for (certain kinds of) NumPy
arrays:

"""Example of wrapping a C library function that accepts a C double array as


input using the numpy.ctypeslib."""

import numpy as np
import numpy.ctypeslib as npct
from ctypes import c_int

# input type for the cos_doubles function


# must be a double array, with single dimension that is contiguous
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags="CONTIGUOUS")

# load the library, using NumPy mechanisms


libcd = npct.load_library("libcos_doubles", ".")

# setup the return types and argument types


libcd.cos_doubles.restype = None
libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int]

def cos_doubles_func(in_array, out_array):


return libcd.cos_doubles(in_array, out_array, len(in_array))

• Note the inherent limitation of contiguous single dimensional NumPy arrays, since the C functions
requires this kind of buffer.
• Also note that the output array must be preallocated, for example with numpy.zeros() and the
function will write into it’s buffer.
• Although the original signature of the cos_doubles function is ARRAY, ARRAY, int the final
cos_doubles_func takes only two NumPy arrays as arguments.
And, as before, we convince ourselves that it worked:

import numpy as np
import matplotlib.pyplot as plt
import cos_doubles

x = np.arange(0, 2 * np.pi, 0.1)


y = np.empty_like(x)

cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y)
plt.show()

14.3. Ctypes 504


Scientific Python Lectures, Edition 2024.2rc0.dev0

14.4 SWIG

SWIG, the Simplified Wrapper Interface Generator, is a software development tool that connects pro-
grams written in C and C++ with a variety of high-level programming languages, including Python.
The important thing with SWIG is, that it can autogenerate the wrapper code for you. While this is an
advantage in terms of development time, it can also be a burden. The generated file tend to be quite
large and may not be too human readable and the multiple levels of indirection which are a result of the
wrapping process, may be a bit tricky to understand.

Note: The autogenerated C code uses the Python-C-Api.

Advantages
• Can automatically wrap entire libraries given the headers
• Works nicely with C++
Disadvantages
• Autogenerates enormous files
• Hard to debug if something goes wrong
• Steep learning curve

14.4.1 Example

Let’s imagine that our cos function lives in a cos_module which has been written in c and consists of
the source file cos_module.c:

# include <math.h>

double cos_func(double arg){


return cos(arg);
}

and the header file cos_module.h:

double cos_func(double arg);

And our goal is to expose the cos_func to Python. To achieve this with SWIG, we must write an
interface file which contains the instructions for SWIG.

14.4. SWIG 505


Scientific Python Lectures, Edition 2024.2rc0.dev0

/* Example of wrapping cos function from math.h using SWIG. */

%module cos_module
%{
/* the resulting C file should be built as a python extension */
# define SWIG_FILE_WITH_INIT
/* Includes the header in the wrapper code */
# include "cos_module.h"
%}
/* Parse the header file to generate wrappers */
%include "cos_module.h"

As you can see, not too much code is needed here. For this simple example it is enough to simply include
the header file in the interface file, to expose the function to Python. However, SWIG does allow for
more fine grained inclusion/exclusion of functions found in header files, check the documentation for
details.
Generating the compiled wrappers is a two stage process:
1. Run the swig executable on the interface file to generate the files cos_module_wrap.c, which
is the source file for the autogenerated Python C-extension and cos_module.py, which is the
autogenerated pure python module.
2. Compile the cos_module_wrap.c into the _cos_module.so. Luckily, distutils knows how to
handle SWIG interface files, so that our setup.py is simply:

from distutils.core import setup, Extension

setup(ext_modules=[Extension("_cos_module", sources=["cos_module.c", "cos_module.i


˓→"])])

$ cd advanced/interfacing_with_c/swig

$ ls
cos_module.c cos_module.h cos_module.i setup.py

$ python setup.py build_ext --inplace


running build_ext
building '_cos_module' extension
swigging cos_module.i to cos_module_wrap.c
swig -python -o cos_module_wrap.c cos_module.i
creating build
creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/

˓→temp.linux-x86_64-2.7/cos_module.o

gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-


˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module_wrap.c -o␣

˓→build/temp.linux-x86_64-2.7/cos_module_wrap.o

gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o build/temp.linux-x86_64-


˓→2.7/cos_module_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/

˓→scientific-python-lectures/advanced/interfacing_with_c/swig/_cos_module.so

$ ls
build/ cos_module.c cos_module.h cos_module.i cos_module.py _cos_module.so* cos_
˓→module_wrap.c setup.py

We can now load and execute the cos_module as we have done in the previous examples:

14.4. SWIG 506


Scientific Python Lectures, Edition 2024.2rc0.dev0

In [15]: import cos_module

In [16]: cos_module?
Type: module
String Form:<module 'cos_module' from 'cos_module.py'>
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_
˓→with_c/swig/cos_module.py

Docstring: <no docstring>

In [17]: dir(cos_module)
Out[17]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'_cos_module',
'_newclass',
'_object',
'_swig_getattr',
'_swig_property',
'_swig_repr',
'_swig_setattr',
'_swig_setattr_nondynamic',
'cos_func']

In [18]: cos_module.cos_func(1.0)
Out[18]: 0.5403023058681398

In [19]: cos_module.cos_func(0.0)
Out[19]: 1.0

In [20]: cos_module.cos_func(3.14159265359)
Out[20]: -1.0

Again we test for robustness, and we see that we get a better error message (although, strictly speaking
in Python there is no double type):

In [21]: cos_module.cos_func('foo')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
TypeError: in method 'cos_func', argument 1 of type 'double'

14.4.2 NumPy Support

NumPy provides support for SWIG with the numpy.i file. This interface file defines various so-called
typemaps which support conversion between NumPy arrays and C-Arrays. In the following example we
will take a quick look at how such typemaps work in practice.
We have the same cos_doubles function as in the ctypes example:

void cos_doubles(double * in_array, double * out_array, int size);

14.4. SWIG 507


Scientific Python Lectures, Edition 2024.2rc0.dev0

# include <math.h>

/* Compute the cosine of each element in in_array, storing the result in


* out_array. */
void cos_doubles(double * in_array, double * out_array, int size){
int i;
for(i=0;i<size;i++){
out_array[i] = cos(in_array[i]);
}
}

This is wrapped as cos_doubles_func using the following SWIG interface file:

/* Example of wrapping a C function that takes a C double array as input using


* NumPy typemaps for SWIG. */

%module cos_doubles
%{
/* the resulting C file should be built as a python extension */
# define SWIG_FILE_WITH_INIT
/* Includes the header in the wrapper code */
# include "cos_doubles.h"
%}

/* include the NumPy typemaps */


%include "numpy.i"
/* need this for correct module initialization */
%init %{
import_array();
%}

/* typemaps for the two arrays, the second will be modified in-place */
%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)}
%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)}

/* Wrapper for cos_doubles that massages the types */


%inline %{
/* takes as input two NumPy arrays */
void cos_doubles_func(double * in_array, int size_in, double * out_array, int␣
˓→size_out) {

/* calls the original function, providing only the size of the first */
cos_doubles(in_array, out_array, size_in);
}
%}

• To use the NumPy typemaps, we need include the numpy.i file.


• Observe the call to import_array() which we encountered already in the NumPy-C-API example.
• Since the type maps only support the signature ARRAY, SIZE we need to wrap the cos_doubles
as cos_doubles_func which takes two arrays including sizes as input.
• As opposed to the simple SWIG example, we don’t include the cos_doubles.h header, There
is nothing there that we wish to expose to Python since we expose the functionality through
cos_doubles_func.
And, as before we can use distutils to wrap this:

14.4. SWIG 508


Scientific Python Lectures, Edition 2024.2rc0.dev0

from distutils.core import setup, Extension


import numpy

setup(
ext_modules=[
Extension(
"_cos_doubles",
sources=["cos_doubles.c", "cos_doubles.i"],
include_dirs=[numpy.get_include()],
)
]
)

As previously, we need to use include_dirs to specify the location.

$ ls
cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py
$ python setup.py build_ext -i
running build_ext
building '_cos_doubles' extension
swigging cos_doubles.i to cos_doubles_wrap.c
swig -python -o cos_doubles_wrap.c cos_doubles.i
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
creating build
creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

˓→include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-

˓→x86_64-2.7/cos_doubles.o

gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-


˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

˓→include -I/home/esc/anaconda/include/python2.7 -c cos_doubles_wrap.c -o build/temp.

˓→linux-x86_64-2.7/cos_doubles_wrap.o

In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/


˓→include/numpy/ndarraytypes.h:1722,

from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
˓→include/numpy/ndarrayobject.h:17,

from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
˓→include/numpy/arrayobject.h:15,

from cos_doubles_wrap.c:2706:
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_
˓→deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by

˓→#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"

gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_doubles.o build/temp.linux-x86_


˓→64-2.7/cos_doubles_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-

˓→working/scientific-python-lectures/advanced/interfacing_with_c/swig_numpy/_cos_

˓→doubles.so

$ ls
build/ cos_doubles.h cos_doubles.py cos_doubles_wrap.c setup.py
cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i test_cos_doubles.
˓→py

And, as before, we convince ourselves that it worked:

import numpy as np
(continues on next page)

14.4. SWIG 509


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


import matplotlib.pyplot as plt
import cos_doubles

x = np.arange(0, 2 * np.pi, 0.1)


y = np.empty_like(x)

cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y)
plt.show()

14.5 Cython

Cython is both a Python-like language for writing C-extensions and an advanced compiler for this
language. The Cython language is a superset of Python, which comes with additional constructs that
allow you call C functions and annotate variables and class attributes with c types. In this sense one
could also call it a Python with types.
In addition to the basic use case of wrapping native code, Cython supports an additional use-case,
namely interactive optimization. Basically, one starts out with a pure-Python script and incrementally
adds Cython types to the bottleneck code to optimize only those code paths that really matter.
In this sense it is quite similar to SWIG, since the code can be autogenerated but in a sense it also quite
similar to ctypes since the wrapping code can (almost) be written in Python.
While others solutions that autogenerate code can be quite difficult to debug (for example SWIG) Cython
comes with an extension to the GNU debugger that helps debug Python, Cython and C code.

Note: The autogenerated C code uses the Python-C-Api.

Advantages
• Python like language for writing C-extensions
• Autogenerated code
• Supports incremental optimization
• Includes a GNU debugger extension
• Support for C++ (Since version 0.13)
Disadvantages
• Must be compiled
• Requires an additional library ( but only at build time, at this problem can be overcome by shipping
the generated C files)

14.5. Cython 510


Scientific Python Lectures, Edition 2024.2rc0.dev0

14.5.1 Example

The main Cython code for our cos_module is contained in the file cos_module.pyx:
""" Example of wrapping cos function from math.h using Cython. """

cdef extern from "math.h":


double cos(double arg)

def cos_func(arg):
return cos(arg)

Note the additional keywords such as cdef and extern. Also the cos_func is then pure Python.
Again we can use the standard distutils module, but this time we need some additional pieces from
the Cython.Distutils:
from distutils.core import setup, Extension
from Cython.Distutils import build_ext

setup(
cmdclass={"build_ext": build_ext},
ext_modules=[Extension("cos_module", ["cos_module.pyx"])],
)

Compiling this:
$ cd advanced/interfacing_with_c/cython
$ ls
cos_module.pyx setup.py
$ python setup.py build_ext --inplace
running build_ext
cythoning cos_module.pyx to cos_module.c
building 'cos_module' extension
creating build
creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/

˓→temp.linux-x86_64-2.7/cos_module.o

gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/


˓→lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/

˓→interfacing_with_c/cython/cos_module.so

$ ls
build/ cos_module.c cos_module.pyx cos_module.so* setup.py

And running it:


In [22]: import cos_module

In [23]: cos_module?
Type: module
String Form:<module 'cos_module' from 'cos_module.so'>
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_
˓→with_c/cython/cos_module.so

Docstring: <no docstring>

In [24]: dir(cos_module)
Out[24]:
['__builtins__',
(continues on next page)

14.5. Cython 511


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'__doc__',
'__file__',
'__name__',
'__package__',
'__test__',
'cos_func']

In [25]: cos_module.cos_func(1.0)
Out[25]: 0.5403023058681398

In [26]: cos_module.cos_func(0.0)
Out[26]: 1.0

In [27]: cos_module.cos_func(3.14159265359)
Out[27]: -1.0

And, testing a little for robustness, we can see that we get good error messages:

In [28]: cos_module.cos_func('foo')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo')
/home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/
˓→cos_module.so in cos_module.cos_func (cos_module.c:506)()

TypeError: a float is required

Additionally, it is worth noting that Cython ships with complete declarations for the C math library,
which simplifies the code above to become:

""" Simpler example of wrapping cos function from math.h using Cython. """

from libc.math cimport cos

def cos_func(arg):
return cos(arg)

In this case the cimport statement is used to import the cos function.

14.5.2 NumPy Support

Cython has support for NumPy via the numpy.pyx file which allows you to add the NumPy array type
to your Cython code. I.e. like specifying that variable i is of type int, you can specify that variable a
is of type numpy.ndarray with a given dtype. Also, certain optimizations such as bounds checking are
supported. Look at the corresponding section in the Cython documentation. In case you want to pass
NumPy arrays as C arrays to your Cython wrapped C functions, there is a section about this in the
Cython documentation.
In the following example, we will show how to wrap the familiar cos_doubles function using Cython.

void cos_doubles(double * in_array, double * out_array, int size);

# include <math.h>

/* Compute the cosine of each element in in_array, storing the result in


* out_array. */
(continues on next page)

14.5. Cython 512


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


void cos_doubles(double * in_array, double * out_array, int size){
int i;
for(i=0;i<size;i++){
out_array[i] = cos(in_array[i]);
}
}

This is wrapped as cos_doubles_func using the following Cython code:


""" Example of wrapping a C function that takes C double arrays as input using
the NumPy declarations from Cython """

# cimport the Cython declarations for NumPy


cimport numpy as np

# if you want to use the NumPy-C-API from Cython


# (not strictly necessary for this example, but good practice)
np.import_array()

# cdefine the signature of our c function


cdef extern from "cos_doubles.h":
void cos_doubles (double * in_array, double * out_array, int size)

# create the wrapper code, with NumPy type annotations


def cos_doubles_func(np.ndarray[double, ndim=1, mode="c"] in_array not None,
np.ndarray[double, ndim=1, mode="c"] out_array not None):
cos_doubles(<double*> np.PyArray_DATA(in_array),
<double*> np.PyArray_DATA(out_array),
in_array.shape[0])

And can be compiled using distutils:


from distutils.core import setup, Extension
import numpy
from Cython.Distutils import build_ext

setup(
cmdclass={"build_ext": build_ext},
ext_modules=[
Extension(
"cos_doubles",
sources=["_cos_doubles.pyx", "cos_doubles.c"],
include_dirs=[numpy.get_include()],
)
],
)

• As with the previous compiled NumPy examples, we need the include_dirs option.
$ ls
cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py
$ python setup.py build_ext -i
running build_ext
cythoning _cos_doubles.pyx to _cos_doubles.c
building 'cos_doubles' extension
creating build
creating build/temp.linux-x86_64-2.7
(continues on next page)

14.5. Cython 513


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

˓→include -I/home/esc/anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.

˓→linux-x86_64-2.7/_cos_doubles.o

In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/


˓→include/numpy/ndarraytypes.h:1722,

from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
˓→include/numpy/ndarrayobject.h:17,

from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
˓→include/numpy/arrayobject.h:15,

from _cos_doubles.c:253:
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_
˓→deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by

˓→#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"

/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.
˓→h:236: warning: ‘_import_umath’ defined but not used

gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-


˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

˓→include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-

˓→x86_64-2.7/cos_doubles.o

gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_


˓→64-2.7/cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/

˓→scientific-python-lectures/advanced/interfacing_with_c/cython_numpy/cos_doubles.so

$ ls
build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles.
˓→so* setup.py test_cos_doubles.py

And, as before, we convince ourselves that it worked:

import numpy as np
import matplotlib.pyplot as plt
import cos_doubles

x = np.arange(0, 2 * np.pi, 0.1)


y = np.empty_like(x)

cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y)
plt.show()

14.5. Cython 514


Scientific Python Lectures, Edition 2024.2rc0.dev0

14.6 Summary

In this section four different techniques for interfacing with native code have been presented. The table
below roughly summarizes some of the aspects of the techniques.

x Part of CPython Compiled Autogenerated NumPy Support


Python-C-API True True False True
Ctypes True False False True
Swig False True True True
Cython False True True True

Of all three presented techniques, Cython is the most modern and advanced. In particular, the ability
to optimize code incrementally by adding types to your Python code is unique.

14.7 Further Reading and References

• Gaël Varoquaux’s blog post about avoiding data copies provides some insight on how to handle
memory management cleverly. If you ever run into issues with large datasets, this is a reference to
come back to for some inspiration.

14.8 Exercises

Since this is a brand new section, the exercises are considered more as pointers as to what to look at
next, so pick the ones that you find more interesting. If you have good ideas for exercises, please let us
know!
1. Download the source code for each example and compile and run them on your machine.
2. Make trivial changes to each example and convince yourself that this works. ( E.g. change cos for
sin.)
3. Most of the examples, especially the ones involving NumPy may still be fragile and respond badly
to input errors. Look for ways to crash the examples, figure what the problem is and devise a
potential solution. Here are some ideas:
1. Numerical overflow.
2. Input and output arrays that have different lengths.
3. Multidimensional array.
4. Empty array
5. Arrays with non-double types
4. Use the %timeit IPython magic to measure the execution time of the various solutions

14.6. Summary 515


Scientific Python Lectures, Edition 2024.2rc0.dev0

14.8.1 Python-C-API

1. Modify the NumPy example such that the function takes two input arguments, where the second
is the preallocated output array, making it similar to the other NumPy examples.
2. Modify the example such that the function only takes a single input array and modifies this in
place.
3. Try to fix the example to use the new NumPy iterator protocol. If you manage to obtain a working
solution, please submit a pull-request on github.
4. You may have noticed, that the NumPy-C-API example is the only NumPy example that does not
wrap cos_doubles but instead applies the cos function directly to the elements of the NumPy
array. Does this have any advantages over the other techniques.
5. Can you wrap cos_doubles using only the NumPy-C-API. You may need to ensure that the arrays
have the correct type, are one dimensional and contiguous in memory.

14.8.2 Ctypes

1. Modify the NumPy example such that cos_doubles_func handles the preallocation for you, thus
making it more like the NumPy-C-API example.

14.8.3 SWIG

1. Look at the code that SWIG autogenerates, how much of it do you understand?
2. Modify the NumPy example such that cos_doubles_func handles the preallocation for you, thus
making it more like the NumPy-C-API example.
3. Modify the cos_doubles C function so that it returns an allocated array. Can you wrap this using
SWIG typemaps? If not, why not? Is there a workaround for this specific situation? (Hint: you
know the size of the output array, so it may be possible to construct a NumPy array from the
returned double *.)

14.8.4 Cython

1. Look at the code that Cython autogenerates. Take a closer look at some of the comments that
Cython inserts. What do you see?
2. Look at the section Working with NumPy from the Cython documentation to learn how to incre-
mentally optimize a pure python script that uses NumPy.
3. Modify the NumPy example such that cos_doubles_func handles the preallocation for you, thus
making it more like the NumPy-C-API example.

14.8. Exercises 516


Part III

Packages and applications

517
Scientific Python Lectures, Edition 2024.2rc0.dev0

This part of the Scientific Python Lectures is dedicated to various scientific packages useful for extended
needs.

518
CHAPTER 15
Statistics in Python

Author: Gaël Varoquaux

Requirements

• Standard scientific Python environment (NumPy, SciPy, matplotlib)


• Pandas
• Statsmodels
• Seaborn
To install Python and these dependencies, we recommend that you download Anaconda Python or,
preferably, use the package manager if you are under Ubuntu or other linux.

See also:
• Bayesian statistics in Python: This chapter does not cover tools for Bayesian statistics. Of
particular interest for Bayesian modelling is PyMC, which implements a probabilistic programming
language in Python.
• Read a statistics book: The Think stats book is available as free PDF or in print and is a great
introduction to statistics.

Tip: Why Python for statistics?

519
Scientific Python Lectures, Edition 2024.2rc0.dev0

R is a language dedicated to statistics. Python is a general-purpose language with statistics modules. R


has more statistical analysis features than Python, and specialized syntaxes. However, when it comes to
building complex analysis pipelines that mix statistics with e.g. image analysis, text mining, or control
of a physical experiment, the richness of Python is an invaluable asset.

Contents

• Data representation and interaction


– Data as a table
– The pandas data-frame
• Hypothesis testing: comparing two groups
– Student’s t-test: the simplest statistical test
– Paired tests: repeated measurements on the same individuals
• Linear models, multiple factors, and analysis of variance
– “formulas” to specify statistical models in Python
– Multiple Regression: including multiple factors
– Post-hoc hypothesis testing: analysis of variance (ANOVA)
• More visualization: seaborn for statistical exploration
– Pairplot: scatter matrices
– lmplot: plotting a univariate regression
• Testing for interactions
• Full code for the figures
• Solutions to this chapter’s exercises

Tip: In this document, the Python inputs are represented with the sign “>>>”.

Disclaimer: Gender questions


Some of the examples of this tutorial are chosen around gender questions. The reason is that on such
questions controlling the truth of a claim actually matters to many people.

15.1 Data representation and interaction

15.1.1 Data as a table

The setting that we consider for statistical analysis is that of multiple observations or samples described
by a set of different attributes or features. The data can than be seen as a 2D table, or matrix, with
columns giving the different attributes of the data, and rows the observations. For instance, the data
contained in examples/brain_size.csv:

15.1. Data representation and interaction 520


Scientific Python Lectures, Edition 2024.2rc0.dev0

"";"Gender";"FSIQ";"VIQ";"PIQ";"Weight";"Height";"MRI_Count"
"1";"Female";133;132;124;"118";"64.5";816932
"2";"Male";140;150;124;".";"72.5";1001121
"3";"Male";139;123;150;"143";"73.3";1038437
"4";"Male";133;129;128;"172";"68.8";965353
"5";"Female";137;132;134;"147";"65.0";951545

15.1.2 The pandas data-frame

Tip: We will store and manipulate this data in a pandas.DataFrame, from the pandas module. It is
the Python equivalent of the spreadsheet table. It is different from a 2D numpy array as it has named
columns, can contain a mixture of different data types by column, and has elaborate selection and pivotal
mechanisms.

Creating dataframes: reading data files or converting arrays

Separator

It is a CSV file, but the separator is “;”

Reading from a CSV file: Using the above CSV file that gives observations of brain size and weight
and IQ (Willerman et al. 1991), the data are a mixture of numerical and categorical values:

>>> import pandas


>>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".")
>>> data
Unnamed: 0 Gender FSIQ VIQ PIQ Weight Height MRI_Count
0 1 Female 133 132 124 118.0 64.5 816932
1 2 Male 140 150 124 NaN 72.5 1001121
2 3 Male 139 123 150 143.0 73.3 1038437
3 4 Male 133 129 128 172.0 68.8 965353
4 5 Female 137 132 134 147.0 65.0 951545
...

Warning: Missing values


The weight of the second individual is missing in the CSV file. If we don’t specify the missing value
(NA = not available) marker, we will not be able to do statistical analysis.

Creating from arrays: A pandas.DataFrame can also be seen as a dictionary of 1D ‘series’, eg arrays
or lists. If we have 3 numpy arrays:

>>> import numpy as np


>>> t = np.linspace(-6, 6, 20)
>>> sin_t = np.sin(t)
>>> cos_t = np.cos(t)

15.1. Data representation and interaction 521


Scientific Python Lectures, Edition 2024.2rc0.dev0

We can expose them as a pandas.DataFrame:

>>> pandas.DataFrame({'t': t, 'sin': sin_t, 'cos': cos_t})


t sin cos
0 -6.000000 0.279415 0.960170
1 -5.368421 0.792419 0.609977
2 -4.736842 0.999701 0.024451
3 -4.105263 0.821291 -0.570509
4 -3.473684 0.326021 -0.945363
5 -2.842105 -0.295030 -0.955488
6 -2.210526 -0.802257 -0.596979
7 -1.578947 -0.999967 -0.008151
8 -0.947368 -0.811882 0.583822
...

Other inputs: pandas can input data from SQL, excel files, or other formats. See the pandas docu-
mentation.

Manipulating data

data is a pandas.DataFrame, that resembles R’s dataframe:

>>> data.shape # 40 rows and 8 columns


(40, 8)

>>> data.columns # It has columns


Index(['Unnamed: 0', 'Gender', 'FSIQ', 'VIQ', 'PIQ', 'Weight', 'Height',
'MRI_Count'],
dtype='object')

>>> print(data['Gender']) # Columns can be addressed by name


0 Female
1 Male
2 Male
3 Male
4 Female
...

>>> # Simpler selector


>>> data[data['Gender'] == 'Female']['VIQ'].mean()
109.45

Note: For a quick view on a large dataframe, use its describe method: pandas.DataFrame.describe().

15.1. Data representation and interaction 522


Scientific Python Lectures, Edition 2024.2rc0.dev0

groupby: splitting a dataframe on values of categorical variables:

>>> groupby_gender = data.groupby('Gender')


>>> for gender, value in groupby_gender['VIQ']:
... print((gender, value.mean()))
('Female', 109.45)
('Male', 115.25)

groupby_gender is a powerful object that exposes many operations on the resulting group of dataframes:

>>> groupby_gender.mean()
Unnamed: 0 FSIQ VIQ PIQ Weight Height MRI_Count
Gender
Female 19.65 111.9 109.45 110.45 137.200000 65.765000 862654.6
Male 21.35 115.0 115.25 111.60 166.444444 71.431579 954855.4

Tip: Use tab-completion on groupby_gender to find more. Other common grouping functions are
median, count (useful for checking to see the amount of missing values in different subsets) or sum.
Groupby evaluation is lazy, no work is done until an aggregation function is applied.

Exercise

• What is the mean value for VIQ for the full population?
• How many males/females were included in this study?
Hint use ‘tab completion’ to find out the methods that can be called, instead of ‘mean’ in the
above example.
• What is the average value of MRI counts expressed in log units, for males and females?

Note: groupby_gender.boxplot is used for the plots above (see this example).

15.1. Data representation and interaction 523


Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting data

Pandas comes with some plotting tools (pandas.plotting, using matplotlib behind the scene) to display
statistics of the data in dataframes:
Scatter matrices:

>>> from pandas import plotting


>>> plotting.scatter_matrix(data[['Weight', 'Height', 'MRI_Count']])
array([[<Axes: xlabel='Weight', ylabel='Weight'>,
<Axes: xlabel='Height', ylabel='Weight'>,
<Axes: xlabel='MRI_Count', ylabel='Weight'>],
[<Axes: xlabel='Weight', ylabel='Height'>,
<Axes: xlabel='Height', ylabel='Height'>,
<Axes: xlabel='MRI_Count', ylabel='Height'>],
[<Axes: xlabel='Weight', ylabel='MRI_Count'>,
<Axes: xlabel='Height', ylabel='MRI_Count'>,
<Axes: xlabel='MRI_Count', ylabel='MRI_Count'>]], dtype=object)

>>> plotting.scatter_matrix(data[['PIQ', 'VIQ', 'FSIQ']])


array([[<Axes: xlabel='PIQ', ylabel='PIQ'>,
<Axes: xlabel='VIQ', ylabel='PIQ'>,
<Axes: xlabel='FSIQ', ylabel='PIQ'>],
[<Axes: xlabel='PIQ', ylabel='VIQ'>,
<Axes: xlabel='VIQ', ylabel='VIQ'>,
<Axes: xlabel='FSIQ', ylabel='VIQ'>],
[<Axes: xlabel='PIQ', ylabel='FSIQ'>,
<Axes: xlabel='VIQ', ylabel='FSIQ'>,
<Axes: xlabel='FSIQ', ylabel='FSIQ'>]], dtype=object)

Two populations

The IQ metrics are bimodal, as if there are 2 sub-populations.

15.1. Data representation and interaction 524


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise

Plot the scatter matrix for males only, and for females only. Do you think that the 2 sub-populations
correspond to gender?

15.2 Hypothesis testing: comparing two groups

For simple statistical tests, we will use the scipy.stats sub-module of SciPy:

>>> import scipy as sp

See also:
SciPy is a vast library. For a quick summary to the whole library, see the scipy chapter.

15.2.1 Student’s t-test: the simplest statistical test

15.2. Hypothesis testing: comparing two groups 525


Scientific Python Lectures, Edition 2024.2rc0.dev0

One-sample tests: testing the value of a population mean

scipy.stats.ttest_1samp() tests the null hypothesis that the mean of the population underlying the
data is equal to a given value. It returns the T statistic, and the p-value (see the function’s help):

>>> sp.stats.ttest_1samp(data['VIQ'], 0)
TtestResult(statistic=30.088099970..., pvalue=1.32891964...e-28, df=39)

The p-value of 10− 28 indicates that such an extreme value of the statistic is unlikely to be observed
under the null hypothesis. This may be taken as evidence that the null hypothesis is false and that the
population mean IQ (VIQ measure) is not 0.
Technically, the p-value of the t-test is derived under the assumption that the means of samples drawn
from the population are normally distributed. This condition is exactly satisfied when the population
itself is normally distributed; however, due to the central limit theorem, the condition is nearly true for
reasonably large samples drawn from populations that follow a variety of non-normal distributions.
Nonetheless, if we are concerned that violation of the normality assumptions will affect the conclusions
of the test, we can use a Wilcoxon signed-rank test, which relaxes this assumption at the expense of test
power:

>>> sp.stats.wilcoxon(data['VIQ'])
WilcoxonResult(statistic=0.0, pvalue=1.8189894...e-12)

Two-sample t-test: testing for difference across populations

We have seen above that the mean VIQ in the male and female samples were different. To test whether
this difference is significant (and suggests that there is a difference in population means), we perform a
two-sample t-test using scipy.stats.ttest_ind():

>>> female_viq = data[data['Gender'] == 'Female']['VIQ']


>>> male_viq = data[data['Gender'] == 'Male']['VIQ']
>>> sp.stats.ttest_ind(female_viq, male_viq)
TtestResult(statistic=-0.77261617232..., pvalue=0.4445287677858..., df=38.0)

The corresponding non-parametric test is the Mann–Whitney U test, scipy.stats.mannwhitneyu().

>>> sp.stats.mannwhitneyu(female_viq, male_viq)


MannwhitneyuResult(statistic=164.5, pvalue=0.34228868687...)

15.2. Hypothesis testing: comparing two groups 526


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.2.2 Paired tests: repeated measurements on the same individuals

PIQ, VIQ, and FSIQ give three measures of IQ. Let us test whether FISQ and PIQ are significantly
different. We can use an “independent sample” test:

>>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ'])


TtestResult(statistic=0.46563759638..., pvalue=0.64277250..., df=78.0)

The problem with this approach is that it ignores an important relationship between observations: FSIQ
and PIQ are measured on the same individuals. Thus, the variance due to inter-subject variability is
confounding, reducing the power of the test. This variability can be removed using a “paired test” or
“repeated measures test”:

>>> sp.stats.ttest_rel(data['FSIQ'], data['PIQ'])


TtestResult(statistic=1.784201940..., pvalue=0.082172638183..., df=39)

This is equivalent to a one-sample test on the differences between paired observations:

>>> sp.stats.ttest_1samp(data['FSIQ'] - data['PIQ'], 0)


TtestResult(statistic=1.784201940..., pvalue=0.082172638..., df=39)

Accordingly, we can perform a nonparametric version of the test with wilcoxon.

>>> sp.stats.wilcoxon(data['FSIQ'], data['PIQ'], method="approx")


WilcoxonResult(statistic=274.5, pvalue=0.106594927135...)

Exercise

• Test the difference between weights in males and females.


• Use non parametric statistics to test the difference between VIQ in males and females.

15.2. Hypothesis testing: comparing two groups 527


Scientific Python Lectures, Edition 2024.2rc0.dev0

Conclusion: we find that the data does not support the hypothesis that males and females have
different VIQ.

15.3 Linear models, multiple factors, and analysis of variance

15.3.1 “formulas” to specify statistical models in Python

A simple linear regression

Given two set of observations, x and y, we want to test the hypothesis that y is a linear function of x.
In other terms:
𝑦 = 𝑥 * coef + intercept + 𝑒
where e is observation noise. We will use the statsmodels module to:
1. Fit a linear model. We will use the simplest strategy, ordinary least squares (OLS).
2. Test that coef is non zero.

First, we generate simulated data according to the model:

>>> import numpy as np


>>> x = np.linspace(-5, 5, 20)
>>> rng = np.random.default_rng(27446968)
>>> # normal distributed noise
>>> y = -5 + 3*x + 4 * rng.normal(size=x.shape)
>>> # Create a data frame containing all the relevant variables
>>> data = pandas.DataFrame({'x': x, 'y': y})

“formulas” for statistics in Python

See the statsmodels documentation

15.3. Linear models, multiple factors, and analysis of variance 528


Scientific Python Lectures, Edition 2024.2rc0.dev0

Then we specify an OLS model and fit it:

>>> from statsmodels.formula.api import ols


>>> model = ols("y ~ x", data).fit()

We can inspect the various statistics derived from the fit:

>>> print(model.summary())
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.901
Model: OLS Adj. R-squared: 0.896
Method: Least Squares F-statistic: 164.5
Date: ... Prob (F-statistic): 1.72e-10
Time: ... Log-Likelihood: -51.758
No. Observations: 20 AIC: 107.5
Df Residuals: 18 BIC: 109.5
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -4.2948 0.759 -5.661 0.000 -5.889 -2.701
x 3.2060 0.250 12.825 0.000 2.681 3.731
==============================================================================
Omnibus: 1.218 Durbin-Watson: 1.796
Prob(Omnibus): 0.544 Jarque-Bera (JB): 0.999
Skew: 0.503 Prob(JB): 0.607
Kurtosis: 2.568 Cond. No. 3.03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

Terminology:

Statsmodels uses a statistical terminology: the y variable in statsmodels is called ‘endogenous’ while
the x variable is called exogenous. This is discussed in more detail here.
To simplify, y (endogenous) is the value you are trying to predict, while x (exogenous) represents the
features you are using to make the prediction.

Exercise

Retrieve the estimated parameters from the model above. Hint: use tab-completion to find the
relevant attribute.

15.3. Linear models, multiple factors, and analysis of variance 529


Scientific Python Lectures, Edition 2024.2rc0.dev0

Categorical variables: comparing groups or multiple categories

Let us go back the data on brain size:

>>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".")

We can write a comparison between IQ of male and female using a linear model:

>>> model = ols("VIQ ~ Gender + 1", data).fit()


>>> print(model.summary())
OLS Regression Results
==============================================================================
Dep. Variable: VIQ R-squared: 0.015
Model: OLS Adj. R-squared: -0.010
Method: Least Squares F-statistic: 0.5969
Date: ... Prob (F-statistic): 0.445
Time: ... Log-Likelihood: -182.42
No. Observations: 40 AIC: 368.8
Df Residuals: 38 BIC: 372.2
Df Model: 1
Covariance Type: nonrobust
==================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------
Intercept 109.4500 5.308 20.619 0.000 98.704 120.196
Gender[T.Male] 5.8000 7.507 0.773 0.445 -9.397 20.997
==============================================================================
Omnibus: 26.188 Durbin-Watson: 1.709
Prob(Omnibus): 0.000 Jarque-Bera (JB): 3.703
Skew: 0.010 Prob(JB): 0.157
Kurtosis: 1.510 Cond. No. 2.62
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

Tips on specifying model

Forcing categorical: the ‘Gender’ is automatically detected as a categorical variable, and thus each
of its different values are treated as different entities.
An integer column can be forced to be treated as categorical using:
>>> model = ols('VIQ ~ C(Gender)', data).fit()

Intercept: We can remove the intercept using - 1 in the formula, or force the use of an intercept
using + 1.

Tip: By default, statsmodels treats a categorical variable with K possible values as K-1 ‘dummy’
boolean variables (the last level being absorbed into the intercept term). This is almost always a
good default choice - however, it is possible to specify different encodings for categorical variables
(https://www.statsmodels.org/devel/contrasts.html).

15.3. Linear models, multiple factors, and analysis of variance 530


Scientific Python Lectures, Edition 2024.2rc0.dev0

Link to t-tests between different FSIQ and PIQ

To compare different types of IQ, we need to create a “long-form” table, listing IQs, where the type
of IQ is indicated by a categorical variable:
>>>data_fisq = pandas.DataFrame({'iq': data['FSIQ'], 'type': 'fsiq'})
>>>data_piq = pandas.DataFrame({'iq': data['PIQ'], 'type': 'piq'})
>>>data_long = pandas.concat((data_fisq, data_piq))
>>>print(data_long)
iq type
0 133 fsiq
1 140 fsiq
2 139 fsiq
3 133 fsiq
4 137 fsiq
... ... ...
35 128 piq
36 124 piq
37 94 piq
38 74 piq
39 89 piq

[80 rows x 2 columns]

>>> model = ols("iq ~ type", data_long).fit()


>>> print(model.summary())
OLS Regression Results
...
==========================...
coef std err t P>|t| [0.025 0.975]
------------------------------------------...
Intercept 113.4500 3.683 30.807 0.000 106.119 120.781
type[T.piq] -2.4250 5.208 -0.466 0.643 -12.793 7.943
...

We can see that we retrieve the same values for t-test and corresponding p-values for the effect of the
type of iq than the previous t-test:
>>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ'])
TtestResult(statistic=0.46563759638..., pvalue=0.64277250..., df=78.0)

15.3.2 Multiple Regression: including multiple factors

15.3. Linear models, multiple factors, and analysis of variance 531


Scientific Python Lectures, Edition 2024.2rc0.dev0

Consider a linear model explaining a variable z (the dependent variable) with 2 variables x and y:
𝑧 = 𝑥 𝑐1 + 𝑦 𝑐2 + 𝑖 + 𝑒
Such a model can be seen in 3D as fitting a plane to a cloud of (x, y, z) points.

Example: the iris data (examples/iris.csv)

Tip: Sepal and petal size tend to be related: bigger flowers are bigger! But is there in addition a
systematic effect of species?

>>> data = pandas.read_csv('examples/iris.csv')


>>> model = ols('sepal_width ~ name + petal_length', data).fit()
>>> print(model.summary())
OLS Regression Results
==========================...
Dep. Variable: sepal_width R-squared: 0.478
Model: OLS Adj. R-squared: 0.468
Method: Least Squares F-statistic: 44.63
Date: ... Prob (F-statistic): 1.58e-20
Time: ... Log-Likelihood: -38.185
No. Observations: 150 AIC: 84.37
Df Residuals: 146 BIC: 96.41
Df Model: 3
Covariance Type: nonrobust
(continues on next page)

15.3. Linear models, multiple factors, and analysis of variance 532


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


==========================...
coef std err t P>|t| [0.025 0.975]
------------------------------------------...
Intercept 2.9813 0.099 29.989 0.000 2.785 3.178
name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124
name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158
petal_length 0.2983 0.061 4.920 0.000 0.178 0.418
==========================...
Omnibus: 2.868 Durbin-Watson: 1.753
Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885
Skew: -0.082 Prob(JB): 0.236
Kurtosis: 3.659 Cond. No. 54.0
==========================...

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

15.3.3 Post-hoc hypothesis testing: analysis of variance (ANOVA)

In the above iris example, we wish to test if the petal length is different between versicolor and virginica,
after removing the effect of sepal width. This can be formulated as testing the difference between the
coefficient associated to versicolor and virginica in the linear model estimated above (it is an Analysis of
Variance, ANOVA). For this, we write a vector of ‘contrast’ on the parameters estimated: we want
to test "name[T.versicolor] - name[T.virginica]", with an F-test:

>>> print(model.f_test([0, 1, -1, 0]))


<F test: F=3.24533535..., p=0.07369..., df_denom=146, df_num=1>

Is this difference significant?

Exercise

Going back to the brain size + IQ data, test if the VIQ of male and female are different after removing
the effect of brain size, height and weight.

15.3. Linear models, multiple factors, and analysis of variance 533


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.4 More visualization: seaborn for statistical exploration

Seaborn combines simple statistical fits with plotting on pandas dataframes.


Let us consider a data giving wages and many other personal information on 500 individuals (Berndt,
ER. The Practice of Econometrics. 1991. NY: Addison-Wesley).

Tip: The full code loading and plotting of the wages data is found in corresponding example.

>>> print(data)
EDUCATION SOUTH SEX EXPERIENCE UNION WAGE AGE RACE \
0 8 0 1 21 0 0.707570 35 2
1 9 0 1 42 0 0.694605 57 3
2 12 0 0 1 0 0.824126 19 3
3 12 0 0 4 0 0.602060 22 3
...

15.4.1 Pairplot: scatter matrices

We can easily have an intuition on the interactions between continuous variables using seaborn.
pairplot() to display a scatter matrix:

>>> import seaborn


>>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'],
... kind='reg')

Categorical variables can be plotted as the hue:

15.4. More visualization: seaborn for statistical exploration 534


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'],


... kind='reg', hue='SEX')

Look and feel and matplotlib settings

Seaborn changes the default of matplotlib figures to achieve a more “modern”, “excel-like” look. It
does that upon import. You can reset the default using:
>>> import matplotlib.pyplot as plt
>>> plt.rcdefaults()

Tip: To switch back to seaborn settings, or understand better styling in seaborn, see the relevant
section of the seaborn documentation.

15.4. More visualization: seaborn for statistical exploration 535


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.4.2 lmplot: plotting a univariate regression

A regression capturing the relation between one variable and another, eg wage and eduction, can be
plotted using seaborn.lmplot():

>>> seaborn.lmplot(y='WAGE', x='EDUCATION', data=data)

Robust regression

Tip: Given that, in the above plot, there seems to be a couple of data points that are outside of the
main cloud to the right, they might be outliers, not representative of the population, but driving the
regression.

To compute a regression that is less sensitive to outliers, one must use a robust model. This is done
in seaborn using robust=True in the plotting functions, or in statsmodels by replacing the use of the
OLS by a “Robust Linear Model”, statsmodels.formula.api.rlm().

15.4. More visualization: seaborn for statistical exploration 536


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.5 Testing for interactions

Do wages increase more with education for males than females?

Tip: The plot above is made of two different fits. We need to formulate a single model that tests for a
variance of slope across the two populations. This is done via an “interaction”.

>>> result = sm.ols(formula='wage ~ education + gender + education * gender',


... data=data).fit()
>>> print(result.summary())
...
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 0.2998 0.072 4.173 0.000 0.159 0.441
gender[T.male] 0.2750 0.093 2.972 0.003 0.093 0.457
education 0.0415 0.005 7.647 0.000 0.031 0.052
education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 0.000
==========================...
...

Can we conclude that education benefits males more than females?

Take home messages

• Hypothesis testing and p-values give you the significance of an effect / difference.
• Formulas (with categorical variables) enable you to express rich links in your data.
• Visualizing your data and fitting simple models give insight into the data.

15.5. Testing for interactions 537


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Conditionning (adding factors that can explain all or part of the variation) is an important
modeling aspect that changes the interpretation.

15.6 Full code for the figures

Code examples for the statistics chapter.

15.6.1 Boxplots and paired differences

Plot boxplots for FSIQ, PIQ, and the paired difference between the two: while the spread (error bars)
for FSIQ and PIQ are very large, there is a systematic (common) effect due to the subjects. This effect
is cancelled out in the difference and the spread of the difference (“paired” by subject) is much smaller
than the spread of the individual measures.

15.6. Full code for the figures 538


Scientific Python Lectures, Edition 2024.2rc0.dev0

import pandas

import matplotlib.pyplot as plt

data = pandas.read_csv("brain_size.csv", sep=";", na_values=".")

# Box plot of FSIQ and PIQ (different measures od IQ)


plt.figure(figsize=(4, 3))
data.boxplot(column=["FSIQ", "PIQ"])

# Boxplot of the difference


plt.figure(figsize=(4, 3))
plt.boxplot(data["FSIQ"] - data["PIQ"])
plt.xticks((1,), ("FSIQ - PIQ",))

plt.show()

Total running time of the script: (0 minutes 0.069 seconds)

15.6.2 Plotting simple quantities of a pandas dataframe

This example loads from a CSV file data with mixed numerical and categorical entries, and plots a few
quantities, separately for females and males, thanks to the pandas integrated plotting tool (that uses
matplotlib behind the scene).
See http://pandas.pydata.org/pandas-docs/stable/visualization.html

15.6. Full code for the figures 539


Scientific Python Lectures, Edition 2024.2rc0.dev0

import pandas

(continues on next page)

15.6. Full code for the figures 540


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


data = pandas.read_csv("brain_size.csv", sep=";", na_values=".")

# Box plots of different columns for each gender


groupby_gender = data.groupby("Gender")
groupby_gender.boxplot(column=["FSIQ", "VIQ", "PIQ"])

from pandas import plotting

# Scatter matrices for different columns


plotting.scatter_matrix(data[["Weight", "Height", "MRI_Count"]])
plotting.scatter_matrix(data[["PIQ", "VIQ", "FSIQ"]])

import matplotlib.pyplot as plt

plt.show()

Total running time of the script: (0 minutes 0.579 seconds)

15.6.3 Analysis of Iris petal and sepal sizes

Illustrate an analysis on a real dataset:


• Visualizing the data to formulate intuitions
• Fitting of a linear model
• Hypothesis test of the effect of a categorical variable in the presence of a continuous confound

import matplotlib.pyplot as plt

import pandas
from pandas import plotting

from statsmodels.formula.api import ols

# Load the data


data = pandas.read_csv("iris.csv")

Plot a scatter matrix

# Express the names as categories


categories = pandas.Categorical(data["name"])

# The parameter 'c' is passed to plt.scatter and will control the color
plotting.scatter_matrix(data, c=categories.codes, marker="o")

fig = plt.gcf()
fig.suptitle("blue: setosa, green: versicolor, red: virginica", size=13)

15.6. Full code for the figures 541


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 0.98, 'blue: setosa, green: versicolor, red: virginica')

Statistical analysis

# Let us try to explain the sepal length as a function of the petal


# width and the category of iris

model = ols("sepal_width ~ name + petal_length", data).fit()


print(model.summary())

# Now formulate a "contrast", to test if the offset for versicolor and


# virginica are identical

print("Testing the difference between effect of versicolor and virginica")


print(model.f_test([0, 1, -1, 0]))
plt.show()

OLS Regression Results


==============================================================================
Dep. Variable: sepal_width R-squared: 0.478
Model: OLS Adj. R-squared: 0.468
Method: Least Squares F-statistic: 44.63
Date: Tue, 04 Jun 2024 Prob (F-statistic): 1.58e-20
Time: 22:38:38 Log-Likelihood: -38.185
No. Observations: 150 AIC: 84.37
Df Residuals: 146 BIC: 96.41
Df Model: 3
Covariance Type: nonrobust
(continues on next page)

15.6. Full code for the figures 542


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


======================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------
Intercept 2.9813 0.099 29.989 0.000 2.785 3.178
name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124
name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158
petal_length 0.2983 0.061 4.920 0.000 0.178 0.418
==============================================================================
Omnibus: 2.868 Durbin-Watson: 1.753
Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885
Skew: -0.082 Prob(JB): 0.236
Kurtosis: 3.659 Cond. No. 54.0
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

Testing the difference between effect of versicolor and virginica


<F test: F=3.245335346574177, p=0.07369058781701142, df_denom=146, df_num=1>

Total running time of the script: (0 minutes 0.405 seconds)

15.6.4 Simple Regression

Fit a simple linear regression using ‘statsmodels’, compute corresponding p-values.

# Original author: Thomas Haslwanter

import numpy as np
import matplotlib.pyplot as plt
import pandas

# For statistics. Requires statsmodels 5.0 or more


from statsmodels.formula.api import ols

# Analysis of Variance (ANOVA) on linear models


from statsmodels.stats.anova import anova_lm

Generate and show the data

x = np.linspace(-5, 5, 20)

# To get reproducible values, provide a seed value


rng = np.random.default_rng(27446968)

y = -5 + 3 * x + 4 * np.random.normal(size=x.shape)

# Plot the data


plt.figure(figsize=(5, 4))
plt.plot(x, y, "o")

15.6. Full code for the figures 543


Scientific Python Lectures, Edition 2024.2rc0.dev0

[<matplotlib.lines.Line2D object at 0x7f494c235310>]

Multilinear regression model, calculating fit, P-values, confidence intervals etc.

# Convert the data into a Pandas DataFrame to use the formulas framework
# in statsmodels
data = pandas.DataFrame({"x": x, "y": y})

# Fit the model


model = ols("y ~ x", data).fit()

# Print the summary


print(model.summary())

# Perform analysis of variance on fitted linear model


anova_results = anova_lm(model)

print("\nANOVA results")
print(anova_results)

OLS Regression Results


==============================================================================
Dep. Variable: y R-squared: 0.845
Model: OLS Adj. R-squared: 0.836
Method: Least Squares F-statistic: 97.76
Date: Tue, 04 Jun 2024 Prob (F-statistic): 1.06e-08
Time: 22:38:38 Log-Likelihood: -53.560
No. Observations: 20 AIC: 111.1
Df Residuals: 18 BIC: 113.1
Df Model: 1
Covariance Type: nonrobust
==============================================================================
(continues on next page)

15.6. Full code for the figures 544


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -4.1877 0.830 -5.044 0.000 -5.932 -2.444
x 2.7046 0.274 9.887 0.000 2.130 3.279
==============================================================================
Omnibus: 1.871 Durbin-Watson: 1.930
Prob(Omnibus): 0.392 Jarque-Bera (JB): 0.597
Skew: 0.337 Prob(JB): 0.742
Kurtosis: 3.512 Cond. No. 3.03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

ANOVA results
df sum_sq mean_sq F PR(>F)
x 1.0 1347.476043 1347.476043 97.760281 1.062847e-08
Residual 18.0 248.102486 13.783471 NaN NaN

Plot the fitted model

# Retrieve the parameter estimates


offset, coef = model._results.params
plt.plot(x, x * coef + offset)
plt.xlabel("x")
plt.ylabel("y")

plt.show()

15.6. Full code for the figures 545


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.100 seconds)

15.6.5 Test for an education/gender interaction in wages

Wages depend mostly on education. Here we investigate how this dependence is related to gender: not
only does gender create an offset in wages, it also seems that wages increase more with education for
males than females.
Does our data support this last hypothesis? We will test this using statsmodels’ formulas (http://
statsmodels.sourceforge.net/stable/example_formulas.html).
Load and massage the data

import pandas

import urllib
import os

if not os.path.exists("wages.txt"):
# Download the file if it is not present
urllib.urlretrieve("http://lib.stat.cmu.edu/datasets/CPS_85_Wages", "wages.txt")

# EDUCATION: Number of years of education


# SEX: 1=Female, 0=Male
# WAGE: Wage (dollars per hour)
data = pandas.read_csv(
"wages.txt",
(continues on next page)

15.6. Full code for the figures 546


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


skiprows=27,
skipfooter=6,
sep=None,
header=None,
names=["education", "gender", "wage"],
usecols=[0, 2, 5],
)

# Convert genders to strings (this is particularly useful so that the


# statsmodels formulas detects that gender is a categorical variable)
import numpy as np

data["gender"] = np.choose(data.gender, ["male", "female"])

# Log-transform the wages, because they typically are increased with


# multiplicative factors
data["wage"] = np.log10(data["wage"])

/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/plot_wage_education_gender.py:30: ParserWarning: Falling back␣

˓→to the 'python' engine because the 'c' engine does not support skipfooter; you can␣

˓→avoid this warning by specifying engine='python'.

data = pandas.read_csv(

simple plotting

import seaborn

# Plot 2 linear fits for male and female.


seaborn.lmplot(y="wage", x="education", hue="gender", data=data)

15.6. Full code for the figures 547


Scientific Python Lectures, Edition 2024.2rc0.dev0

<seaborn.axisgrid.FacetGrid object at 0x7f494bfba790>

statistical analysis

import statsmodels.formula.api as sm

# Note that this model is not the plot displayed above: it is one
# joined model for male and female, not separate models for male and
# female. The reason is that a single model enables statistical testing
result = sm.ols(formula="wage ~ education + gender", data=data).fit()
print(result.summary())

OLS Regression Results


==============================================================================
Dep. Variable: wage R-squared: 0.193
Model: OLS Adj. R-squared: 0.190
Method: Least Squares F-statistic: 63.42
Date: Tue, 04 Jun 2024 Prob (F-statistic): 2.01e-25
Time: 22:38:39 Log-Likelihood: 86.654
No. Observations: 534 AIC: -167.3
Df Residuals: 531 BIC: -154.5
Df Model: 2
Covariance Type: nonrobust
==================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------
(continues on next page)

15.6. Full code for the figures 548


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Intercept 0.4053 0.046 8.732 0.000 0.314 0.496
gender[T.male] 0.1008 0.018 5.625 0.000 0.066 0.136
education 0.0334 0.003 9.768 0.000 0.027 0.040
==============================================================================
Omnibus: 4.675 Durbin-Watson: 1.792
Prob(Omnibus): 0.097 Jarque-Bera (JB): 4.876
Skew: -0.147 Prob(JB): 0.0873
Kurtosis: 3.365 Cond. No. 69.7
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

The plots above highlight that there is not only a different offset in wage but also a different slope
We need to model this using an interaction

result = sm.ols(
formula="wage ~ education + gender + education * gender", data=data
).fit()
print(result.summary())

OLS Regression Results


==============================================================================
Dep. Variable: wage R-squared: 0.198
Model: OLS Adj. R-squared: 0.194
Method: Least Squares F-statistic: 43.72
Date: Tue, 04 Jun 2024 Prob (F-statistic): 2.94e-25
Time: 22:38:39 Log-Likelihood: 88.503
No. Observations: 534 AIC: -169.0
Df Residuals: 530 BIC: -151.9
Df Model: 3
Covariance Type: nonrobust
============================================================================================
coef std err t P>|t| [0.025 ␣
˓→0.975]

--------------------------------------------------------------------------------------
˓→------

Intercept 0.2998 0.072 4.173 0.000 0.159 ␣


˓→ 0.441

gender[T.male] 0.2750 0.093 2.972 0.003 0.093 ␣


˓→ 0.457

education 0.0415 0.005 7.647 0.000 0.031 ␣


˓→ 0.052

education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 ␣


˓→ 0.000

==============================================================================
Omnibus: 4.838 Durbin-Watson: 1.825
Prob(Omnibus): 0.089 Jarque-Bera (JB): 5.000
Skew: -0.156 Prob(JB): 0.0821
Kurtosis: 3.356 Cond. No. 194.
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

15.6. Full code for the figures 549


Scientific Python Lectures, Edition 2024.2rc0.dev0

Looking at the p-value of the interaction of gender and education, the data does not support the hy-
pothesis that education benefits males more than female (p-value > 0.05).

import matplotlib.pyplot as plt

plt.show()

Total running time of the script: (0 minutes 0.506 seconds)

15.6.6 Multiple Regression

Calculate using ‘statsmodels’ just the best fit, or all the corresponding statistical parameters.
Also shows how to make 3d plots.

# Original author: Thomas Haslwanter

import numpy as np
import matplotlib.pyplot as plt
import pandas

# For 3d plots. This import is necessary to have 3D plotting below


from mpl_toolkits.mplot3d import Axes3D

# For statistics. Requires statsmodels 5.0 or more


from statsmodels.formula.api import ols

# Analysis of Variance (ANOVA) on linear models


from statsmodels.stats.anova import anova_lm

Generate and show the data

x = np.linspace(-5, 5, 21)
# We generate a 2D grid
X, Y = np.meshgrid(x, x)

# To get reproducible values, provide a seed value


rng = np.random.default_rng(27446968)

# Z is the elevation of this 2D grid


Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape)

# Plot the data


ax = plt.figure().add_subplot(projection="3d")
surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, rstride=1, cstride=1)
ax.view_init(20, -120)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")

15.6. Full code for the figures 550


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(-0.10764513121260137, 0.009865032686848034, 'Z')

Multilinear regression model, calculating fit, P-values, confidence intervals etc.

# Convert the data into a Pandas DataFrame to use the formulas framework
# in statsmodels

# First we need to flatten the data: it's 2D layout is not relevant.


X = X.flatten()
Y = Y.flatten()
Z = Z.flatten()

data = pandas.DataFrame({"x": X, "y": Y, "z": Z})

# Fit the model


model = ols("z ~ x + y", data).fit()

# Print the summary


print(model.summary())

print("\nRetrieving manually the parameter estimates:")


print(model._results.params)
# should be array([-4.99754526, 3.00250049, -0.50514907])

# Perform analysis of variance on fitted linear model


anova_results = anova_lm(model)

print("\nANOVA results")
(continues on next page)

15.6. Full code for the figures 551


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


print(anova_results)

plt.show()

OLS Regression Results


==============================================================================
Dep. Variable: z R-squared: 0.579
Model: OLS Adj. R-squared: 0.577
Method: Least Squares F-statistic: 300.7
Date: Tue, 04 Jun 2024 Prob (F-statistic): 6.43e-83
Time: 22:38:39 Log-Likelihood: -1552.0
No. Observations: 441 AIC: 3110.
Df Residuals: 438 BIC: 3122.
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -4.4332 0.390 -11.358 0.000 -5.200 -3.666
x 3.0861 0.129 23.940 0.000 2.833 3.340
y -0.6856 0.129 -5.318 0.000 -0.939 -0.432
==============================================================================
Omnibus: 0.560 Durbin-Watson: 1.967
Prob(Omnibus): 0.756 Jarque-Bera (JB): 0.651
Skew: -0.077 Prob(JB): 0.722
Kurtosis: 2.893 Cond. No. 3.03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

Retrieving manually the parameter estimates:


[-4.43322435 3.08614608 -0.68556194]

ANOVA results
df sum_sq mean_sq F PR(>F)
x 1.0 38501.973182 38501.973182 573.111646 1.365553e-81
y 1.0 1899.955512 1899.955512 28.281320 1.676135e-07
Residual 438.0 29425.094352 67.180581 NaN NaN

Total running time of the script: (0 minutes 0.119 seconds)

15.6.7 Visualizing factors influencing wages

This example uses seaborn to quickly plot various factors relating wages, experience and eduction.
Seaborn (https://seaborn.pydata.org) is a library that combines visualization and statistical fits to show
trends in data.
Note that importing seaborn changes the matplotlib style to have an “excel-like” feeling. This changes
affect other matplotlib figures. To restore defaults once this example is run, we would need to call
plt.rcdefaults().

15.6. Full code for the figures 552


Scientific Python Lectures, Edition 2024.2rc0.dev0

# Standard library imports


import os

import matplotlib.pyplot as plt

Load the data

import pandas
import requests

if not os.path.exists("wages.txt"):
# Download the file if it is not present
r = requests.get("http://lib.stat.cmu.edu/datasets/CPS_85_Wages")
with open("wages.txt", "wb") as f:
f.write(r.content)

# Give names to the columns


names = [
"EDUCATION: Number of years of education",
"SOUTH: 1=Person lives in South, 0=Person lives elsewhere",
"SEX: 1=Female, 0=Male",
"EXPERIENCE: Number of years of work experience",
"UNION: 1=Union member, 0=Not union member",
"WAGE: Wage (dollars per hour)",
"AGE: years",
"RACE: 1=Other, 2=Hispanic, 3=White",
"OCCUPATION: 1=Management, 2=Sales, 3=Clerical, 4=Service, 5=Professional, 6=Other
˓→",

"SECTOR: 0=Other, 1=Manufacturing, 2=Construction",


"MARR: 0=Unmarried, 1=Married",
]

short_names = [n.split(":")[0] for n in names]

data = pandas.read_csv(
"wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python"
)
data.columns = short_names

# Log-transform the wages, because they typically are increased with


# multiplicative factors
import numpy as np

data["WAGE"] = np.log10(data["WAGE"])

Plot scatter matrices highlighting different aspects

import seaborn

seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg")

seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="SEX")


plt.suptitle("Effect of gender: 1=Female, 0=Male")

seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="RACE")


plt.suptitle("Effect of race: 1=Other, 2=Hispanic, 3=White")

(continues on next page)

15.6. Full code for the figures 553


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="UNION")
plt.suptitle("Effect of union: 1=Union member, 0=Not union member")

15.6. Full code for the figures 554


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.6. Full code for the figures 555


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.6. Full code for the figures 556


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 0.98, 'Effect of union: 1=Union member, 0=Not union member')

Plot a simple regression

seaborn.lmplot(y="WAGE", x="EDUCATION", data=data)

plt.show()

15.6. Full code for the figures 557


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 8.984 seconds)

15.6.8 Air fares before and after 9/11

This is a business-intelligence (BI) like application.


What is interesting here is that we may want to study fares as a function of the year, paired accordingly
to the trips, or forgetting the year, only as a function of the trip endpoints.
Using statsmodels’ linear models, we find that both with an OLS (ordinary least square) and a robust
fit, the intercept and the slope are significantly non-zero: the air fares have decreased between 2000 and
2001, and their dependence on distance travelled has also decreased
# Standard library imports
import os

Load the data


import pandas
import requests

if not os.path.exists("airfares.txt"):
# Download the file if it is not present
r = requests.get(
"https://users.stat.ufl.edu/~winner/data/airq4.dat",
verify=False, # Wouldn't normally do this, but this site's certificate
(continues on next page)

15.6. Full code for the figures 558


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# is not yet distributed
)
with open("airfares.txt", "wb") as f:
f.write(r.content)

# As a separator, ' +' is a regular expression that means 'one of more


# space'
data = pandas.read_csv(
"airfares.txt",
delim_whitespace=True,
header=0,
names=[
"city1",
"city2",
"pop1",
"pop2",
"dist",
"fare_2000",
"nb_passengers_2000",
"fare_2001",
"nb_passengers_2001",
],
)

# we log-transform the number of passengers


import numpy as np

data["nb_passengers_2000"] = np.log10(data["nb_passengers_2000"])
data["nb_passengers_2001"] = np.log10(data["nb_passengers_2001"])

/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/plot_airfare.py:38: FutureWarning: The 'delim_whitespace'␣

˓→keyword in pd.read_csv is deprecated and will be removed in a future version. Use␣

˓→``sep='\s+'`` instead

data = pandas.read_csv(

Make a dataframe with the year as an attribute, instead of separate columns

# This involves a small danse in which we separate the dataframes in 2,


# one for year 2000, and one for 2001, before concatenating again.

# Make an index of each flight


data_flat = data.reset_index()

data_2000 = data_flat[
["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"]
]
# Rename the columns
data_2000.columns = ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers
˓→"]

# Add a column with the year


data_2000.insert(0, "year", 2000)

data_2001 = data_flat[
["city1", "city2", "pop1", "pop2", "dist", "fare_2001", "nb_passengers_2001"]
]
(continues on next page)

15.6. Full code for the figures 559


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Rename the columns
data_2001.columns = ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers
˓→"]

# Add a column with the year


data_2001.insert(0, "year", 2001)

data_flat = pandas.concat([data_2000, data_2001])

Plot scatter matrices highlighting different aspects

import seaborn

seaborn.pairplot(
data_flat, vars=["fare", "dist", "nb_passengers"], kind="reg", markers="."
)

# A second plot, to show the effect of the year (ie the 9/11 effect)
seaborn.pairplot(
data_flat,
vars=["fare", "dist", "nb_passengers"],
kind="reg",
hue="year",
markers=".",
)

15.6. Full code for the figures 560


Scientific Python Lectures, Edition 2024.2rc0.dev0

15.6. Full code for the figures 561


Scientific Python Lectures, Edition 2024.2rc0.dev0

<seaborn.axisgrid.PairGrid object at 0x7f4955859510>

Plot the difference in fare

import matplotlib.pyplot as plt

plt.figure(figsize=(5, 2))
seaborn.boxplot(data.fare_2001 - data.fare_2000)
plt.title("Fare: 2001 - 2000")
plt.subplots_adjust()

plt.figure(figsize=(5, 2))
seaborn.boxplot(data.nb_passengers_2001 - data.nb_passengers_2000)
plt.title("NB passengers: 2001 - 2000")
plt.subplots_adjust()

15.6. Full code for the figures 562


Scientific Python Lectures, Edition 2024.2rc0.dev0


Statistical testing: dependence of fare on distance and number of passengers

import statsmodels.formula.api as sm

result = sm.ols(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit()


print(result.summary())

# Using a robust fit


result = sm.rlm(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit()
print(result.summary())

OLS Regression Results


==============================================================================
Dep. Variable: fare R-squared: 0.275
Model: OLS Adj. R-squared: 0.275
Method: Least Squares F-statistic: 1585.
Date: Tue, 04 Jun 2024 Prob (F-statistic): 0.00
Time: 22:38:56 Log-Likelihood: -45532.
No. Observations: 8352 AIC: 9.107e+04
Df Residuals: 8349 BIC: 9.109e+04
Df Model: 2
Covariance Type: nonrobust
=================================================================================
coef std err t P>|t| [0.025 0.975]
---------------------------------------------------------------------------------
Intercept 211.2428 2.466 85.669 0.000 206.409 216.076
dist 0.0484 0.001 48.149 0.000 0.046 0.050
nb_passengers -32.8925 1.127 -29.191 0.000 -35.101 -30.684
==============================================================================
Omnibus: 604.051 Durbin-Watson: 1.446
Prob(Omnibus): 0.000 Jarque-Bera (JB): 740.733
Skew: 0.710 Prob(JB): 1.42e-161
(continues on next page)

15.6. Full code for the figures 563


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Kurtosis: 3.338 Cond. No. 5.23e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

[2] The condition number is large, 5.23e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
Robust linear Model Regression Results
==============================================================================
Dep. Variable: fare No. Observations: 8352
Model: RLM Df Residuals: 8349
Method: IRLS Df Model: 2
Norm: HuberT
Scale Est.: mad
Cov Type: H1
Date: Tue, 04 Jun 2024
Time: 22:38:56
No. Iterations: 12
=================================================================================
coef std err z P>|z| [0.025 0.975]
---------------------------------------------------------------------------------
Intercept 215.0848 2.448 87.856 0.000 210.287 219.883
dist 0.0460 0.001 46.166 0.000 0.044 0.048
nb_passengers -35.2686 1.119 -31.526 0.000 -37.461 -33.076
=================================================================================

If the model instance has been used for another fit with different fit parameters,␣
˓→then the fit options might not be the correct ones anymore .

Statistical testing: regression of fare on distance: 2001/2000 difference

result = sm.ols(formula="fare_2001 - fare_2000 ~ 1 + dist", data=data).fit()


print(result.summary())

# Plot the corresponding regression


data["fare_difference"] = data["fare_2001"] - data["fare_2000"]
seaborn.lmplot(x="dist", y="fare_difference", data=data)

plt.show()

15.6. Full code for the figures 564


Scientific Python Lectures, Edition 2024.2rc0.dev0

OLS Regression Results


==============================================================================
Dep. Variable: fare_2001 R-squared: 0.159
Model: OLS Adj. R-squared: 0.159
Method: Least Squares F-statistic: 791.7
Date: Tue, 04 Jun 2024 Prob (F-statistic): 1.20e-159
Time: 22:38:56 Log-Likelihood: -22640.
No. Observations: 4176 AIC: 4.528e+04
Df Residuals: 4174 BIC: 4.530e+04
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 148.0279 1.673 88.480 0.000 144.748 151.308
dist 0.0388 0.001 28.136 0.000 0.036 0.041
==============================================================================
Omnibus: 136.558 Durbin-Watson: 1.544
Prob(Omnibus): 0.000 Jarque-Bera (JB): 149.624
Skew: 0.462 Prob(JB): 3.23e-33
Kurtosis: 2.920 Cond. No. 2.40e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

(continues on next page)

15.6. Full code for the figures 565


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[2] The condition number is large, 2.4e+03. This might indicate that there are
strong multicollinearity or other numerical problems.

Total running time of the script: (0 minutes 7.845 seconds)

15.7 Solutions to this chapter’s exercises

15.7.1 Solutions to this chapter’s exercises

Relating Gender and IQ

Going back to the brain size + IQ data, test if the VIQ of male and female are different after removing
the effect of brain size, height and weight.
Notice that here ‘Gender’ is a categorical value. As it is a non-float data type, statsmodels is able to
automatically infer this.

import pandas
from statsmodels.formula.api import ols

data = pandas.read_csv("../brain_size.csv", sep=";", na_values=".")

model = ols("VIQ ~ Gender + MRI_Count + Height", data).fit()


print(model.summary())

# Here, we don't need to define a contrast, as we are testing a single


# coefficient of our model, and not a combination of coefficients.
# However, defining a contrast, which would then be a 'unit contrast',
# will give us the same results
print(model.f_test([0, 1, 0, 0]))

OLS Regression Results


==============================================================================
Dep. Variable: VIQ R-squared: 0.246
Model: OLS Adj. R-squared: 0.181
Method: Least Squares F-statistic: 3.809
Date: Tue, 04 Jun 2024 Prob (F-statistic): 0.0184
Time: 22:38:56 Log-Likelihood: -172.34
No. Observations: 39 AIC: 352.7
Df Residuals: 35 BIC: 359.3
Df Model: 3
Covariance Type: nonrobust
==================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------
Intercept 166.6258 88.824 1.876 0.069 -13.696 346.948
Gender[T.Male] 8.8524 10.710 0.827 0.414 -12.890 30.595
MRI_Count 0.0002 6.46e-05 2.615 0.013 3.78e-05 0.000
Height -3.0837 1.276 -2.417 0.021 -5.674 -0.494
==============================================================================
Omnibus: 7.373 Durbin-Watson: 2.109
Prob(Omnibus): 0.025 Jarque-Bera (JB): 2.252
Skew: 0.005 Prob(JB): 0.324
(continues on next page)

15.7. Solutions to this chapter’s exercises 566


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Kurtosis: 1.823 Cond. No. 2.40e+07
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

[2] The condition number is large, 2.4e+07. This might indicate that there are
strong multicollinearity or other numerical problems.
<F test: F=0.683196084584229, p=0.4140878441244694, df_denom=35, df_num=1>

Here we plot a scatter matrix to get intuitions on our results. This goes beyond what was asked in the
exercise

# This plotting is useful to get an intuitions on the relationships between


# our different variables

from pandas import plotting


import matplotlib.pyplot as plt

# Fill in the missing values for Height for plotting


data["Height"].fillna(method="pad", inplace=True)

# The parameter 'c' is passed to plt.scatter and will control the color
# The same holds for parameters 'marker', 'alpha' and 'cmap', that
# control respectively the type of marker used, their transparency and
# the colormap
plotting.scatter_matrix(
data[["VIQ", "MRI_Count", "Height"]],
c=(data["Gender"] == "Female"),
marker="o",
alpha=1,
cmap="winter",
)

fig = plt.gcf()
fig.suptitle("blue: male, green: female", size=13)

plt.show()

15.7. Solutions to this chapter’s exercises 567


Scientific Python Lectures, Edition 2024.2rc0.dev0

/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/solutions/plot_brain_size.py:39: FutureWarning: A value is␣

˓→trying to be set on a copy of a DataFrame or Series through chained assignment␣

˓→using an inplace method.

The behavior will change in pandas 3.0. This inplace method will never work because␣
˓→the intermediate object on which we are setting values always behaves as a copy.

For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method(


˓→{col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform␣

˓→the operation inplace on the original object.

data["Height"].fillna(method="pad", inplace=True)
/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/solutions/plot_brain_size.py:39: FutureWarning: Series.fillna␣

˓→with 'method' is deprecated and will raise in a future version. Use obj.ffill() or␣

˓→obj.bfill() instead.

data["Height"].fillna(method="pad", inplace=True)

Total running time of the script: (0 minutes 0.253 seconds)

15.7. Solutions to this chapter’s exercises 568


CHAPTER 16
Sympy : Symbolic Mathematics in
Python

Author: Fabian Pedregosa

Objectives

1. Evaluate expressions with arbitrary precision.


2. Perform algebraic manipulations on symbolic expressions.
3. Perform basic calculus tasks (limits, differentiation and
integration) with symbolic expressions.
4. Solve polynomial and transcendental equations.
5. Solve some differential equations.

What is SymPy? SymPy is a Python library for symbolic mathematics. It aims to be an alternative to
systems such as Mathematica or Maple while keeping the code as simple as possible and easily extensible.
SymPy is written entirely in Python and does not require any external libraries.
Sympy documentation and packages for installation can be found on https://www.sympy.org/

Chapters contents

• First Steps with SymPy


– Using SymPy as a calculator
– Symbols

569
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Algebraic manipulations
– Expand
– Simplify
• Calculus
– Limits
– Differentiation
– Series expansion
– Integration
• Equation solving
• Linear Algebra
– Matrices
– Differential Equations

16.1 First Steps with SymPy

16.1.1 Using SymPy as a calculator

SymPy defines three numerical types: Real, Rational and Integer.


The Rational class represents a rational number as a pair of two Integers: the numerator and the
denominator, so Rational(1, 2) represents 1/2, Rational(5, 2) 5/2 and so on:

>>> import sympy as sym


>>> a = sym.Rational(1, 2)

>>> a
1/2

>>> a*2
1

SymPy uses mpmath in the background, which makes it possible to perform computations using
arbitrary-precision arithmetic. That way, some special constants, like 𝑒, 𝑝𝑖, 𝑜𝑜 (Infinity), are treated
as symbols and can be evaluated with arbitrary precision:

>>> sym.pi**2
pi**2

>>> sym.pi.evalf()
3.14159265358979

>>> (sym.pi + sym.exp(1)).evalf()


5.85987448204884

as you see, evalf evaluates the expression to a floating-point number.


There is also a class representing mathematical infinity, called oo:

>>> sym.oo > 99999


True
(continues on next page)

16.1. First Steps with SymPy 570


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> sym.oo + 1
oo

Exercises

1. Calculate 2 with 100 decimals.
2. Calculate 1/2 + 1/3 in rational arithmetic.

16.1.2 Symbols

In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables
explicitly:

>>> x = sym.Symbol('x')
>>> y = sym.Symbol('y')

Then you can manipulate them:

>>> x + y + x - y
2*x

>>> (x + y) ** 2
(x + y)**2

Symbols can now be manipulated using some of python operators: +, -, *, ** (arithmetic), &, |, ~, >>,
<< (boolean).

Printing

Sympy allows for control of the display of the output. From here we use the following setting for
printing:
>>> sym.init_printing(use_unicode=False, wrap_line=True)

16.2 Algebraic manipulations

SymPy is capable of performing powerful algebraic manipulations. We’ll take a look into some of the
most frequently used: expand and simplify.

16.2.1 Expand

Use this to expand an algebraic expression. It will try to denest powers and multiplications:

>>> sym.expand((x + y) ** 3)
3 2 2 3
x + 3*x *y + 3*x*y + y
>>> 3 * x * y ** 2 + 3 * y * x ** 2 + x ** 3 + y ** 3
3 2 2 3
x + 3*x *y + 3*x*y + y

16.2. Algebraic manipulations 571


Scientific Python Lectures, Edition 2024.2rc0.dev0

Further options can be given in form on keywords:

>>> sym.expand(x + y, complex=True)


re(x) + re(y) + I*im(x) + I*im(y)
>>> sym.I * sym.im(x) + sym.I * sym.im(y) + sym.re(x) + sym.re(y)
re(x) + re(y) + I*im(x) + I*im(y)

>>> sym.expand(sym.cos(x + y), trig=True)


-sin(x)*sin(y) + cos(x)*cos(y)
>>> sym.cos(x) * sym.cos(y) - sym.sin(x) * sym.sin(y)
-sin(x)*sin(y) + cos(x)*cos(y)

16.2.2 Simplify

Use simplify if you would like to transform an expression into a simpler form:

>>> sym.simplify((x + x * y) / x)
y + 1

Simplification is a somewhat vague term, and more precises alternatives to simplify exists: powsimp
(simplification of exponents), trigsimp (for trigonometric expressions) , logcombine, radsimp, together.

Exercises

1. Calculate the expanded form of (𝑥 + 𝑦)6 .


2. Simplify the trigonometric expression sin(𝑥)/ cos(𝑥)

16.3 Calculus

16.3.1 Limits

Limits are easy to use in SymPy, they follow the syntax limit(function, variable, point), so to
compute the limit of 𝑓 (𝑥) as 𝑥 → 0, you would issue limit(f, x, 0):

>>> sym.limit(sym.sin(x) / x, x, 0)
1

you can also calculate the limit at infinity:

>>> sym.limit(x, x, sym.oo)


oo

>>> sym.limit(1 / x, x, sym.oo)


0

>>> sym.limit(x ** x, x, 0)
1

16.3. Calculus 572


Scientific Python Lectures, Edition 2024.2rc0.dev0

16.3.2 Differentiation

You can differentiate any SymPy expression using diff(func, var). Examples:

>>> sym.diff(sym.sin(x), x)
cos(x)
>>> sym.diff(sym.sin(2 * x), x)
2*cos(2*x)

>>> sym.diff(sym.tan(x), x)
2
tan (x) + 1

You can check that it is correct by:

>>> sym.limit((sym.tan(x + y) - sym.tan(x)) / y, y, 0)


1
-------
2
cos (x)

Which is equivalent since


1
sec(𝑥) = 𝑎𝑛𝑑 sec2 (𝑥) = tan2 (𝑥) + 1.
cos(𝑥)
You can check this as well:

>>> sym.trigsimp(sym.diff(sym.tan(x), x))


1
-------
2
cos (x)

Higher derivatives can be calculated using the diff(func, var, n) method:

>>> sym.diff(sym.sin(2 * x), x, 1)


2*cos(2*x)

>>> sym.diff(sym.sin(2 * x), x, 2)


-4*sin(2*x)

>>> sym.diff(sym.sin(2 * x), x, 3)


-8*cos(2*x)

16.3.3 Series expansion

SymPy also knows how to compute the Taylor series of an expression at a point. Use series(expr,
var):

>>> sym.series(sym.cos(x), x)
2 4
x x / 6\
1 - -- + -- + O\x /
2 24
>>> sym.series(1/sym.cos(x), x)
2 4
x 5*x / 6\
(continues on next page)

16.3. Calculus 573


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


1 + -- + ---- + O\x /
2 24

Exercises

1. Calculate lim𝑥→0 sin(𝑥)/𝑥


2. Calculate the derivative of 𝑙𝑜𝑔(𝑥) for 𝑥.

16.3.4 Integration

SymPy has support for indefinite and definite integration of transcendental elementary and special func-
tions via integrate() facility, which uses the powerful extended Risch-Norman algorithm and some
heuristics and pattern matching. You can integrate elementary functions:

>>> sym.integrate(6 * x ** 5, x)
6
x
>>> sym.integrate(sym.sin(x), x)
-cos(x)
>>> sym.integrate(sym.log(x), x)
x*log(x) - x
>>> sym.integrate(2 * x + sym.sinh(x), x)
2
x + cosh(x)

Also special functions are handled easily:

>>> sym.integrate(sym.exp(-x ** 2) * sym.erf(x), x)


____ 2
\/ pi *erf (x)
--------------
4

It is possible to compute definite integral:

>>> sym.integrate(x**3, (x, -1, 1))


0
>>> sym.integrate(sym.sin(x), (x, 0, sym.pi / 2))
1
>>> sym.integrate(sym.cos(x), (x, -sym.pi / 2, sym.pi / 2))
2

Also improper integrals are supported as well:

>>> sym.integrate(sym.exp(-x), (x, 0, sym.oo))


1
>>> sym.integrate(sym.exp(-x ** 2), (x, -sym.oo, sym.oo))
____
\/ pi

16.3. Calculus 574


Scientific Python Lectures, Edition 2024.2rc0.dev0

16.4 Equation solving

SymPy is able to solve algebraic equations, in one and several variables using solveset():

>>> sym.solveset(x ** 4 - 1, x)
{-1, 1, -I, I}

As you can see it takes as first argument an expression that is supposed to be equaled to 0. It also has
(limited) support for transcendental equations:

>>> sym.solveset(sym.exp(x) + 1, x)
{I*(2*n*pi + pi) | n in Integers}

Systems of linear equations

Sympy is able to solve a large part of polynomial equations, and is also capable of solving multiple
equations with respect to multiple variables giving a tuple as second argument. To do this you use
the solve() command:
>>> solution = sym.solve((x + 5 * y - 2, -3 * x + 6 * y - 15), (x, y))
>>> solution[x], solution[y]
(-3, 1)

Another alternative in the case of polynomial equations is factor. factor returns the polynomial factorized
into irreducible terms, and is capable of computing the factorization over various domains:

>>> f = x ** 4 - 3 * x ** 2 + 1
>>> sym.factor(f)
/ 2 \ / 2 \
\x - x - 1/*\x + x - 1/

>>> sym.factor(f, modulus=5)


2 2
(x - 2) *(x + 2)

SymPy is also able to solve boolean equations, that is, to decide if a certain boolean expression is
satisfiable or not. For this, we use the function satisfiable:

>>> sym.satisfiable(x & y)


{x: True, y: True}

This tells us that (x & y) is True whenever x and y are both True. If an expression cannot be true, i.e.
no values of its arguments can make the expression True, it will return False:

>>> sym.satisfiable(x & ~x)


False

Exercises

1. Solve the system of equations 𝑥 + 𝑦 = 2, 2 · 𝑥 + 𝑦 = 0


2. Are there boolean values x, y that make (~x | y) & (~y | x) true?

16.4. Equation solving 575


Scientific Python Lectures, Edition 2024.2rc0.dev0

16.5 Linear Algebra

16.5.1 Matrices

Matrices are created as instances from the Matrix class:

>>> sym.Matrix([[1, 0], [0, 1]])


[1 0]
[ ]
[0 1]

unlike a NumPy array, you can also put Symbols in it:

>>> x, y = sym.symbols('x, y')


>>> A = sym.Matrix([[1, x], [y, 1]])
>>> A
[1 x]
[ ]
[y 1]

>>> A**2
[x*y + 1 2*x ]
[ ]
[ 2*y x*y + 1]

16.5.2 Differential Equations

SymPy is capable of solving (some) Ordinary Differential. To solve differential equations, use dsolve.
First, create an undefined function by passing cls=Function to the symbols function:

>>> f, g = sym.symbols('f g', cls=sym.Function)

f and g are now undefined functions. We can call f(x), and it will represent an unknown function:

>>> f(x)
f(x)

>>> f(x).diff(x, x) + f(x)


2
d
f(x) + ---(f(x))
2
dx

>>> sym.dsolve(f(x).diff(x, x) + f(x), f(x))


f(x) = C1*sin(x) + C2*cos(x)

Keyword arguments can be given to this function in order to help if find the best possible resolution sys-
tem. For example, if you know that it is a separable equations, you can use keyword hint='separable'
to force dsolve to resolve it as a separable equation:

>>> sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x),


˓→ f(x), hint='separable')

/ C1 \ / C1 \
[f(x) = - acos|------| + 2*pi, f(x) = acos|------|]
\cos(x)/ \cos(x)/

16.5. Linear Algebra 576


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercises

1. Solve the Bernoulli differential equation

𝑑𝑓 (𝑥)
𝑥 + 𝑓 (𝑥) − 𝑓 (𝑥)2 = 0
𝑥
2. Solve the same equation using hint='Bernoulli'. What do you observe ?

16.5. Linear Algebra 577


CHAPTER 17
scikit-image: image processing

Author: Emmanuelle Gouillart


scikit-image is a Python package dedicated to image processing, using NumPy arrays as image objects.
This chapter describes how to use scikit-image for various image processing tasks, and how it relates
to other scientific Python modules such as NumPy and SciPy.
See also:
For basic image manipulation, such as image cropping or simple filtering, a large number of simple
operations can be realized with NumPy and SciPy only. See Image manipulation and processing using
NumPy and SciPy.
Note that you should be familiar with the content of the previous chapter before reading the current
one, as basic operations such as masking and labeling are a prerequisite.

Chapters contents

• Introduction and concepts


– scikit-image and the scientific Python ecosystem
– What is included in scikit-image
• Importing
• Example data
• Input/output, data types and colorspaces
– Data types
– Colorspaces
• Image preprocessing / enhancement

578
Scientific Python Lectures, Edition 2024.2rc0.dev0

– Local filters
– Non-local filters
– Mathematical morphology
• Image segmentation
– Binary segmentation: foreground + background
– Marker based methods
• Measuring regions’ properties
• Data visualization and interaction
• Feature extraction for computer vision
• Full code examples
• Examples for the scikit-image chapter

17.1 Introduction and concepts

Images are NumPy’s arrays np.ndarray


image
np.ndarray
pixels
array values: a[2, 3]
channels
array dimensions
image encoding
dtype (np.uint8, np.uint16, np.float)
filters
functions (numpy, skimage, scipy)

>>> import numpy as np


>>> check = np.zeros((8, 8))
>>> check[::2, 1::2] = 1
>>> check[1::2, ::2] = 1
>>> import matplotlib.pyplot as plt
>>> plt.imshow(check, cmap='gray', interpolation='nearest')
<matplotlib.image.AxesImage object at ...>

17.1. Introduction and concepts 579


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.1.1 scikit-image and the scientific Python ecosystem

scikit-image is packaged in both pip and conda-based Python installations, as well as in most Linux
distributions. Other Python packages for image processing & visualization that operate on NumPy
arrays include:
scipy.ndimage
For N-dimensional arrays. Basic filtering, mathematical morphology, regions properties
Mahotas
With a focus on high-speed implementations.
Napari
A fast, interactive, multi-dimensional image viewer built in Qt.
Some powerful C++ image processing libraries also have Python bindings:
OpenCV
A highly optimized computer vision library with a focus on real-time applications.
ITK
The Insight ToolKit, especially useful for registration and working with 3D images.
To varying degrees, these tend to be less Pythonic and NumPy-friendly.

17.1.2 What is included in scikit-image

• Website: https://scikit-image.org/
• Gallery of examples: https://scikit-image.org/docs/stable/auto_examples/
The library contains predominantly image processing algorithms, but also utility functions to ease data
handling and processing. It contains the following submodules:
color
Color space conversion.
data
Test images and example data.
draw
Drawing primitives (lines, text, etc.) that operate on NumPy arrays.

17.1. Introduction and concepts 580


Scientific Python Lectures, Edition 2024.2rc0.dev0

exposure
Image intensity adjustment, e.g., histogram equalization, etc.
feature
Feature detection and extraction, e.g., texture analysis corners, etc.
filters
Sharpening, edge finding, rank filters, thresholding, etc.
graph
Graph-theoretic operations, e.g., shortest paths.
io
Reading, saving, and displaying images and video.
measure
Measurement of image properties, e.g., region properties and contours.
metrics
Metrics corresponding to images, e.g. distance metrics, similarity, etc.
morphology
Morphological operations, e.g., opening or skeletonization.
restoration
Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.
segmentation
Partitioning an image into multiple regions.
transform
Geometric and other transforms, e.g., rotation or the Radon transform.
util
Generic utilities.

17.2 Importing

We import scikit-image using the convention:

>>> import skimage as ski

Most functionality lives in subpackages, e.g.:

>>> image = ski.data.cat()

You can list all submodules with:

>>> for m in dir(ski): print(m)


__version__
color
data
draw
exposure
feature
filters
future
graph
io
measure
metrics
morphology
(continues on next page)

17.2. Importing 581


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


registration
restoration
segmentation
transform
util

Most scikit-image functions take NumPy ndarrays as arguments

>>> camera = ski.data.camera()


>>> camera.dtype
dtype('uint8')
>>> camera.shape
(512, 512)
>>> filtered_camera = ski.filters.gaussian(camera, sigma=1)
>>> type(filtered_camera)
<class 'numpy.ndarray'>

17.3 Example data

To start off, we need example images to work with. The library ships with a few of these:
skimage.data

>>> image = ski.data.cat()


>>> image.shape
(300, 451, 3)

17.4 Input/output, data types and colorspaces

I/O: skimage.io
Save an image to disk: skimage.io.imsave()

>>> ski.io.imsave("cat.png", image)

Reading from files: skimage.io.imread()

>>> cat = ski.io.imread("cat.png")

17.3. Example data 582


Scientific Python Lectures, Edition 2024.2rc0.dev0

This works with many data formats supported by the ImageIO library.
Loading also works with URLs:

>>> logo = ski.io.imread('https://scikit-image.org/_static/img/logo.png')

17.4.1 Data types

Image ndarrays can be represented either by integers (signed or unsigned) or floats.


Careful with overflows with integer data types

>>> camera = ski.data.camera()


>>> camera.dtype
dtype('uint8')
>>> camera_multiply = 3 * camera

Different integer sizes are possible: 8-, 16- or 32-bytes, signed or unsigned.

Warning: An important (if questionable) skimage convention: float images are supposed to lie
in [-1, 1] (in order to have comparable contrast for all float images)
>>> camera_float = ski.util.img_as_float(camera)
>>> camera.max(), camera_float.max()
(255, 1.0)

17.4. Input/output, data types and colorspaces 583


Scientific Python Lectures, Edition 2024.2rc0.dev0

Some image processing routines need to work with float arrays, and may hence output an array with a
different type and the data range from the input array

>>> camera_sobel = ski.filters.sobel(camera)


>>> camera_sobel.max()
0.644...

Utility functions are provided in skimage to convert both the dtype and the data range, following
skimage’s conventions: util.img_as_float, util.img_as_ubyte, etc.
See the user guide for more details.

17.4.2 Colorspaces

Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel encodes transparency)

>>> face = sp.datasets.face()


>>> face.shape
(768, 1024, 3)

Routines converting between different colorspaces (RGB, HSV, LAB etc.) are available in skimage.
color : color.rgb2hsv, color.lab2rgb, etc. Check the docstring for the expected dtype (and data
range) of input images.

3D images

Most functions of skimage can take 3D images as input arguments. Check the docstring to know if a
function can be used on 3D images (for example MRI or CT images).

Exercise

Open a color image on your disk as a NumPy array.


Find a skimage function computing the histogram of an image and plot the histogram of
each color channel
Convert the image to grayscale and plot its histogram.

17.5 Image preprocessing / enhancement

Goals: denoising, feature (edges) extraction, . . .

17.5.1 Local filters

Local filters replace the value of pixels by a function of the values of neighboring pixels. The function
can be linear or non-linear.
Neighbourhood: square (choose size), disk, or more complicated structuring element.

17.5. Image preprocessing / enhancement 584


Scientific Python Lectures, Edition 2024.2rc0.dev0

Example : horizontal Sobel filter

>>> text = ski.data.text()


>>> hsobel_text = ski.filters.sobel_h(text)

Uses the following linear kernel for computing horizontal gradients:

1 2 1
0 0 0
-1 -2 -1

17.5.2 Non-local filters

Non-local filters use a large region of the image (or all the image) to transform the value of one pixel:

>>> camera = ski.data.camera()


>>> camera_equalized = ski.exposure.equalize_hist(camera)

Enhances contrast in large almost uniform regions.

17.5. Image preprocessing / enhancement 585


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.5.3 Mathematical morphology

See wikipedia for an introduction on mathematical morphology.


Probe an image with a simple shape (a structuring element), and modify this image according to how
the shape locally fits or misses the image.
Default structuring element: 4-connectivity of a pixel

>>> # Import structuring elements to make them more easily accessible


>>> from skimage.morphology import disk, diamond

>>> diamond(1)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype=uint8)

Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring
element.:

>>> a = np.zeros((7,7), dtype=np.uint8)


>>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> ski.morphology.binary_erosion(a, diamond(1)).astype(np.uint8)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> #Erosion removes objects smaller than the structure
>>> ski.morphology.binary_erosion(a, diamond(2)).astype(np.uint8)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
(continues on next page)

17.5. Image preprocessing / enhancement 586


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)

Dilation: maximum filter:

>>> a = np.zeros((5, 5))


>>> a[2, 2] = 1
>>> a
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> ski.morphology.binary_dilation(a, diamond(1)).astype(np.uint8)
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)

Opening: erosion + dilation:

>>> a = np.zeros((5,5), dtype=int)


>>> a[1:4, 1:4] = 1; a[4, 4] = 1
>>> a
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 1]])
>>> ski.morphology.binary_opening(a, diamond(1)).astype(np.uint8)
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)

Opening removes small objects and smoothes corners.

Grayscale mathematical morphology

Mathematical morphology operations are also available for (non-binary) grayscale images (int or float
type). Erosion and dilation correspond to minimum (resp. maximum) filters.

Higher-level mathematical morphology are available: tophat, skeletonization, etc.


See also:
Basic mathematical morphology is also implemented in scipy.ndimage.morphology. The scipy.
ndimage implementation works on arbitrary-dimensional arrays.

Example of filters comparison: image denoising


>>> coins = ski.data.coins()
>>> coins_zoom = coins[10:80, 300:370]
>>> median_coins = ski.filters.median(

17.5. Image preprocessing / enhancement 587


Scientific Python Lectures, Edition 2024.2rc0.dev0

... coins_zoom, disk(1)


... )
>>> tv_coins = ski.restoration.denoise_tv_chambolle(
... coins_zoom, weight=0.1
... )
>>> gaussian_coins = ski.filters.gaussian(coins, sigma=2)

17.6 Image segmentation

Image segmentation is the attribution of different labels to different regions of the image, for example in
order to extract the pixels of an object of interest.

17.6.1 Binary segmentation: foreground + background

Histogram-based method: Otsu thresholding

Tip: The Otsu method is a simple heuristic to find a threshold to separate the foreground from the
background.

Earlier scikit-image versions

skimage.filters is called skimage.filter in earlier versions of scikit-image

camera = ski.data.camera()
val = ski.filters.threshold_otsu(camera)
mask = camera < val

17.6. Image segmentation 588


Scientific Python Lectures, Edition 2024.2rc0.dev0

Labeling connected components of a discrete image

Tip: Once you have separated foreground objects, it is use to separate them from each other. For this,
we can assign a different integer labels to each one.

Synthetic data:

>>> n = 20
>>> l = 256
>>> im = np.zeros((l, l))
>>> rng = np.random.default_rng()
>>> points = l * rng.random((2, n ** 2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = ski.filters.gaussian(im, sigma=l / (4. * n))
>>> blobs = im > im.mean()

Label all connected components:

>>> all_labels = ski.measure.label(blobs)

Label only foreground connected components:

>>> blobs_labels = ski.measure.label(blobs, background=0)

See also:
scipy.ndimage.find_objects() is useful to return slices on object in an image.

17.6. Image segmentation 589


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.6.2 Marker based methods

If you have markers inside a set of regions, you can use these to segment the regions.

Watershed segmentation

The Watershed (skimage.segmentation.watershed()) is a region-growing approach that fills “basins”


in the image
>>> # Generate an initial image with two overlapping circles
>>> x, y = np.indices((80, 80))
>>> x1, y1, x2, y2 = 28, 28, 44, 52
>>> r1, r2 = 16, 20
>>> mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2
>>> mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2
>>> image = np.logical_or(mask_circle1, mask_circle2)
>>> # Now we want to separate the two objects in image
>>> # Generate the markers as local maxima of the distance
>>> # to the background
>>> import scipy as sp
>>> distance = sp.ndimage.distance_transform_edt(image)
>>> peak_idx = ski.feature.peak_local_max(
... distance, footprint=np.ones((3, 3)), labels=image
... )
>>> peak_mask = np.zeros_like(distance, dtype=bool)
>>> peak_mask[tuple(peak_idx.T)] = True
>>> markers = ski.morphology.label(peak_mask)
>>> labels_ws = ski.segmentation.watershed(
... -distance, markers, mask=image
... )

Random walker segmentation

The random walker algorithm (skimage.segmentation.random_walker()) is similar to the Watershed,


but with a more “probabilistic” approach. It is based on the idea of the diffusion of labels in the image:
>>> # Transform markers image so that 0-valued pixels are to
>>> # be labelled, and -1-valued pixels represent background
>>> markers[~image] = -1
>>> labels_rw = ski.segmentation.random_walker(image, markers)

Postprocessing label images

skimage provides several utility functions that can be used on label images (ie images where
different discrete values identify different regions). Functions names are often self-explaining:

17.6. Image segmentation 590


Scientific Python Lectures, Edition 2024.2rc0.dev0

skimage.segmentation.clear_border(), skimage.segmentation.relabel_from_one(), skimage.


morphology.remove_small_objects(), etc.

Exercise

• Load the coins image from the data submodule.


• Separate the coins from the background by testing several segmentation methods: Otsu thresh-
olding, adaptive thresholding, and watershed or random walker segmentation.
• If necessary, use a postprocessing function to improve the coins / background segmentation.

17.7 Measuring regions’ properties

Example: compute the size and perimeter of the two segmented regions:

>>> properties = ski.measure.regionprops(labels_rw)


>>> [float(prop.area) for prop in properties]
[770.0, 1168.0]
>>> [prop.perimeter for prop in properties]
[100.91..., 126.81...]

See also:
for some properties, functions are available as well in scipy.ndimage.measurements with a different
API (a list is returned).

Exercise (continued)

• Use the binary image of the coins and background from the previous exercise.
• Compute an image of labels for the different coins.
• Compute the size and eccentricity of all coins.

17.8 Data visualization and interaction

Meaningful visualizations are useful when testing a given processing pipeline.


Some image processing operations:

>>> coins = ski.data.coins()


>>> mask = coins > ski.filters.threshold_otsu(coins)
>>> clean_border = ski.segmentation.clear_border(mask)

Visualize binary result:

>>> plt.figure()
<Figure size ... with 0 Axes>
>>> plt.imshow(clean_border, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>

Visualize contour

17.7. Measuring regions’ properties 591


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> plt.figure()
<Figure size ... with 0 Axes>
>>> plt.imshow(coins, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
>>> plt.contour(clean_border, [0.5])
<matplotlib.contour.QuadContourSet ...>

Use skimage dedicated utility function:

>>> coins_edges = ski.segmentation.mark_boundaries(


... coins, clean_border.astype(int)
... )

17.9 Feature extraction for computer vision

Geometric or textural descriptor can be extracted from images in order to


• classify parts of the image (e.g. sky vs. buildings)
• match parts of different images (e.g. for object detection)
• and many other applications of Computer Vision
Example: detecting corners using Harris detector

tform = ski.transform.AffineTransform(
scale=(1.3, 1.1), rotation=1, shear=0.7,
translation=(210, 50)
)
image = ski.transform.warp(
data.checkerboard(), tform.inverse, output_shape=(350, 350)
)

coords = ski.feature.corner_peaks(
ski.feature.corner_harris(image), min_distance=5
)
coords_subpix = ski.feature.corner_subpix(
image, coords, window_size=13
)

17.9. Feature extraction for computer vision 592


Scientific Python Lectures, Edition 2024.2rc0.dev0

(this example is taken from the plot_corner example in scikit-image)


Points of interest such as corners can then be used to match objects in different images, as described in
the plot_matching example of scikit-image.

17.10 Full code examples

17.11 Examples for the scikit-image chapter

17.11.1 Creating an image

How to create an image with basic NumPy commands : np.zeros, slicing. . .


This examples show how to create a simple checkerboard.

17.10. Full code examples 593


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt

check = np.zeros((8, 8))


check[::2, 1::2] = 1
check[1::2, ::2] = 1
plt.matshow(check, cmap="gray")
plt.show()

Total running time of the script: (0 minutes 0.069 seconds)

17.11.2 Displaying a simple image

Load and display an image

17.11. Examples for the scikit-image chapter 594


Scientific Python Lectures, Edition 2024.2rc0.dev0

import matplotlib.pyplot as plt


from skimage import data

camera = data.camera()

plt.figure(figsize=(4, 4))
plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.axis("off")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.082 seconds)

17.11.3 Integers can overflow

An illustration of overflow problem arising when working with integers

17.11. Examples for the scikit-image chapter 595


Scientific Python Lectures, Edition 2024.2rc0.dev0

import matplotlib.pyplot as plt


from skimage import data

camera = data.camera()
camera_multiply = 3 * camera

plt.figure(figsize=(8, 4))
plt.subplot(121)
plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(camera_multiply, cmap="gray", interpolation="nearest")
plt.axis("off")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.135 seconds)

17.11.4 Equalizing the histogram of an image

Histogram equalizing makes images have a uniform histogram.

17.11. Examples for the scikit-image chapter 596


Scientific Python Lectures, Edition 2024.2rc0.dev0

from skimage import data, exposure


import matplotlib.pyplot as plt

camera = data.camera()
camera_equalized = exposure.equalize_hist(camera)

plt.figure(figsize=(7, 3))

plt.subplot(121)
plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(camera_equalized, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.100 seconds)

17.11.5 Computing horizontal gradients with the Sobel filter

This example illustrates the use of the horizontal Sobel filter, to compute horizontal gradients.

from skimage import data


from skimage import filters
import matplotlib.pyplot as plt

text = data.text()
(continues on next page)

17.11. Examples for the scikit-image chapter 597


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


hsobel_text = filters.sobel_h(text)

plt.figure(figsize=(12, 3))

plt.subplot(121)
plt.imshow(text, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(hsobel_text, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.118 seconds)

17.11.6 Segmentation contours

Visualize segmentation contours on original grayscale image.

from skimage import data, segmentation


from skimage import filters
import matplotlib.pyplot as plt
import numpy as np

coins = data.coins()
mask = coins > filters.threshold_otsu(coins)
clean_border = segmentation.clear_border(mask).astype(int)

coins_edges = segmentation.mark_boundaries(coins, clean_border)

plt.figure(figsize=(8, 3.5))
plt.subplot(121)
plt.imshow(clean_border, cmap="gray")
plt.axis("off")
plt.subplot(122)
plt.imshow(coins_edges)
plt.axis("off")
(continues on next page)

17.11. Examples for the scikit-image chapter 598


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.119 seconds)

17.11.7 Otsu thresholding

This example illustrates automatic Otsu thresholding.

import matplotlib.pyplot as plt


from skimage import data
from skimage import filters
from skimage import exposure

camera = data.camera()
val = filters.threshold_otsu(camera)

hist, bins_center = exposure.histogram(camera)

plt.figure(figsize=(9, 4))
plt.subplot(131)
plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(132)
plt.imshow(camera < val, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(133)
plt.plot(bins_center, hist, lw=2)
plt.axvline(val, color="k", ls="--")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.138 seconds)

17.11. Examples for the scikit-image chapter 599


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.11.8 Affine transform

Warping and affine transforms of images.

import matplotlib.pyplot as plt

from skimage import data


from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform

tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210,␣


˓→50))

image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350))

coords = corner_peaks(corner_harris(image), min_distance=5)


coords_subpix = corner_subpix(image, coords, window_size=13)

plt.gray()
plt.imshow(image, interpolation="nearest")
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5)
plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7)
plt.axis("off")
plt.show()

Total running time of the script: (0 minutes 5.360 seconds)

17.11. Examples for the scikit-image chapter 600


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.11.9 Labelling connected components of an image

This example shows how to label connected components of a binary image, using the dedicated skim-
age.measure.label function.

from skimage import measure


from skimage import filters
import matplotlib.pyplot as plt
import numpy as np

n = 12
l = 256
rng = np.random.default_rng(27446968)
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = filters.gaussian(im, sigma=l / (4.0 * n))
blobs = im > 0.7 * im.mean()

all_labels = measure.label(blobs)
blobs_labels = measure.label(blobs, background=0)

plt.figure(figsize=(9, 3.5))
plt.subplot(131)
plt.imshow(blobs, cmap="gray")
plt.axis("off")
plt.subplot(132)
plt.imshow(all_labels, cmap="nipy_spectral")
plt.axis("off")
plt.subplot(133)
plt.imshow(blobs_labels, cmap="nipy_spectral")
plt.axis("off")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.096 seconds)

17.11. Examples for the scikit-image chapter 601


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.11.10 Various denoising filters

This example compares several denoising filters available in scikit-image: a Gaussian filter, a median
filter, and total variation denoising.

import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import filters
from skimage import restoration

coins = data.coins()
gaussian_filter_coins = filters.gaussian(coins, sigma=2)
med_filter_coins = filters.median(coins, np.ones((3, 3)))
tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1)

plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Image")
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest
˓→")

plt.axis("off")
plt.title("Gaussian filter")
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("Median filter")
plt.subplot(144)
plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("TV filter")
plt.show()

Total running time of the script: (0 minutes 0.175 seconds)

17.11. Examples for the scikit-image chapter 602


Scientific Python Lectures, Edition 2024.2rc0.dev0

17.11.11 Watershed and random walker for segmentation

This example compares two segmentation methods in order to separate two connected disks: the water-
shed algorithm, and the random walker algorithm.
Both segmentation methods require seeds, that are pixels belonging unambigusouly to a reagion. Here,
local maxima of the distance map to the background are used as seeds.

import numpy as np
from skimage.segmentation import watershed
from skimage.feature import peak_local_max
from skimage import measure
from skimage.segmentation import random_walker
import matplotlib.pyplot as plt
import scipy as sp

# Generate an initial image with two overlapping circles


x, y = np.indices((80, 80))
x1, y1, x2, y2 = 28, 28, 44, 52
r1, r2 = 16, 20
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2
image = np.logical_or(mask_circle1, mask_circle2)
# Now we want to separate the two objects in image
# Generate the markers as local maxima of the distance
# to the background
distance = sp.ndimage.distance_transform_edt(image)
peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)
peak_mask = np.zeros_like(distance, dtype=bool)
peak_mask[tuple(peak_idx.T)] = True
markers = measure.label(peak_mask)
labels_ws = watershed(-distance, markers, mask=image)

markers[~image] = -1
labels_rw = random_walker(image, markers)

plt.figure(figsize=(12, 3.5))
plt.subplot(141)
plt.imshow(image, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("image")
plt.subplot(142)
plt.imshow(-distance, interpolation="nearest")
plt.axis("off")
plt.title("distance map")
plt.subplot(143)
(continues on next page)

17.11. Examples for the scikit-image chapter 603


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.imshow(labels_ws, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.title("watershed segmentation")
plt.subplot(144)
plt.imshow(labels_rw, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.title("random walker segmentation")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.182 seconds)

17.11. Examples for the scikit-image chapter 604


CHAPTER 18
scikit-learn: machine learning in Python

Authors: Gael Varoquaux

Prerequisites

• numpy
• scipy
• matplotlib (optional)
• ipython (the enhancements come handy)

Acknowledgements

This chapter is adapted from a tutorial given by Gaël Varoquaux, Jake Vanderplas, Olivier Grisel.

See also:
Data science in Python
• The Statistics in Python chapter may also be of interest for readers looking into machine learning.
• The documentation of scikit-learn is very complete and didactic.

605
Scientific Python Lectures, Edition 2024.2rc0.dev0

Chapters contents

• Introduction: problem settings


• Basic principles of machine learning with scikit-learn
• Supervised Learning: Classification of Handwritten Digits
• Supervised Learning: Regression of Housing Data
• Measuring prediction performance
• Unsupervised Learning: Dimensionality Reduction and Visualization
• Parameter selection, Validation, and Testing
• Examples for the scikit-learn chapter

18.1 Introduction: problem settings

18.1.1 What is machine learning?

Tip: Machine Learning is about building programs with tunable parameters that are adjusted
automatically so as to improve their behavior by adapting to previously seen data.
Machine Learning can be considered a subfield of Artificial Intelligence since those algorithms can be
seen as building blocks to make computers learn to behave more intelligently by somehow generalizing
rather that just storing and retrieving data items like a database system would do.

Fig. 1: A classification problem

We’ll take a look at two very simple machine learning tasks here. The first is a classification task:
the figure shows a collection of two-dimensional data, colored according to two different class labels. A
classification algorithm may be used to draw a dividing boundary between the two clusters of points:
By drawing this separating line, we have learned a model which can generalize to new data: if you were
to drop another point onto the plane which is unlabeled, this algorithm could now predict whether it’s
a blue or a red point.

18.1. Introduction: problem settings 606


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fig. 2: A regression problem

The next simple task we’ll look at is a regression task: a simple best-fit line to a set of data.
Again, this is an example of fitting a model to data, but our focus here is that the model can make
generalizations about new data. The model has been learned from the training data, and can be used
to predict the result of test data: here, we might be given an x-value, and the model would allow us to
predict the y value.

18.1.2 Data in scikit-learn

The data matrix

Machine learning algorithms implemented in scikit-learn expect data to be stored in a two-dimensional


array or matrix. The arrays can be either numpy arrays, or in some cases scipy.sparse matrices. The
size of the array is expected to be [n_samples, n_features]
• n_samples: The number of samples: each sample is an item to process (e.g. classify). A sample
can be a document, a picture, a sound, a video, an astronomical object, a row in database or CSV
file, or whatever you can describe with a fixed set of quantitative traits.
• n_features: The number of features or distinct traits that can be used to describe each item in
a quantitative manner. Features are generally real-valued, but may be boolean or discrete-valued
in some cases.

Tip: The number of features must be fixed in advance. However it can be very high dimensional (e.g.
millions of features) with most of them being zeros for a given sample. This is a case where scipy.sparse
matrices can be useful, in that they are much more memory-efficient than NumPy arrays.

18.1. Introduction: problem settings 607


Scientific Python Lectures, Edition 2024.2rc0.dev0

A Simple Example: the Iris Dataset

The application problem

As an example of a simple dataset, let us a look at the iris data stored by scikit-learn. Suppose we want
to recognize species of irises. The data consists of measurements of three different species of irises:

Setosa Iris Versicolor Iris Virginica Iris

Quick Question:

If we want to design an algorithm to recognize iris species, what might the


data be?
Remember: we need a 2D array of size [n_samples x n_features].
• What would the n_samples refer to?
• What might the n_features refer to?

Remember that there must be a fixed number of features for each sample, and feature number i must
be a similar kind of quantity for each sample.

Loading the Iris Data with Scikit-learn

Scikit-learn has a very straightforward set of data on these iris species. The data consist of the following:
• Features in the Iris dataset:
– sepal length (cm)
– sepal width (cm)
– petal length (cm)
– petal width (cm)
• Target classes to predict:
– Setosa
– Versicolour
– Virginica
scikit-learn embeds a copy of the iris CSV file along with a function to load it into NumPy arrays:

>>> from sklearn.datasets import load_iris


>>> iris = load_iris()

18.1. Introduction: problem settings 608


Scientific Python Lectures, Edition 2024.2rc0.dev0

Note: Import sklearn Note that scikit-learn is imported as sklearn

The features of each sample flower are stored in the data attribute of the dataset:

>>> print(iris.data.shape)
(150, 4)
>>> n_samples, n_features = iris.data.shape
>>> print(n_samples)
150
>>> print(n_features)
4
>>> print(iris.data[0])
[5.1 3.5 1.4 0.2]

The information about the class of each sample is stored in the target attribute of the dataset:

>>> print(iris.target.shape)
(150,)
>>> print(iris.target)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]

The names of the classes are stored in the last attribute, namely target_names:

>>> print(iris.target_names)
['setosa' 'versicolor' 'virginica']

This data is four-dimensional, but we can visualize two of the dimensions at a time using a scatter plot:

18.1. Introduction: problem settings 609


Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise:

Can you choose 2 features to find a plot where it is easier to separate the different classes of irises?
Hint: click on the figure above to see the code that generates it, and modify this code.

18.2 Basic principles of machine learning with scikit-learn

18.2.1 Introducing the scikit-learn estimator object

Every algorithm is exposed in scikit-learn via an ‘’Estimator” object. For instance a linear regression is:
sklearn.linear_model.LinearRegression

>>> from sklearn.linear_model import LinearRegression

Estimator parameters: All the parameters of an estimator can be set when it is instantiated:

>>> model = LinearRegression(n_jobs=1)


>>> print(model)
LinearRegression(n_jobs=1)

Fitting on data

Let’s create some simple data with numpy:

>>> import numpy as np


>>> x = np.array([0, 1, 2])
>>> y = np.array([0, 1, 2])

>>> X = x[:, np.newaxis] # The input data for sklearn is 2D: (samples == 3 x features␣
˓→== 1)

>>> X
array([[0],
[1],
[2]])

>>> model.fit(X, y)
LinearRegression(n_jobs=1)

Estimated parameters: When data is fitted with an estimator, parameters are estimated from the data
at hand. All the estimated parameters are attributes of the estimator object ending by an underscore:

>>> model.coef_
array([1.])

18.2. Basic principles of machine learning with scikit-learn 610


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.2.2 Supervised Learning: Classification and regression

In Supervised Learning, we have a dataset consisting of both features and labels. The task is to
construct an estimator which is able to predict the label of an object given the set of features. A
relatively simple example is predicting the species of iris given a set of measurements of its flower. This
is a relatively simple task. Some more complicated examples are:
• given a multicolor image of an object through a telescope, determine whether that object is a star,
a quasar, or a galaxy.
• given a photograph of a person, identify the person in the photo.
• given a list of movies a person has watched and their personal rating of the movie, recommend a
list of movies they would like (So-called recommender systems: a famous example is the Netflix
Prize).

Tip: What these tasks have in common is that there is one or more unknown quantities associated
with the object which needs to be determined from other observed quantities.

Supervised learning is further broken down into two categories, classification and regression. In
classification, the label is discrete, while in regression, the label is continuous. For example, in astronomy,
the task of determining whether an object is a star, a galaxy, or a quasar is a classification problem: the
label is from three distinct categories. On the other hand, we might wish to estimate the age of an object
based on such observations: this would be a regression problem, because the label (age) is a continuous
quantity.
Classification: K nearest neighbors (kNN) is one of the simplest learning strategies: given a new,
unknown observation, look up in your reference database which ones have the closest features and assign
the predominant class. Let’s try it out on our iris classification problem:

from sklearn import neighbors, datasets


iris = datasets.load_iris()
X, y = iris.data, iris.target
knn = neighbors.KNeighborsClassifier(n_neighbors=1)
knn.fit(X, y)
# What kind of iris has 3cm x 5cm sepal and 4cm x 2cm petal?
print(iris.target_names[knn.predict([[3, 5, 4, 2]])])

Regression: The simplest possible regression setting is the linear regression one:

from sklearn.linear_model import LinearRegression

# x from 0 to 30
rng = np.random.default_rng()
x = 30 * rng.random((20, 1))

# y = a*x + b with noise


y = 0.5 * x + 1.0 + rng.normal(size=x.shape)

# create a linear regression model


model = LinearRegression()
model.fit(x, y)

# predict y from the data


x_new = np.linspace(0, 30, 100)
y_new = model.predict(x_new[:, np.newaxis])

18.2. Basic principles of machine learning with scikit-learn 611


Scientific Python Lectures, Edition 2024.2rc0.dev0

Fig. 3: A plot of the sepal space and the prediction of the KNN

Fig. 4: A plot of a simple linear regression.

18.2. Basic principles of machine learning with scikit-learn 612


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.2.3 A recap on Scikit-learn’s estimator interface

Scikit-learn strives to have a uniform interface across all methods, and we’ll see examples of these below.
Given a scikit-learn estimator object named model, the following methods are available:
In all Estimators
• model.fit() : fit training data. For supervised learning applications, this accepts
two arguments: the data X and the labels y (e.g. model.fit(X, y)). For unsu-
pervised learning applications, this accepts only a single argument, the data X (e.g.
model.fit(X)).
In supervised estimators
• model.predict() : given a trained model, predict the label of a new set of
data. This method accepts one argument, the new data X_new (e.g. model.
predict(X_new)), and returns the learned label for each object in the array.
• model.predict_proba() : For classification problems, some estimators also pro-
vide this method, which returns the probability that a new observation has each
categorical label. In this case, the label with the highest probability is returned by
model.predict().
• model.score() : for classification or regression problems, most (all?) estimators
implement a score method. Scores are between 0 and 1, with a larger score indicating
a better fit.
In unsupervised estimators
• model.transform() : given an unsupervised model, transform new data into the
new basis. This also accepts one argument X_new, and returns the new representa-
tion of the data based on the unsupervised model.
• model.fit_transform() : some estimators implement this method, which more
efficiently performs a fit and a transform on the same input data.

18.2.4 Regularization: what it is and why it is necessary

Preferring simpler models

Train errors Suppose you are using a 1-nearest neighbor estimator. How many errors do you expect
on your train set?
• Train set error is not a good measurement of prediction performance. You need to leave out a test
set.
• In general, we should accept errors on the train set.
An example of regularization The core idea behind regularization is that we are going to prefer
models that are simpler, for a certain definition of ‘’simpler”, even if they lead to more errors on the
train set.
As an example, let’s generate with a 9th order polynomial, with noise:
And now, let’s fit a 4th order and a 9th order polynomial to the data.
With your naked eyes, which model do you prefer, the 4th order one, or the 9th order one?
Let’s look at the ground truth:

Tip: Regularization is ubiquitous in machine learning. Most scikit-learn estimators have a parameter
to tune the amount of regularization. For instance, with k-NN, it is ‘k’, the number of nearest neighbors
used to make the decision. k=1 amounts to no regularization: 0 error on the training set, whereas large
k will push toward smoother decision boundaries in the feature space.

18.2. Basic principles of machine learning with scikit-learn 613


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.2. Basic principles of machine learning with scikit-learn 614


Scientific Python Lectures, Edition 2024.2rc0.dev0

Simple versus complex models for classification

A linear separation A non-linear separation

Tip: For classification models, the decision boundary, that separates the class expresses the complexity
of the model. For instance, a linear model, that makes a decision based on a linear combination of
features, is more complex than a non-linear one.

18.2. Basic principles of machine learning with scikit-learn 615


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.3 Supervised Learning: Classification of Handwritten Digits

18.3.1 The nature of the data

Code and notebook

Python code and Jupyter notebook for this section are found here

In this section we’ll apply scikit-learn to the classification of handwritten digits. This will go a bit beyond
the iris classification we saw before: we’ll discuss some of the metrics which can be used in evaluating
the effectiveness of a classification model.
>>> from sklearn.datasets import load_digits
>>> digits = load_digits()

Let us visualize the data and remind us what we’re looking at (click on the figure for the full code):

# plot the digits: each image is 8x8 pixels


for i in range(64):
(continues on next page)

18.3. Supervised Learning: Classification of Handwritten Digits 616


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest')

18.3.2 Visualizing the Data on its principal components

A good first-step for many problems is to visualize the data using a Dimensionality Reduction technique.
We’ll start with the most straightforward one, Principal Component Analysis (PCA).
PCA seeks orthogonal linear combinations of the features which show the greatest variance, and as such,
can help give you a good idea of the structure of the data set.

>>> from sklearn.decomposition import PCA


>>> pca = PCA(n_components=2)
>>> proj = pca.fit_transform(digits.data)
>>> plt.scatter(proj[:, 0], proj[:, 1], c=digits.target)
<matplotlib.collections.PathCollection object at ...>
>>> plt.colorbar()
<matplotlib.colorbar.Colorbar object at ...>

Question

Given these projections of the data, which numbers do you think a classifier might have trouble
distinguishing?

18.3. Supervised Learning: Classification of Handwritten Digits 617


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.3.3 Gaussian Naive Bayes Classification

For most classification problems, it’s nice to have a simple, fast method to provide a quick baseline
classification. If the simple and fast method is sufficient, then we don’t have to waste CPU cycles on
more complex models. If not, we can use the results of the simple method to give us clues about our
data.
One good method to keep in mind is Gaussian Naive Bayes (sklearn.naive_bayes.GaussianNB).

Old scikit-learn versions

train_test_split() is imported from sklearn.cross_validation

Tip: Gaussian Naive Bayes fits a Gaussian distribution to each training label independently on each
feature, and uses this to quickly give a rough classification. It is generally not sufficiently accurate for
real-world data, but can perform surprisingly well, for instance on text data.

>>> from sklearn.naive_bayes import GaussianNB


>>> from sklearn.model_selection import train_test_split

>>> # split the data into training and validation sets


>>> X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)

>>> # train the model


>>> clf = GaussianNB()
>>> clf.fit(X_train, y_train)
GaussianNB()

>>> # use the model to predict the labels of the test data
>>> predicted = clf.predict(X_test)
>>> expected = y_test
>>> print(predicted)
[5 1 7 2 8 9 4 3 9 3 6 2 3 2 6 7 4 3 5 7 5 7 0 1 2 5 9 8 1 8...]
>>> print(expected)
[5 8 7 2 8 9 4 3 7 3 6 2 3 2 6 7 4 3 5 7 5 7 0 1 2 5 3 3 1 8...]

As above, we plot the digits with the predicted labels to get an idea of how well the classification is
working.

18.3. Supervised Learning: Classification of Handwritten Digits 618


Scientific Python Lectures, Edition 2024.2rc0.dev0

Question

Why did we split the data into training and validation sets?

18.3.4 Quantitative Measurement of Performance

We’d like to measure the performance of our estimator without having to resort to plotting examples. A
simple method might be to simply compare the number of matches:

>>> matches = (predicted == expected)


>>> print(matches.sum())
371
>>> print(len(matches))
450
>>> matches.sum() / float(len(matches))
0.82444...

We see that more than 80% of the 450 predictions match the input. But there are other more sophisticated

18.3. Supervised Learning: Classification of Handwritten Digits 619


Scientific Python Lectures, Edition 2024.2rc0.dev0

metrics that can be used to judge the performance of a classifier: several are available in the sklearn.
metrics submodule.
One of the most useful metrics is the classification_report, which combines several measures and
prints a table with the results:

>>> from sklearn import metrics


>>> print(metrics.classification_report(expected, predicted))
precision recall f1-score support

0 1.00 0.98 0.99 45


1 0.91 0.66 0.76 44
2 0.91 0.56 0.69 36
3 0.89 0.67 0.77 49
4 0.95 0.83 0.88 46
5 0.93 0.93 0.93 45
6 0.92 0.98 0.95 47
7 0.75 0.96 0.84 50
8 0.49 0.97 0.66 39
9 0.85 0.67 0.75 49

accuracy 0.82 450


macro avg 0.86 0.82 0.82 450
weighted avg 0.86 0.82 0.83 450

Another enlightening metric for this sort of multi-label classification is a confusion matrix: it helps us
visualize which labels are being interchanged in the classification errors:

>>> print(metrics.confusion_matrix(expected, predicted))


[[44 0 0 0 0 0 0 0 0 1]
[ 0 29 0 0 0 0 1 6 6 2]
[ 0 1 20 1 0 0 0 0 14 0]
[ 0 0 0 33 0 2 0 1 11 2]
[ 0 0 0 0 38 1 2 4 1 0]
[ 0 0 0 0 0 42 1 0 2 0]
[ 0 0 0 0 0 0 46 0 1 0]
[ 0 0 0 0 1 0 0 48 0 1]
[ 0 1 0 0 0 0 0 0 38 0]
[ 0 1 2 3 1 0 0 5 4 33]]

We see here that in particular, the numbers 1, 2, 3, and 9 are often being labeled 8.

18.4 Supervised Learning: Regression of Housing Data

Here we’ll do a short example of a regression problem: learning a continuous value from a set of features.

18.4.1 A quick look at the data

Code and notebook

Python code and Jupyter notebook for this section are found here

We’ll use the California house prices set, available in scikit-learn. This records measurements of 8
attributes of housing markets in California, as well as the median price. The question is: can you predict
the price of a new market given its attributes?:

18.4. Supervised Learning: Regression of Housing Data 620


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> from sklearn.datasets import fetch_california_housing


>>> data = fetch_california_housing(as_frame=True)
>>> print(data.data.shape)
(20640, 8)
>>> print(data.target.shape)
(20640,)

We can see that there are just over 20000 data points.
The DESCR variable has a long description of the dataset:

>>> print(data.DESCR)
.. _california_housing_dataset:

California Housing dataset


--------------------------

**Data Set Characteristics:**

:Number of Instances: 20640

:Number of Attributes: 8 numeric, predictive attributes and the target

:Attribute Information:
- MedInc median income in block group
- HouseAge median house age in block group
- AveRooms average number of rooms per household
- AveBedrms average number of bedrooms per household
- Population block group population
- AveOccup average number of household members
- Latitude block group latitude
- Longitude block group longitude

:Missing Attribute Values: None

This dataset was obtained from the StatLib repository.


https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html

The target variable is the median house value for California districts,
expressed in hundreds of thousands of dollars ($100,000).

This dataset was derived from the 1990 U.S. census, using one row per census
block group. A block group is the smallest geographical unit for which the U.S.
Census Bureau publishes sample data (a block group typically has a population
of 600 to 3,000 people).

A household is a group of people residing within a home. Since the average


number of rooms and bedrooms in this dataset are provided per household, these
columns may take surprisingly large values for block groups with few households
and many empty houses, such as vacation resorts.

It can be downloaded/loaded using the


:func:`sklearn.datasets.fetch_california_housing` function.

.. topic:: References

- Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions,


Statistics and Probability Letters, 33 (1997) 291-297

18.4. Supervised Learning: Regression of Housing Data 621


Scientific Python Lectures, Edition 2024.2rc0.dev0

It often helps to quickly visualize pieces of the data using histograms, scatter plots, or other plot types.
With matplotlib, let us show a histogram of the target values: the median price in each neighborhood:

>>> plt.hist(data.target)
(array([...

Let’s have a quick look to see if some features are more relevant than others for our problem:

>>> for index, feature_name in enumerate(data.feature_names):


... plt.figure()
... plt.scatter(data.data[feature_name], data.target)
<Figure size...

18.4. Supervised Learning: Regression of Housing Data 622


Scientific Python Lectures, Edition 2024.2rc0.dev0

This is a manual version of a technique called feature selection.

Tip: Sometimes, in Machine Learning it is useful to use feature selection to decide which features are
the most useful for a particular problem. Automated methods exist which quantify this sort of exercise
of choosing the most informative features.

18.4. Supervised Learning: Regression of Housing Data 623


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.4.2 Predicting Home Prices: a Simple Linear Regression

Now we’ll use scikit-learn to perform a simple linear regression on the housing data. There are many
possibilities of regressors to use. A particularly simple one is LinearRegression: this is basically a
wrapper around an ordinary least squares calculation.
>>> from sklearn.model_selection import train_test_split
>>> X_train, X_test, y_train, y_test = train_test_split(data.data, data.target)
>>> from sklearn.linear_model import LinearRegression
>>> clf = LinearRegression()
>>> clf.fit(X_train, y_train)
LinearRegression()
>>> predicted = clf.predict(X_test)
>>> expected = y_test
>>> print("RMS: %s " % np.sqrt(np.mean((predicted - expected) ** 2)))
RMS: 0.7...

We can plot the error: expected as a function of predicted:

>>> plt.scatter(expected, predicted)


<matplotlib.collections.PathCollection object at ...>

Tip: The prediction at least correlates with the true price, though there are clearly some biases. We
could imagine evaluating the performance of the regressor by, say, computing the RMS residuals between
the true and predicted price. There are some subtleties in this, however, which we’ll cover in a later
section.

Exercise: Gradient Boosting Tree Regression

There are many other types of regressors available in scikit-learn: we’ll try a more powerful one here.
Use the GradientBoostingRegressor class to fit the housing data.
hint You can copy and paste some of the above code, replacing LinearRegression with
GradientBoostingRegressor:
from sklearn.ensemble import GradientBoostingRegressor
# Instantiate the model, fit the results, and scatter in vs. out

18.4. Supervised Learning: Regression of Housing Data 624


Scientific Python Lectures, Edition 2024.2rc0.dev0

Solution The solution is found in the code of this chapter

18.5 Measuring prediction performance

18.5.1 A quick test on the K-neighbors classifier

Here we’ll continue to look at the digits data, but we’ll switch to the K-Neighbors classifier. The K-
neighbors classifier is an instance-based classifier. The K-neighbors classifier predicts the label of an
unknown point based on the labels of the K nearest points in the parameter space.

>>> # Get the data


>>> from sklearn.datasets import load_digits
>>> digits = load_digits()
>>> X = digits.data
>>> y = digits.target

>>> # Instantiate and train the classifier


>>> from sklearn.neighbors import KNeighborsClassifier
>>> clf = KNeighborsClassifier(n_neighbors=1)
>>> clf.fit(X, y)
KNeighborsClassifier(...)

>>> # Check the results using metrics


>>> from sklearn import metrics
>>> y_pred = clf.predict(X)

>>> print(metrics.confusion_matrix(y_pred, y))


[[178 0 0 0 0 0 0 0 0 0]
[ 0 182 0 0 0 0 0 0 0 0]
[ 0 0 177 0 0 0 0 0 0 0]
[ 0 0 0 183 0 0 0 0 0 0]
[ 0 0 0 0 181 0 0 0 0 0]
[ 0 0 0 0 0 182 0 0 0 0]
[ 0 0 0 0 0 0 181 0 0 0]
[ 0 0 0 0 0 0 0 179 0 0]
[ 0 0 0 0 0 0 0 0 174 0]
[ 0 0 0 0 0 0 0 0 0 180]]

Apparently, we’ve found a perfect classifier! But this is misleading for the reasons we saw before: the
classifier essentially “memorizes” all the samples it has already seen. To really test how well this algorithm
does, we need to try some samples it hasn’t yet seen.
This problem also occurs with regression models. In the following we fit an other instance-based model
named “decision tree” to the California Housing price dataset we introduced previously:

>>> from sklearn.datasets import fetch_california_housing


>>> from sklearn.tree import DecisionTreeRegressor

>>> data = fetch_california_housing(as_frame=True)


>>> clf = DecisionTreeRegressor().fit(data.data, data.target)
>>> predicted = clf.predict(data.data)
>>> expected = data.target

>>> plt.scatter(expected, predicted)


<matplotlib.collections.PathCollection object at ...>
(continues on next page)

18.5. Measuring prediction performance 625


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> plt.plot([0, 50], [0, 50], '--k')
[<matplotlib.lines.Line2D object at ...]

Here again the predictions are seemingly perfect as the model was able to perfectly memorize the training
set.

Warning: Performance on test set


Performance on test set does not measure overfit (as described above)

18.5.2 A correct approach: Using a validation set

Learning the parameters of a prediction function and testing it on the same data is a methodological
mistake: a model that would just repeat the labels of the samples that it has just seen would have a
perfect score but would fail to predict anything useful on yet-unseen data.
To avoid over-fitting, we have to define two different sets:
• a training set X_train, y_train which is used for learning the parameters of a predictive model
• a testing set X_test, y_test which is used for evaluating the fitted predictive model
In scikit-learn such a random split can be quickly computed with the train_test_split() function:

>>> from sklearn import model_selection


>>> X = digits.data
>>> y = digits.target

>>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y,


... test_size=0.25, random_state=0)

>>> print("%r , %r , %r " % (X.shape, X_train.shape, X_test.shape))


(1797, 64), (1347, 64), (450, 64)

Now we train on the training data, and test on the testing data:

>>> clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train)


>>> y_pred = clf.predict(X_test)
(continues on next page)

18.5. Measuring prediction performance 626


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

>>> print(metrics.confusion_matrix(y_test, y_pred))


[[37 0 0 0 0 0 0 0 0 0]
[ 0 43 0 0 0 0 0 0 0 0]
[ 0 0 43 1 0 0 0 0 0 0]
[ 0 0 0 45 0 0 0 0 0 0]
[ 0 0 0 0 38 0 0 0 0 0]
[ 0 0 0 0 0 47 0 0 0 1]
[ 0 0 0 0 0 0 52 0 0 0]
[ 0 0 0 0 0 0 0 48 0 0]
[ 0 0 0 0 0 0 0 0 48 0]
[ 0 0 0 1 0 1 0 0 0 45]]
>>> print(metrics.classification_report(y_test, y_pred))
precision recall f1-score support

0 1.00 1.00 1.00 37


1 1.00 1.00 1.00 43
2 1.00 0.98 0.99 44
3 0.96 1.00 0.98 45
4 1.00 1.00 1.00 38
5 0.98 0.98 0.98 48
6 1.00 1.00 1.00 52
7 1.00 1.00 1.00 48
8 1.00 1.00 1.00 48
9 0.98 0.96 0.97 47

accuracy 0.99 450


macro avg 0.99 0.99 0.99 450
weighted avg 0.99 0.99 0.99 450

The averaged f1-score is often used as a convenient measure of the overall performance of an algorithm.
It appears in the bottom row of the classification report; it can also be accessed directly:

>>> metrics.f1_score(y_test, y_pred, average="macro")


0.991367...

The over-fitting we saw previously can be quantified by computing the f1-score on the training data
itself:

>>> metrics.f1_score(y_train, clf.predict(X_train), average="macro")


1.0

Note: Regression metrics In the case of regression models, we need to use different metrics, such as
explained variance.

18.5. Measuring prediction performance 627


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.5.3 Model Selection via Validation

Tip: We have applied Gaussian Naives, support vectors machines, and K-nearest neighbors classifiers
to the digits dataset. Now that we have these validation tools in place, we can ask quantitatively which
of the three estimators works best for this dataset.

• With the default hyper-parameters for each estimator, which gives the best f1 score on the valida-
tion set? Recall that hyperparameters are the parameters set when you instantiate the classifier:
for example, the n_neighbors in clf = KNeighborsClassifier(n_neighbors=1)

>>> from sklearn.naive_bayes import GaussianNB


>>> from sklearn.neighbors import KNeighborsClassifier
>>> from sklearn.svm import LinearSVC

>>> X = digits.data
>>> y = digits.target
>>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y,
... test_size=0.25, random_state=0)

>>> for Model in [GaussianNB(), KNeighborsClassifier(), LinearSVC(dual=False)]:


... clf = Model.fit(X_train, y_train)
... y_pred = clf.predict(X_test)
... print('%s : %s ' %
... (Model.__class__.__name__, metrics.f1_score(y_test, y_pred,␣
˓→average="macro")))

GaussianNB: 0.8...
KNeighborsClassifier: 0.9...
LinearSVC: 0.9...

• For each classifier, which value for the hyperparameters gives the best results for the digits data?
For LinearSVC, use loss='l2' and loss='l1'. For KNeighborsClassifier we use n_neighbors
between 1 and 10. Note that GaussianNB does not have any adjustable hyperparameters.

LinearSVC(loss='l1'): 0.930570687535
LinearSVC(loss='l2'): 0.933068826918
-------------------
KNeighbors(n_neighbors=1): 0.991367521884
KNeighbors(n_neighbors=2): 0.984844206884
KNeighbors(n_neighbors=3): 0.986775344954
KNeighbors(n_neighbors=4): 0.980371905382
KNeighbors(n_neighbors=5): 0.980456280495
KNeighbors(n_neighbors=6): 0.975792419414
KNeighbors(n_neighbors=7): 0.978064579214
KNeighbors(n_neighbors=8): 0.978064579214
KNeighbors(n_neighbors=9): 0.978064579214
KNeighbors(n_neighbors=10): 0.975555089773

Solution: code source

18.5. Measuring prediction performance 628


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.5.4 Cross-validation

Cross-validation consists in repeatedly splitting the data in pairs of train and test sets, called ‘folds’.
Scikit-learn comes with a function to automatically compute score on all these folds. Here we do KFold
with k=5.

>>> clf = KNeighborsClassifier()


>>> from sklearn.model_selection import cross_val_score
>>> cross_val_score(clf, X, y, cv=5)
array([0.947..., 0.955..., 0.966..., 0.980..., 0.963... ])

We can use different splitting strategies, such as random splitting:

>>> from sklearn.model_selection import ShuffleSplit


>>> cv = ShuffleSplit(n_splits=5)
>>> cross_val_score(clf, X, y, cv=cv)
array([...])

Tip: There exists many different cross-validation strategies in scikit-learn. They are often useful to
take in account non iid datasets.

18.5.5 Hyperparameter optimization with cross-validation

Consider regularized linear models, such as Ridge Regression, which uses l2 regularization, and Lasso
Regression, which uses l1 regularization. Choosing their regularization parameter is important.
Let us set these parameters on the Diabetes dataset, a simple regression problem. The diabetes data
consists of 10 physiological variables (age, sex, weight, blood pressure) measure on 442 patients, and an
indication of disease progression after one year:

>>> from sklearn.datasets import load_diabetes


>>> data = load_diabetes()
>>> X, y = data.data, data.target
>>> print(X.shape)
(442, 10)

With the default hyper-parameters: we compute the cross-validation score:

>>> from sklearn.linear_model import Ridge, Lasso

>>> for Model in [Ridge, Lasso]:


... model = Model()
... print('%s : %s ' % (Model.__name__, cross_val_score(model, X, y).mean()))
Ridge: 0.4...
Lasso: 0.3...

18.5. Measuring prediction performance 629


Scientific Python Lectures, Edition 2024.2rc0.dev0

Basic Hyperparameter Optimization

We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso
and Ridge. We choose 20 values of alpha between 0.0001 and 1:

>>> alphas = np.logspace(-3, -1, 30)

>>> for Model in [Lasso, Ridge]:


... scores = [cross_val_score(Model(alpha), X, y, cv=3).mean()
... for alpha in alphas]
... plt.plot(alphas, scores, label=Model.__name__)
[<matplotlib.lines.Line2D object at ...

Question

Can we trust our results to be actually useful?

Automatically Performing Grid Search

sklearn.grid_search.GridSearchCV is constructed with an estimator, as well as a dictionary of pa-


rameter values to be searched. We can find the optimal parameters this way:

>>> from sklearn.model_selection import GridSearchCV


>>> for Model in [Ridge, Lasso]:
... gscv = GridSearchCV(Model(), dict(alpha=alphas), cv=3).fit(X, y)
... print('%s : %s ' % (Model.__name__, gscv.best_params_))
Ridge: {'alpha': 0.062101694189156162}
Lasso: {'alpha': 0.01268961003167922}

Built-in Hyperparameter Search

For some models within scikit-learn, cross-validation can be performed more efficiently on large datasets.
In this case, a cross-validated version of the particular model is included. The cross-validated versions
of Ridge and Lasso are RidgeCV and LassoCV, respectively. Parameter search on these estimators can
be performed as follows:

>>> from sklearn.linear_model import RidgeCV, LassoCV


>>> for Model in [RidgeCV, LassoCV]:
... model = Model(alphas=alphas, cv=3).fit(X, y)
... print('%s : %s ' % (Model.__name__, model.alpha_))
(continues on next page)

18.5. Measuring prediction performance 630


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


RidgeCV: 0.0621016941892
LassoCV: 0.0126896100317

We see that the results match those returned by GridSearchCV

Nested cross-validation

How do we measure the performance of these estimators? We have used data to set the hyperparameters,
so we need to test on actually new data. We can do this by running cross_val_score() on our CV
objects. Here there are 2 cross-validation loops going on, this is called ‘nested cross validation’:

for Model in [RidgeCV, LassoCV]:


scores = cross_val_score(Model(alphas=alphas, cv=3), X, y, cv=3)
print(Model.__name__, np.mean(scores))

Note: Note that these results do not match the best results of our curves above, and LassoCV seems
to under-perform RidgeCV. The reason is that setting the hyper-parameter is harder for Lasso, thus the
estimation error on this hyper-parameter is larger.

18.6 Unsupervised Learning: Dimensionality Reduction and Visual-


ization

Unsupervised learning is applied on X without y: data without labels. A typical use case is to find
hidden structure in the data.

18.6.1 Dimensionality Reduction: PCA

Dimensionality reduction derives a set of new artificial features smaller than the original feature set.
Here we’ll use Principal Component Analysis (PCA), a dimensionality reduction that strives to retain
most of the variance of the original data. We’ll use sklearn.decomposition.PCA on the iris dataset:

>>> X = iris.data
>>> y = iris.target

Tip: PCA computes linear combinations of the original features using a truncated Singular Value
Decomposition of the matrix X, to project the data onto a base of the top singular vectors.

>>> from sklearn.decomposition import PCA


>>> pca = PCA(n_components=2, whiten=True)
>>> pca.fit(X)
PCA(n_components=2, whiten=True)

Once fitted, PCA exposes the singular vectors in the components_ attribute:

>>> pca.components_
array([[ 0.3..., -0.08..., 0.85..., 0.3...],
[ 0.6..., 0.7..., -0.1..., -0.07...]])

Other attributes are available as well:

18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 631


Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> pca.explained_variance_ratio_
array([0.92..., 0.053...])

Let us project the iris dataset along those first two dimensions::

>>> X_pca = pca.transform(X)


>>> X_pca.shape
(150, 2)

PCA normalizes and whitens the data, which means that the data is now centered on both components
with unit variance:

>>> X_pca.mean(axis=0)
array([...e-15, ...e-15])
>>> X_pca.std(axis=0, ddof=1)
array([1., 1.])

Furthermore, the samples components do no longer carry any linear correlation:

>>> np.corrcoef(X_pca.T)
array([[1.00000000e+00, 0.0],
[0.0, 1.00000000e+00]])

With a number of retained components 2 or 3, PCA is useful to visualize the dataset:

>>> target_ids = range(len(iris.target_names))


>>> for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names):
... plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1],
... c=c, label=label)
<matplotlib.collections.PathCollection ...

Tip: Note that this projection was determined without any information about the labels (represented
by the colors): this is the sense in which the learning is unsupervised. Nevertheless, we see that the
projection gives us insight into the distribution of the different flowers in parameter space: notably, iris
setosa is much more distinct than the other two species.

18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 632


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.6.2 Visualization with a non-linear embedding: tSNE

For visualization, more complex embeddings can be useful (for statistical analysis, they are harder to
control). sklearn.manifold.TSNE is such a powerful manifold learning method. We apply it to the digits
dataset, as the digits are vectors of dimension 8*8 = 64. Embedding them in 2D enables visualization:

>>> # Take the first 500 data points: it's hard to see 1500 points
>>> X = digits.data[:500]
>>> y = digits.target[:500]

>>> # Fit and transform with a TSNE


>>> from sklearn.manifold import TSNE
>>> tsne = TSNE(n_components=2, learning_rate='auto', init='random', random_state=0)
>>> X_2d = tsne.fit_transform(X)

>>> # Visualize the data


>>> plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y)
<matplotlib.collections.PathCollection object at ...>

fit_transform

As TSNE cannot be applied to new data, we need to use its fit_transform method.

sklearn.manifold.TSNE separates quite well the different classes of digits even though it had no access
to the class information.

Exercise: Other dimension reduction of digits

sklearn.manifold has many other non-linear embeddings. Try them out on the digits dataset. Could

18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 633


Scientific Python Lectures, Edition 2024.2rc0.dev0

you judge their quality without knowing the labels y?


>>> from sklearn.datasets import load_digits
>>> digits = load_digits()
>>> # ...

18.7 Parameter selection, Validation, and Testing

18.7.1 Hyperparameters, Over-fitting, and Under-fitting

See also:
This section is adapted from Andrew Ng’s excellent Coursera course
The issues associated with validation and cross-validation are some of the most important aspects of the
practice of machine learning. Selecting the optimal model for your data is vital, and is a piece of the
problem that is not often appreciated by machine learning practitioners.
The central question is: If our estimator is underperforming, how should we move forward?
• Use simpler or more complicated model?
• Add more features to each observed data point?
• Add more training samples?
The answer is often counter-intuitive. In particular, Sometimes using a more complicated model
will give worse results. Also, Sometimes adding training data will not improve your results.
The ability to determine what steps will improve your model is what separates the successful machine
learning practitioners from the unsuccessful.

Bias-variance trade-off: illustration on a simple regression problem

Code and notebook

Python code and Jupyter notebook for this section are found here

Let us start with a simple 1D regression problem. This will help us to easily visualize the data and the
model, and the results generalize easily to higher-dimensional datasets. We’ll explore a simple linear
regression problem, with sklearn.linear_model.

X = np.c_[0.5, 1].T
y = [0.5, 1]
X_test = np.c_[0, 2].T

Without noise, as linear regression fits the data perfectly

from sklearn import linear_model

regr = linear_model.LinearRegression()
regr.fit(X, y)
plt.plot(X, y, "o")
plt.plot(X_test, regr.predict(X_test))

18.7. Parameter selection, Validation, and Testing 634


Scientific Python Lectures, Edition 2024.2rc0.dev0

[<matplotlib.lines.Line2D object at 0x7f494c1f3bd0>]

In real life situation, we have noise (e.g. measurement noise) in our data:

rng = np.random.default_rng(27446968)
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))

As we can see, our linear model captures and amplifies the noise in the data. It displays a lot of variance.
We can use another linear estimator that uses regularization, the Ridge estimator. This estimator
regularizes the coefficients by shrinking them to zero, under the assumption that very high correlations
are often spurious. The alpha parameter controls the amount of shrinkage used.

regr = linear_model.Ridge(alpha=0.1)
np.random.seed(0)
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))

plt.show()

18.7. Parameter selection, Validation, and Testing 635


Scientific Python Lectures, Edition 2024.2rc0.dev0

As we can see, the estimator displays much less variance. However it systematically under-estimates the
coefficient. It displays a biased behavior.
This is a typical example of bias/variance tradeof : non-regularized estimator are not biased, but they
can display a lot of variance. Highly-regularized models have little variance, but high bias. This bias is
not necessarily a bad thing: what matters is choosing the tradeoff between bias and variance that leads
to the best prediction performance. For a specific dataset there is a sweet spot corresponding to the
highest complexity that the data can support, depending on the amount of noise and of observations
available.

18.7.2 Visualizing the Bias/Variance Tradeoff

Tip: Given a particular dataset and a model (e.g. a polynomial), we’d like to understand whether bias
(underfit) or variance limits prediction, and how to tune the hyperparameter (here d, the degree of the
polynomial) to give the best fit.

On a given data, let us fit a simple polynomial regression model with varying degrees:

Tip: In the above figure, we see fits for three different values of d. For d = 1, the data is under-fit.
This means that the model is too simplistic: no straight line will ever be a good fit to this data. In this
case, we say that the model suffers from high bias. The model itself is biased, and this will be reflected
in the fact that the data is poorly fit. At the other extreme, for d = 6 the data is over-fit. This means
that the model has too many free parameters (6 in this case) which can be adjusted to perfectly fit the
training data. If we add a new point to this plot, though, chances are it will be very far from the curve
representing the degree-6 fit. In this case, we say that the model suffers from high variance. The reason
for the term “high variance” is that if any of the input points are varied slightly, it could result in a very
different model.

18.7. Parameter selection, Validation, and Testing 636


Scientific Python Lectures, Edition 2024.2rc0.dev0

In the middle, for d = 2, we have found a good mid-point. It fits the data fairly well, and does not suffer
from the bias and variance problems seen in the figures on either side. What we would like is a way to
quantitatively identify bias and variance, and optimize the metaparameters (in this case, the polynomial
degree d) in order to determine the best algorithm.

Polynomial regression with scikit-learn

A polynomial regression is built by pipelining PolynomialFeatures and a LinearRegression:


>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import PolynomialFeatures
>>> from sklearn.linear_model import LinearRegression
>>> model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())

Validation Curves

Let us create a dataset like in the example above:

>>> def generating_func(x, rng, err=0.5):


... return rng.normal(10 - 1. / (x + 0.1), err)

>>> # randomly sample more data


>>> rng = np.random.default_rng(27446968)
>>> x = rng.random(size=200)
>>> y = generating_func(x, err=1., rng=rng)

Central to quantify bias and variance of a model is to apply it on test data, sampled from the same
distribution as the train, but that will capture independent noise:

>>> xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.4)

Validation curve A validation curve consists in varying a model parameter that controls its complexity
(here the degree of the polynomial) and measures both error of the model on training data, and on test
data (eg with cross-validation). The model parameter is then adjusted so that the test error is minimized:
We use sklearn.model_selection.validation_curve() to compute train and test error, and plot it:

>>> from sklearn.model_selection import validation_curve

>>> degrees = np.arange(1, 21)


(continues on next page)

18.7. Parameter selection, Validation, and Testing 637


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

>>> model = make_pipeline(PolynomialFeatures(), LinearRegression())

>>> # Vary the "degrees" on the pipeline step "polynomialfeatures"


>>> train_scores, validation_scores = validation_curve(
... model, x[:, np.newaxis], y,
... param_name='polynomialfeatures__degree',
... param_range=degrees)

>>> # Plot the mean train score and validation score across folds
>>> plt.plot(degrees, validation_scores.mean(axis=1), label='cross-validation')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(degrees, train_scores.mean(axis=1), label='training')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.legend(loc='best')
<matplotlib.legend.Legend object at ...>

This figure shows why validation is important. On the left side of the plot, we have very low-degree
polynomial, which under-fit the data. This leads to a low explained variance for both the training set
and the validation set. On the far right side of the plot, we have a very high degree polynomial, which
over-fits the data. This can be seen in the fact that the training explained variance is very high, while
on the validation set, it is low. Choosing d around 4 or 5 gets us the best tradeoff.

Tip: The astute reader will realize that something is amiss here: in the above plot, d = 4 gives the
best results. But in the previous plot, we found that d = 6 vastly over-fits the data. What’s going on
here? The difference is the number of training points used. In the previous example, there were only
eight training points. In this example, we have 100. As a general rule of thumb, the more training points
used, the more complicated model can be used. But how can you determine for a given model whether
more training points will be helpful? A useful diagnostic for this are learning curves.

18.7. Parameter selection, Validation, and Testing 638


Scientific Python Lectures, Edition 2024.2rc0.dev0

Learning Curves

A learning curve shows the training and validation score as a function of the number of training points.
Note that when we train on a subset of the training data, the training score is computed using this
subset, not the full training set. This curve gives a quantitative view into how beneficial it will be to
add training samples.

Questions:

• As the number of training samples are increased, what do you expect to see for the training
score? For the validation score?
• Would you expect the training score to be higher or lower than the validation score? Would you
ever expect this to change?

scikit-learn provides sklearn.model_selection.learning_curve():

>>> from sklearn.model_selection import learning_curve


>>> train_sizes, train_scores, validation_scores = learning_curve(
... model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20))

>>> # Plot the mean train score and validation score across folds
>>> plt.plot(train_sizes, validation_scores.mean(axis=1), label='cross-validation')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(train_sizes, train_scores.mean(axis=1), label='training')
[<matplotlib.lines.Line2D object at ...>]

Fig. 5: For a degree=1 model

Note that the validation score generally increases with a growing training set, while the training score
generally decreases with a growing training set. As the training size increases, they will converge to a
single value.
From the above discussion, we know that d = 1 is a high-bias estimator which under-fits the data. This
is indicated by the fact that both the training and validation scores are low. When confronted with this
type of learning curve, we can expect that adding more training data will not help: both lines converge
to a relatively low score.

When the learning curves have converged to a low score, we have a high bias model.
A high-bias model can be improved by:

18.7. Parameter selection, Validation, and Testing 639


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Using a more sophisticated model (i.e. in this case, increase d)


• Gather more features for each sample.
• Decrease regularization in a regularized model.
Increasing the number of samples, however, does not improve a high-bias model.
Now let’s look at a high-variance (i.e. over-fit) model:

Fig. 6: For a degree=15 model

Here we show the learning curve for d = 15. From the above discussion, we know that d = 15 is a
high-variance estimator which over-fits the data. This is indicated by the fact that the training score
is much higher than the validation score. As we add more samples to this training set, the training score
will continue to decrease, while the cross-validation error will continue to increase, until they meet in
the middle.

Learning curves that have not yet converged with the full training set indicate a high-
variance, over-fit model.
A high-variance model can be improved by:
• Gathering more training samples.
• Using a less-sophisticated model (i.e. in this case, make d smaller)
• Increasing regularization.
In particular, gathering more features for each sample will not help the results.

18.7.3 Summary on model selection

We’ve seen above that an under-performing algorithm can be due to two possible situations: high
bias (under-fitting) and high variance (over-fitting). In order to evaluate our algorithm, we set aside
a portion of our training data for cross-validation. Using the technique of learning curves, we can
train on progressively larger subsets of the data, evaluating the training error and cross-validation error
to determine whether our algorithm has high variance or high bias. But what do we do with this
information?

18.7. Parameter selection, Validation, and Testing 640


Scientific Python Lectures, Edition 2024.2rc0.dev0

High Bias

If a model shows high bias, the following actions might help:


• Add more features. In our example of predicting home prices, it may be helpful to make use of
information such as the neighborhood the house is in, the year the house was built, the size of the
lot, etc. Adding these features to the training and test sets can improve a high-bias estimator
• Use a more sophisticated model. Adding complexity to the model can help improve on bias.
For a polynomial fit, this can be accomplished by increasing the degree d. Each learning technique
has its own methods of adding complexity.
• Use fewer samples. Though this will not improve the classification, a high-bias algorithm can
attain nearly the same error with a smaller training sample. For algorithms which are compu-
tationally expensive, reducing the training sample size can lead to very large improvements in
speed.
• Decrease regularization. Regularization is a technique used to impose simplicity in some ma-
chine learning models, by adding a penalty term that depends on the characteristics of the param-
eters. If a model has high bias, decreasing the effect of regularization can lead to better results.

High Variance

If a model shows high variance, the following actions might help:


• Use fewer features. Using a feature selection technique may be useful, and decrease the over-
fitting of the estimator.
• Use a simpler model. Model complexity and over-fitting go hand-in-hand.
• Use more training samples. Adding training samples can reduce the effect of over-fitting, and
lead to improvements in a high variance estimator.
• Increase Regularization. Regularization is designed to prevent over-fitting. In a high-variance
model, increasing regularization can lead to better results.
These choices become very important in real-world situations. For example, due to limited telescope
time, astronomers must seek a balance between observing a large number of objects, and observing a
large number of features for each object. Determining which is more important for a particular learning
task can inform the observing strategy that the astronomer employs.

18.7.4 A last word of caution: separate validation and test set

Using validation schemes to determine hyper-parameters means that we are fitting the hyper-parameters
to the particular validation set. In the same way that parameters can be over-fit to the training set,
hyperparameters can be over-fit to the validation set. Because of this, the validation error tends to
under-predict the classification error of new data.
For this reason, it is recommended to split the data into three sets:
• The training set, used to train the model (usually ~60% of the data)
• The validation set, used to validate the model (usually ~20% of the data)
• The test set, used to evaluate the expected error of the validated model (usually ~20% of the
data)
Many machine learning practitioners do not separate test set and validation set. But if your goal is to
gauge the error of a model on unknown data, using an independent test set is vital.

18.7. Parameter selection, Validation, and Testing 641


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8 Examples for the scikit-learn chapter

18.8.1 Demo PCA in 2D

Load the iris data

from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target

Fit a PCA

from sklearn.decomposition import PCA

pca = PCA(n_components=2, whiten=True)


pca.fit(X)

Project the data in 2D

X_pca = pca.transform(X)

Visualize the data

target_ids = range(len(iris.target_names))

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 5))
for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False):
plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label)
plt.legend()
plt.show()

18.8. Examples for the scikit-learn chapter 642


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.110 seconds)

18.8.2 Measuring Decision Tree performance

Demonstrates overfit when testing on train set.


Get the data

from sklearn.datasets import fetch_california_housing

data = fetch_california_housing(as_frame=True)

Train and test a model

from sklearn.tree import DecisionTreeRegressor

clf = DecisionTreeRegressor().fit(data.data, data.target)

predicted = clf.predict(data.data)
expected = data.target

Plot predicted as a function of expected

import matplotlib.pyplot as plt

(continues on next page)

18.8. Examples for the scikit-learn chapter 643


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.figure(figsize=(4, 3))
plt.scatter(expected, predicted)
plt.plot([0, 5], [0, 5], "--k")
plt.axis("tight")
plt.xlabel("True price ($100k)")
plt.ylabel("Predicted price ($100k)")
plt.tight_layout()

Pretty much no errors!


This is too good to be true: we are testing the model on the train data, which is not a measure of
generalization.
The results are not valid
Total running time of the script: (0 minutes 1.482 seconds)

18.8.3 Plot 2D views of the iris dataset

Plot a simple scatter plot of 2 features of the iris dataset.


Note that more elaborate visualization of this dataset is detailed in the Statistics in Python chapter.

18.8. Examples for the scikit-learn chapter 644


Scientific Python Lectures, Edition 2024.2rc0.dev0

# Load the data


from sklearn.datasets import load_iris

iris = load_iris()

import matplotlib.pyplot as plt

# The indices of the features that we are plotting


x_index = 0
y_index = 1

# this formatter will label the colorbar with the correct target names
formatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])

plt.figure(figsize=(5, 4))
plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)
plt.colorbar(ticks=[0, 1, 2], format=formatter)
plt.xlabel(iris.feature_names[x_index])
plt.ylabel(iris.feature_names[y_index])

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.112 seconds)

18.8. Examples for the scikit-learn chapter 645


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.4 A simple linear regression

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# x from 0 to 30
rng = np.random.default_rng()
x = 30 * rng.random((20, 1))

# y = a*x + b with noise


y = 0.5 * x + 1.0 + rng.normal(size=x.shape)

# create a linear regression model


model = LinearRegression()
model.fit(x, y)

# predict y from the data


x_new = np.linspace(0, 30, 100)
y_new = model.predict(x_new[:, np.newaxis])

# plot the results


plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.scatter(x, y)
ax.plot(x_new, y_new)

ax.set_xlabel("x")
ax.set_ylabel("y")

ax.axis("tight")

plt.show()

Total running time of the script: (0 minutes 0.056 seconds)

18.8. Examples for the scikit-learn chapter 646


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.5 tSNE to visualize digits

Here we use sklearn.manifold.TSNE to visualize the digits datasets. Indeed, the digits are vectors in
a 8*8 = 64 dimensional space. We want to project them in 2D for visualization. tSNE is often a good
solution, as it groups and separates data points based on their local relationship.
Load the iris data

from sklearn import datasets

digits = datasets.load_digits()
# Take the first 500 data points: it's hard to see 1500 points
X = digits.data[:500]
y = digits.target[:500]

Fit and transform with a TSNE

from sklearn.manifold import TSNE

tsne = TSNE(n_components=2, random_state=0)

Project the data in 2D

X_2d = tsne.fit_transform(X)

Visualize the data

target_ids = range(len(digits.target_names))

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 5))
colors = "r", "g", "b", "c", "m", "y", "k", "w", "orange", "purple"
for i, c, label in zip(target_ids, colors, digits.target_names, strict=True):
plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label)
plt.legend()
plt.show()

18.8. Examples for the scikit-learn chapter 647


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 1.176 seconds)

18.8.6 Use the RidgeCV and LassoCV to set the regularization parameter

Load the diabetes dataset

from sklearn.datasets import load_diabetes

data = load_diabetes()
X, y = data.data, data.target
print(X.shape)

(442, 10)

Compute the cross-validation score with the default hyper-parameters

from sklearn.model_selection import cross_val_score


from sklearn.linear_model import Ridge, Lasso

for Model in [Ridge, Lasso]:


model = Model()
print(f"{ Model.__name__} : { cross_val_score(model, X, y).mean()} ")

18.8. Examples for the scikit-learn chapter 648


Scientific Python Lectures, Edition 2024.2rc0.dev0

Ridge: 0.410174971340889
Lasso: 0.3375593674654274

We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso
and Ridge

import numpy as np
import matplotlib.pyplot as plt

alphas = np.logspace(-3, -1, 30)

plt.figure(figsize=(5, 3))

for Model in [Lasso, Ridge]:


scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas]
plt.plot(alphas, scores, label=Model.__name__)

plt.legend(loc="lower left")
plt.xlabel("alpha")
plt.ylabel("cross validation score")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.349 seconds)

18.8.7 Plot variance and regularization in linear models

import numpy as np

# Smaller figures
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = (3, 2)

We consider the situation where we have only 2 data point

18.8. Examples for the scikit-learn chapter 649


Scientific Python Lectures, Edition 2024.2rc0.dev0

X = np.c_[0.5, 1].T
y = [0.5, 1]
X_test = np.c_[0, 2].T

Without noise, as linear regression fits the data perfectly

from sklearn import linear_model

regr = linear_model.LinearRegression()
regr.fit(X, y)
plt.plot(X, y, "o")
plt.plot(X_test, regr.predict(X_test))

[<matplotlib.lines.Line2D object at 0x7f494c1f3bd0>]

In real life situation, we have noise (e.g. measurement noise) in our data:

rng = np.random.default_rng(27446968)
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))

As we can see, our linear model captures and amplifies the noise in the data. It displays a lot of variance.
We can use another linear estimator that uses regularization, the Ridge estimator. This estimator
regularizes the coefficients by shrinking them to zero, under the assumption that very high correlations
are often spurious. The alpha parameter controls the amount of shrinkage used.

regr = linear_model.Ridge(alpha=0.1)
np.random.seed(0)
(continues on next page)

18.8. Examples for the scikit-learn chapter 650


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))

plt.show()

Total running time of the script: (0 minutes 0.103 seconds)

18.8.8 Simple picture of the formal problem of machine learning

This example generates simple synthetic data ploints and shows a separating hyperplane on them.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
from sklearn.datasets import make_blobs

# we create 50 separable synthetic points


X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)

(continues on next page)

18.8. Examples for the scikit-learn chapter 651


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# fit the model
clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True)
clf.fit(X, Y)

# plot the line, the points, and the nearest vectors to the plane
xx = np.linspace(-1, 5, 10)
yy = np.linspace(-1, 5, 10)

X1, X2 = np.meshgrid(xx, yy)


Z = np.empty(X1.shape)
for (i, j), val in np.ndenumerate(X1):
x1 = val
x2 = X2[i, j]
p = clf.decision_function([[x1, x2]])
Z[i, j] = p[0]

plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.contour(
X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"]
)
ax.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)

ax.axis("tight")

plt.show()

Total running time of the script: (0 minutes 0.049 seconds)

18.8.9 Compare classifiers on the digits data

Compare the performance of a variety of classifiers on a test set for the digits data.

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣

˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.

warnings.warn(
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣

˓→iterations.

warnings.warn(
LinearSVC: 0.9341800269333108
GaussianNB: 0.8332741681010102
KNeighborsClassifier: 0.9804562804949924
------------------
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣

˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.

warnings.warn(
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣

˓→iterations.

warnings.warn(
(continues on next page)

18.8. Examples for the scikit-learn chapter 652


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


LinearSVC(loss='hinge'): 0.9294570108037394
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣

˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.

warnings.warn(
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣

˓→iterations.

warnings.warn(
LinearSVC(loss='squared_hinge'): 0.9341371852581549
-------------------
KNeighbors(n_neighbors=1): 0.9913675218842191
KNeighbors(n_neighbors=2): 0.9848442068835102
KNeighbors(n_neighbors=3): 0.9867753449543099
KNeighbors(n_neighbors=4): 0.9803719053818863
KNeighbors(n_neighbors=5): 0.9804562804949924
KNeighbors(n_neighbors=6): 0.9757924194139573
KNeighbors(n_neighbors=7): 0.9780645792142071
KNeighbors(n_neighbors=8): 0.9780645792142071
KNeighbors(n_neighbors=9): 0.9780645792142071
KNeighbors(n_neighbors=10): 0.9755550897728812

from sklearn import model_selection, datasets, metrics


from sklearn.svm import LinearSVC
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier

digits = datasets.load_digits()
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = model_selection.train_test_split(
X, y, test_size=0.25, random_state=0
)

for Model in [LinearSVC, GaussianNB, KNeighborsClassifier]:


clf = Model().fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(f"{ Model.__name__} : { metrics.f1_score(y_test, y_pred, average='macro')} ")

print("------------------")

# test SVC loss


for loss in ["hinge", "squared_hinge"]:
clf = LinearSVC(loss=loss).fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(
f"LinearSVC(loss='{ loss} '): { metrics.f1_score(y_test, y_pred, average='macro
˓→')} "

print("-------------------")
(continues on next page)

18.8. Examples for the scikit-learn chapter 653


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# test the number of neighbors


for n_neighbors in range(1, 11):
clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(
f"KNeighbors(n_neighbors={ n_neighbors} ): { metrics.f1_score(y_test, y_pred,␣
˓→average='macro')} "

Total running time of the script: (0 minutes 0.412 seconds)

18.8.10 Plot fitting a 9th order polynomial

Fits data generated from a 9th order polynomial with model of 4th order and 9th order polynomials, to
demonstrate that often simpler models are to be preferred

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

from sklearn import linear_model

# Create color maps for 3-class classification problem, as with iris


cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"])
cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"])

rng = np.random.default_rng(27446968)
x = 2 * rng.random(100) - 1

f = lambda t: 1.2 * t**2 + 0.1 * t**3 - 0.4 * t**5 - 0.5 * t**9


y = f(x) + 0.4 * rng.normal(size=100)

x_test = np.linspace(-1, 1, 100)

The data

plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)

18.8. Examples for the scikit-learn chapter 654


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.collections.PathCollection object at 0x7f494ca99690>

Fitting 4th and 9th order polynomials


For this we need to engineer features: the n_th powers of x:

plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)

X = np.array([x**i for i in range(5)]).T


X_test = np.array([x_test**i for i in range(5)]).T
regr = linear_model.LinearRegression()
regr.fit(X, y)
plt.plot(x_test, regr.predict(X_test), label="4th order")

X = np.array([x**i for i in range(10)]).T


X_test = np.array([x_test**i for i in range(10)]).T
regr = linear_model.LinearRegression()
regr.fit(X, y)
plt.plot(x_test, regr.predict(X_test), label="9th order")

plt.legend(loc="best")
plt.axis("tight")
plt.title("Fitting a 4th and a 9th order polynomial")

18.8. Examples for the scikit-learn chapter 655


Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 1.0, 'Fitting a 4th and a 9th order polynomial')

Ground truth

plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)
plt.plot(x_test, f(x_test), label="truth")
plt.axis("tight")
plt.title("Ground truth (9th order polynomial)")

plt.show()

18.8. Examples for the scikit-learn chapter 656


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.163 seconds)

18.8.11 A simple regression analysis on the California housing data

Here we perform a simple regression analysis on the California housing data, exploring two types of
regressors.

from sklearn.datasets import fetch_california_housing

data = fetch_california_housing(as_frame=True)

Print a histogram of the quantity to predict: price

import matplotlib.pyplot as plt

plt.figure(figsize=(4, 3))
plt.hist(data.target)
plt.xlabel("price ($100k)")
plt.ylabel("count")
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 657


Scientific Python Lectures, Edition 2024.2rc0.dev0

Print the join histogram for each feature

for index, feature_name in enumerate(data.feature_names):


plt.figure(figsize=(4, 3))
plt.scatter(data.data[feature_name], data.target)
plt.ylabel("Price", size=15)
plt.xlabel(feature_name, size=15)
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 658


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8. Examples for the scikit-learn chapter 659


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8. Examples for the scikit-learn chapter 660


Scientific Python Lectures, Edition 2024.2rc0.dev0


Simple prediction

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(data.data, data.target)

from sklearn.linear_model import LinearRegression

clf = LinearRegression()
clf.fit(X_train, y_train)
predicted = clf.predict(X_test)
expected = y_test

plt.figure(figsize=(4, 3))
plt.scatter(expected, predicted)
plt.plot([0, 8], [0, 8], "--k")
plt.axis("tight")
plt.xlabel("True price ($100k)")
plt.ylabel("Predicted price ($100k)")
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 661


Scientific Python Lectures, Edition 2024.2rc0.dev0

Prediction with gradient boosted tree

from sklearn.ensemble import GradientBoostingRegressor

clf = GradientBoostingRegressor()
clf.fit(X_train, y_train)

predicted = clf.predict(X_test)
expected = y_test

plt.figure(figsize=(4, 3))
plt.scatter(expected, predicted)
plt.plot([0, 5], [0, 5], "--k")
plt.axis("tight")
plt.xlabel("True price ($100k)")
plt.ylabel("Predicted price ($100k)")
plt.tight_layout()

Print the error rate

import numpy as np

print(f"RMS: { np.sqrt(np.mean((predicted - expected) ** 2))!r} ")

plt.show()

RMS: 0.5314909993118918

Total running time of the script: (0 minutes 4.331 seconds)

18.8. Examples for the scikit-learn chapter 662


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.12 Nearest-neighbor prediction on iris

Plot the decision boundary of nearest neighbor decision on iris, first with a single nearest neighbor, and
then using 3 nearest neighbors.

import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors, datasets
from matplotlib.colors import ListedColormap

# Create color maps for 3-class classification problem, as with iris


cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"])
cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"])

iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features. We could
# avoid this ugly slicing by using a two-dim dataset
y = iris.target

knn = neighbors.KNeighborsClassifier(n_neighbors=1)
knn.fit(X, y)

x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1


y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100))
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])

Put the result into a color plot

Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points


plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlabel("sepal length (cm)")
plt.ylabel("sepal width (cm)")
plt.axis("tight")

18.8. Examples for the scikit-learn chapter 663


Scientific Python Lectures, Edition 2024.2rc0.dev0

(4.180808080808081, 8.019191919191918, 1.8868686868686868, 4.513131313131313)

And now, redo the analysis with 3 neighbors

knn = neighbors.KNeighborsClassifier(n_neighbors=3)
knn.fit(X, y)

Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot


Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points


plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlabel("sepal length (cm)")
plt.ylabel("sepal width (cm)")
plt.axis("tight")

plt.show()

18.8. Examples for the scikit-learn chapter 664


Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.706 seconds)

18.8.13 Simple visualization and classification of the digits dataset

Plot the first few samples of the digits dataset and a 2D representation built using PCA, then do a simple
classification

from sklearn.datasets import load_digits

digits = load_digits()

Plot the data: images of digits

Each data in a 8x8 image

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 6)) # figure size in inches


fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation="nearest")
# label the image with the target value
ax.text(0, 7, str(digits.target[i]))

18.8. Examples for the scikit-learn chapter 665


Scientific Python Lectures, Edition 2024.2rc0.dev0

Plot a projection on the 2 first principal axis

plt.figure()

from sklearn.decomposition import PCA

pca = PCA(n_components=2)
proj = pca.fit_transform(digits.data)
plt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap="Paired")
plt.colorbar()

18.8. Examples for the scikit-learn chapter 666


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.colorbar.Colorbar object at 0x7f4943638490>

Classify with Gaussian naive Bayes

from sklearn.naive_bayes import GaussianNB


from sklearn.model_selection import train_test_split

# split the data into training and validation sets


X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)

# train the model


clf = GaussianNB()
clf.fit(X_train, y_train)

# use the model to predict the labels of the test data


predicted = clf.predict(X_test)
expected = y_test

# Plot the prediction


fig = plt.figure(figsize=(6, 6)) # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

# plot the digits: each image is 8x8 pixels


for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap=plt.cm.binary, interpolation="nearest
˓→")

(continues on next page)

18.8. Examples for the scikit-learn chapter 667


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# label the image with the target value


if predicted[i] == expected[i]:
ax.text(0, 7, str(predicted[i]), color="green")
else:
ax.text(0, 7, str(predicted[i]), color="red")

Quantify the performance

First print the number of correct matches

matches = predicted == expected


print(matches.sum())

388

The total number of data points

18.8. Examples for the scikit-learn chapter 668


Scientific Python Lectures, Edition 2024.2rc0.dev0

print(len(matches))

450

And now, the ration of correct predictions

matches.sum() / float(len(matches))

0.8622222222222222

Print the classification report

from sklearn import metrics

print(metrics.classification_report(expected, predicted))

precision recall f1-score support

0 1.00 1.00 1.00 51


1 0.62 0.93 0.75 41
2 0.94 0.70 0.80 46
3 0.93 0.87 0.90 47
4 1.00 0.84 0.91 43
5 0.86 0.93 0.89 40
6 0.98 0.98 0.98 45
7 0.86 0.96 0.91 52
8 0.65 0.69 0.67 49
9 0.96 0.69 0.81 36

accuracy 0.86 450


macro avg 0.88 0.86 0.86 450
weighted avg 0.88 0.86 0.86 450

Print the confusion matrix

print(metrics.confusion_matrix(expected, predicted))

plt.show()

[[51 0 0 0 0 0 0 0 0 0]
[ 0 38 0 0 0 0 0 0 3 0]
[ 0 5 32 0 0 0 0 0 9 0]
[ 0 1 0 41 0 2 0 0 2 1]
[ 0 2 1 0 36 0 1 2 1 0]
[ 0 1 0 0 0 37 0 1 1 0]
[ 0 0 1 0 0 0 44 0 0 0]
[ 0 0 0 0 0 1 0 50 1 0]
[ 0 12 0 0 0 1 0 2 34 0]
[ 0 2 0 3 0 2 0 3 1 25]]

Total running time of the script: (0 minutes 1.757 seconds)

18.8. Examples for the scikit-learn chapter 669


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.14 The eigenfaces example: chaining PCA and SVMs

The goal of this example is to show how an unsupervised method and a supervised one can be chained
for better prediction. It starts with a didactic but lengthy way of doing things, and finishes with the
idiomatic approach to pipelining in scikit-learn.
Here we’ll take a look at a simple facial recognition example. Ideally, we would use a dataset con-
sisting of a subset of the Labeled Faces in the Wild data that is available with sklearn.datasets.
fetch_lfw_people(). However, this is a relatively large download (~200MB) so we will do the tutorial
on a simpler, less rich dataset. Feel free to explore the LFW dataset.

from sklearn import datasets

faces = datasets.fetch_olivetti_faces()
faces.data.shape

downloading Olivetti faces from https://ndownloader.figshare.com/files/5976027 to /


˓→home/runner/scikit_learn_data

(400, 4096)

Let’s visualize these faces to see what we’re working with

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 6))


# plot several images
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(faces.images[i], cmap=plt.cm.bone)

18.8. Examples for the scikit-learn chapter 670


Scientific Python Lectures, Edition 2024.2rc0.dev0

Tip: Note is that these faces have already been localized and scaled to a common size. This is an
important preprocessing piece for facial recognition, and is a process that can require a large collection
of training data. This can be done in scikit-learn, but the challenge is gathering a sufficient amount of
training data for the algorithm to work. Fortunately, this piece is common enough that it has been done.
One good resource is OpenCV, the Open Computer Vision Library.

We’ll perform a Support Vector classification of the images. We’ll do a typical train-test split on the
images:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(


faces.data, faces.target, random_state=0
)

print(X_train.shape, X_test.shape)

(300, 4096) (100, 4096)

18.8. Examples for the scikit-learn chapter 671


Scientific Python Lectures, Edition 2024.2rc0.dev0

Preprocessing: Principal Component Analysis

1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable size,
while maintaining most of the information in the dataset.

from sklearn import decomposition

pca = decomposition.PCA(n_components=150, whiten=True)


pca.fit(X_train)

One interesting part of PCA is that it computes the “mean” face, which can be interesting to examine:

plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=plt.cm.bone)

<matplotlib.image.AxesImage object at 0x7f49559aca90>

The principal components measure deviations about this mean along orthogonal axes.

print(pca.components_.shape)

(150, 4096)

It is also interesting to visualize these principal components:

fig = plt.figure(figsize=(16, 6))


for i in range(30):
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[])
ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=plt.cm.bone)

18.8. Examples for the scikit-learn chapter 672


Scientific Python Lectures, Edition 2024.2rc0.dev0

The components (“eigenfaces”) are ordered by their importance from top-left to bottom-right. We
see that the first few components seem to primarily take care of lighting conditions; the remaining
components pull out certain identifying features: the nose, eyes, eyebrows, etc.
With this projection computed, we can now project our original training and test data onto the PCA
basis:

X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print(X_train_pca.shape)

(300, 150)

print(X_test_pca.shape)

(100, 150)

These projected components correspond to factors in a linear combination of component images such
that the combination approaches the original face.

Doing the Learning: Support Vector Machines

Now we’ll perform support-vector-machine classification on this reduced dataset:

from sklearn import svm

clf = svm.SVC(C=5.0, gamma=0.001)


clf.fit(X_train_pca, y_train)

Finally, we can evaluate how well this classification did. First, we might plot a few of the test-cases with
the labels learned from the training set:

import numpy as np

fig = plt.figure(figsize=(8, 6))


for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap=plt.cm.bone)
y_pred = clf.predict(X_test_pca[i, np.newaxis])[0]
color = "black" if y_pred == y_test[i] else "red"
ax.set_title(y_pred, fontsize="small", color=color)

18.8. Examples for the scikit-learn chapter 673


Scientific Python Lectures, Edition 2024.2rc0.dev0

The classifier is correct on an impressive number of images given the simplicity of its learning model!
Using a linear classifier on 150 features derived from the pixel-level data, the algorithm correctly identifies
a large number of the people in the images.
Again, we can quantify this effectiveness using one of several measures from sklearn.metrics. First we
can do the classification report, which shows the precision, recall and other measures of the “goodness”
of the classification:
from sklearn import metrics

y_pred = clf.predict(X_test_pca)
print(metrics.classification_report(y_test, y_pred))

precision recall f1-score support

0 1.00 0.50 0.67 6


1 1.00 1.00 1.00 4
2 0.50 1.00 0.67 2
3 1.00 1.00 1.00 1
4 0.33 1.00 0.50 1
5 1.00 1.00 1.00 5
6 1.00 1.00 1.00 4
7 1.00 0.67 0.80 3
9 1.00 1.00 1.00 1
10 1.00 1.00 1.00 4
11 1.00 1.00 1.00 1
12 0.67 1.00 0.80 2
13 1.00 1.00 1.00 3
14 1.00 1.00 1.00 5
(continues on next page)

18.8. Examples for the scikit-learn chapter 674


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


15 1.00 1.00 1.00 3
17 1.00 1.00 1.00 6
19 1.00 1.00 1.00 4
20 1.00 1.00 1.00 1
21 1.00 1.00 1.00 1
22 1.00 1.00 1.00 2
23 1.00 1.00 1.00 1
24 1.00 1.00 1.00 2
25 1.00 0.50 0.67 2
26 1.00 0.75 0.86 4
27 1.00 1.00 1.00 1
28 0.67 1.00 0.80 2
29 1.00 1.00 1.00 3
30 1.00 1.00 1.00 4
31 1.00 1.00 1.00 3
32 1.00 1.00 1.00 3
33 1.00 1.00 1.00 2
34 1.00 1.00 1.00 3
35 1.00 1.00 1.00 1
36 1.00 1.00 1.00 3
37 1.00 1.00 1.00 3
38 1.00 1.00 1.00 1
39 1.00 1.00 1.00 3

accuracy 0.94 100


macro avg 0.95 0.96 0.94 100
weighted avg 0.97 0.94 0.94 100

Another interesting metric is the confusion matrix, which indicates how often any two items are mixed-
up. The confusion matrix of a perfect classifier would only have nonzero entries on the diagonal, with
zeros on the off-diagonal:

print(metrics.confusion_matrix(y_test, y_pred))

[[3 0 0 ... 0 0 0]
[0 4 0 ... 0 0 0]
[0 0 2 ... 0 0 0]
...
[0 0 0 ... 3 0 0]
[0 0 0 ... 0 1 0]
[0 0 0 ... 0 0 3]]

Pipelining

Above we used PCA as a pre-processing step before applying our support vector machine classifier.
Plugging the output of one estimator directly into the input of a second estimator is a commonly used
pattern; for this reason scikit-learn provides a Pipeline object which automates this process. The above
problem can be re-expressed as a pipeline as follows:

from sklearn.pipeline import Pipeline

clf = Pipeline(
[
("pca", decomposition.PCA(n_components=150, whiten=True)),
("svm", svm.LinearSVC(C=1.0)),
(continues on next page)

18.8. Examples for the scikit-learn chapter 675


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


]
)

clf.fit(X_train, y_train)

y_pred = clf.predict(X_test)
print(metrics.confusion_matrix(y_pred, y_test))
plt.show()

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣

˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.

warnings.warn(
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣

˓→iterations.

warnings.warn(
[[5 0 0 ... 0 0 0]
[0 4 0 ... 0 0 0]
[0 0 1 ... 0 0 0]
...
[0 0 0 ... 3 0 0]
[0 0 0 ... 0 1 0]
[0 0 0 ... 0 0 3]]

A Note on Facial Recognition

Here we have used PCA “eigenfaces” as a pre-processing step for facial recognition. The reason we
chose this is because PCA is a broadly-applicable technique, which can be useful for a wide array of
data types. Research in the field of facial recognition in particular, however, has shown that other more
specific feature extraction methods are can be much more effective.
Total running time of the script: (0 minutes 3.737 seconds)

18.8.15 Example of linear and non-linear models

This is an example plot from the tutorial which accompanies an explanation of the support vector
machine GUI.

import numpy as np
import matplotlib.pyplot as plt

from sklearn import svm

rng = np.random.default_rng(27446968)

data that is linearly separable

def linear_model(rseed=42, n_samples=30):


"Generate data according to a linear model"
np.random.seed(rseed)

(continues on next page)

18.8. Examples for the scikit-learn chapter 676


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


data = np.random.normal(0, 10, (n_samples, 2))
data[: n_samples // 2] -= 15
data[n_samples // 2 :] += 15

labels = np.ones(n_samples)
labels[: n_samples // 2] = -1

return data, labels

X, y = linear_model()
clf = svm.SVC(kernel="linear")
clf.fit(X, y)

plt.figure(figsize=(6, 4))
ax = plt.subplot(111, xticks=[], yticks=[])
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone)

ax.scatter(
clf.support_vectors_[:, 0],
clf.support_vectors_[:, 1],
s=80,
edgecolors="k",
facecolors="none",
)

delta = 1
y_min, y_max = -50, 50
x_min, x_max = -50, 50
x = np.arange(x_min, x_max + delta, delta)
y = np.arange(y_min, y_max + delta, delta)
X1, X2 = np.meshgrid(x, y)
Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
Z = Z.reshape(X1.shape)

ax.contour(
X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"]
)

18.8. Examples for the scikit-learn chapter 677


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.contour.QuadContourSet object at 0x7f494c053150>

data with a non-linear separation

def nonlinear_model(rseed=27446968, n_samples=30):


rng = np.random.default_rng(rseed)

radius = 40 * rng.random(n_samples)
far_pts = radius > 20
radius[far_pts] *= 1.2
radius[~far_pts] *= 1.1

theta = rng.random(n_samples) * np.pi * 2

data = np.empty((n_samples, 2))


data[:, 0] = radius * np.cos(theta)
data[:, 1] = radius * np.sin(theta)

labels = np.ones(n_samples)
labels[far_pts] = -1

return data, labels

X, y = nonlinear_model()
clf = svm.SVC(kernel="rbf", gamma=0.001, coef0=0, degree=3)
clf.fit(X, y)

plt.figure(figsize=(6, 4))
ax = plt.subplot(1, 1, 1, xticks=[], yticks=[])
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone, zorder=2)

(continues on next page)

18.8. Examples for the scikit-learn chapter 678


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax.scatter(
clf.support_vectors_[:, 0],
clf.support_vectors_[:, 1],
s=80,
edgecolors="k",
facecolors="none",
)

delta = 1
y_min, y_max = -50, 50
x_min, x_max = -50, 50
x = np.arange(x_min, x_max + delta, delta)
y = np.arange(y_min, y_max + delta, delta)
X1, X2 = np.meshgrid(x, y)
Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
Z = Z.reshape(X1.shape)

ax.contour(
X1,
X2,
Z,
[-1.0, 0.0, 1.0],
colors="k",
linestyles=["dashed", "solid", "dashed"],
zorder=1,
)

plt.show()

Total running time of the script: (0 minutes 0.065 seconds)

18.8. Examples for the scikit-learn chapter 679


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.16 Bias and variance of polynomial fit

Demo overfitting, underfitting, and validation and learning curves with polynomial regression.
Fit polynomes of different degrees to a dataset: for too small a degree, the model underfits, while for too
large a degree, it overfits.

import numpy as np
import matplotlib.pyplot as plt

def generating_func(x, rng=None, error=0.5):


rng = np.random.default_rng(rng)
return rng.normal(10 - 1.0 / (x + 0.1), error)

A polynomial regression

from sklearn.pipeline import make_pipeline


from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

A simple figure to illustrate the problem

n_samples = 8

rng = np.random.default_rng(27446968)
x = 10 ** np.linspace(-2, 0, n_samples)
y = generating_func(x, rng=rng)

x_test = np.linspace(-0.2, 1.2, 1000)

titles = ["d = 1 (under-fit; high bias)", "d = 2", "d = 6 (over-fit; high variance)"]
degrees = [1, 2, 6]

fig = plt.figure(figsize=(9, 3.5))


fig.subplots_adjust(left=0.06, right=0.98, bottom=0.15, top=0.85, wspace=0.05)

for i, d in enumerate(degrees):
ax = fig.add_subplot(131 + i, xticks=[], yticks=[])
ax.scatter(x, y, marker="x", c="k", s=50)

model = make_pipeline(PolynomialFeatures(d), LinearRegression())


model.fit(x[:, np.newaxis], y)
ax.plot(x_test, model.predict(x_test[:, np.newaxis]), "-b")

ax.set_xlim(-0.2, 1.2)
ax.set_ylim(0, 12)
ax.set_xlabel("house size")
if i == 0:
ax.set_ylabel("price")

ax.set_title(titles[i])

18.8. Examples for the scikit-learn chapter 680


Scientific Python Lectures, Edition 2024.2rc0.dev0

Generate a larger dataset

from sklearn.model_selection import train_test_split

n_samples = 200
test_size = 0.4
error = 1.0

# randomly sample the data


x = rng.random(n_samples)
y = generating_func(x, rng=rng, error=error)

# split into training, validation, and testing sets.


x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size)

# show the training and validation sets


plt.figure(figsize=(6, 4))
plt.scatter(x_train, y_train, color="red", label="Training set")
plt.scatter(x_test, y_test, color="blue", label="Test set")
plt.title("The data")
plt.legend(loc="best")

18.8. Examples for the scikit-learn chapter 681


Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.legend.Legend object at 0x7f49437c1bd0>

Plot a validation curve

from sklearn.model_selection import validation_curve

degrees = np.arange(1, 21)

model = make_pipeline(PolynomialFeatures(), LinearRegression())

# The parameter to vary is the "degrees" on the pipeline step


# "polynomialfeatures"
train_scores, validation_scores = validation_curve(
model,
x[:, np.newaxis],
y,
param_name="polynomialfeatures__degree",
param_range=degrees,
)

# Plot the mean train error and validation error across folds
plt.figure(figsize=(6, 4))
plt.plot(degrees, validation_scores.mean(axis=1), lw=2, label="cross-validation")
plt.plot(degrees, train_scores.mean(axis=1), lw=2, label="training")

plt.legend(loc="best")
plt.xlabel("degree of fit")
plt.ylabel("explained variance")
plt.title("Validation curve")
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 682


Scientific Python Lectures, Edition 2024.2rc0.dev0

Learning curves

Plot train and test error with an increasing number of samples

# A learning curve for d=1, 5, 15


for d in [1, 5, 15]:
model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression())

from sklearn.model_selection import learning_curve

train_sizes, train_scores, validation_scores = learning_curve(


model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20)
)

# Plot the mean train error and validation error across folds
plt.figure(figsize=(6, 4))
plt.plot(
train_sizes, validation_scores.mean(axis=1), lw=2, label="cross-validation"
)
plt.plot(train_sizes, train_scores.mean(axis=1), lw=2, label="training")
plt.ylim(ymin=-0.1, ymax=1)

plt.legend(loc="best")
plt.xlabel("number of train samples")
plt.ylabel("explained variance")
plt.title("Learning curve (degree=%i )" % d)
plt.tight_layout()

plt.show()

18.8. Examples for the scikit-learn chapter 683


Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8. Examples for the scikit-learn chapter 684


Scientific Python Lectures, Edition 2024.2rc0.dev0


Total running time of the script: (0 minutes 1.252 seconds)

18.8.17 Tutorial Diagrams

This script plots the flow-charts used in the scikit-learn tutorials.

18.8. Examples for the scikit-learn chapter 685


Scientific Python Lectures, Edition 2024.2rc0.dev0

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow

def create_base(box_bg="#CCCCCC", arrow1="#88CCFF", arrow2="#88FF88",␣


˓→supervised=True):

fig = plt.figure(figsize=(9, 6), facecolor="w")


(continues on next page)

18.8. Examples for the scikit-learn chapter 686


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False)
ax.set_xlim(0, 9)
ax.set_ylim(0, 6)

patches = [
Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg),
Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg),
Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg),
Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg),
Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg),
Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg),
Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg),
Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg),
Circle((5.5, 3.5), 1.0, fc=box_bg),
Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg),
FancyArrow(
2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_
˓→length=0.2

),
FancyArrow(
5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2
),
]

if supervised:
patches += [
Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg),
Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg),
Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg),
FancyArrow(
2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_
˓→length=0.2

),
Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg),
]
else:
patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)]

for p in patches:
ax.add_patch(p)

plt.text(
1.45,
4.9,
(continues on next page)

18.8. Examples for the scikit-learn chapter 687


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


"Training\nText,\nDocuments,\nImages,\netc.",
ha="center",
va="center",
fontsize=14,
)

plt.text(3.6, 4.9, "Feature\nVectors", ha="left", va="center", fontsize=14)

plt.text(
5.5, 3.5, "Machine\nLearning\nAlgorithm", ha="center", va="center",␣
˓→fontsize=14

plt.text(
1.05,
1.1,
"New Text,\nDocument,\nImage,\netc.",
ha="center",
va="center",
fontsize=14,
)

plt.text(3.3, 1.7, "Feature\nVector", ha="left", va="center", fontsize=14)

plt.text(5.5, 1.1, "Predictive\nModel", ha="center", va="center", fontsize=12)

if supervised:
plt.text(1.45, 3.05, "Labels", ha="center", va="center", fontsize=14)

plt.text(8.05, 1.1, "Expected\nLabel", ha="center", va="center", fontsize=14)


plt.text(
8.8, 5.8, "Supervised Learning Model", ha="right", va="top", fontsize=18
)

else:
plt.text(
8.05,
1.1,
"Likelihood\nor Cluster ID\nor Better\nRepresentation",
ha="center",
va="center",
fontsize=12,
)
plt.text(
8.8, 5.8, "Unsupervised Learning Model", ha="right", va="top", fontsize=18
)

def plot_supervised_chart(annotate=False):
create_base(supervised=True)
if annotate:
fontdict = {"color": "r", "weight": "bold", "size": 14}
plt.text(
1.9,
4.55,
"X = vec.fit_transform(input)",
(continues on next page)

18.8. Examples for the scikit-learn chapter 688


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


fontdict=fontdict,
rotation=20,
ha="left",
va="bottom",
)
plt.text(
3.7,
3.2,
"clf.fit(X, y)",
fontdict=fontdict,
rotation=20,
ha="left",
va="bottom",
)
plt.text(
1.7,
1.5,
"X_new = vec.transform(input)",
fontdict=fontdict,
rotation=20,
ha="left",
va="bottom",
)
plt.text(
6.1,
1.5,
"y_new = clf.predict(X_new)",
fontdict=fontdict,
rotation=20,
ha="left",
va="bottom",
)

def plot_unsupervised_chart():
create_base(supervised=False)

if __name__ == "__main__":
plot_supervised_chart(False)
plot_supervised_chart(True)
plot_unsupervised_chart()
plt.show()

Total running time of the script: (0 minutes 0.195 seconds)

See also:
Going further
• The documentation of scikit-learn is very complete and didactic.
• Introduction to Machine Learning with Python, by Sarah Guido, Andreas Müller (notebooks avail-
able here).

18.8. Examples for the scikit-learn chapter 689


Part IV

About the Scientific Python


Lectures

690
CHAPTER 19
About the Scientific Python Lectures

Release: 2024.2rc0.dev0
The lectures are archived on zenodo: http://dx.doi.org/10.5281/zenodo.594102
All code and material is licensed under a Creative Commons Attribution 4.0 International License (CC-
by) http://creativecommons.org/licenses/by/4.0/

19.1 Authors • Christophe Combelles

• André Espaze
19.1.1 Editors
• Emmanuelle Gouillart
• Gaël Varoquaux
• Emmanuelle Gouillart • Mike Müller
• Olav Vahtras
• Fabian Pedregosa
• Pierre de Buyl
• K. Jarrod Millman • Didrik Pinte
• Stéfan van der Walt
• Nicolas Rougier

19.1.2 Chapter authors • Gaël Varoquaux

Listed by alphabetical order. • Pauli Virtanen


• Christopher Burns
• Zbigniew Jędrzejewski-Szmek
• Adrian Chauve
• Robert Cimrman • Valentin Haenel (editor from 2011 to 2015)

691
Scientific Python Lectures, Edition 2024.2rc0.dev0

19.1.3 Additional Contributions • Valentin Haenel


• Pierre Haessig
Listed by alphabetical order
• Bruno Hanzen
• Osayd Abdu
• Michael Hartmann
• arunpersaud
• Jonathan Helmus
• Ross Barnowski
• Andreas Hilboll
• Sebastian Berg
• Himanshu
• Lilian Besson
• Julian Hofer
• Matthieu Boileau
• Tim Hoffmann
• Joris Van den Bossche
• Michael Boyle • B. Hohl

• Matthew Brett • Tarek Hoteit

• BSGalvan • Gert-Ludwig Ingold

• Lars Buitinck • Zbigniew Jędrzejewski-Szmek

• Pierre de Buyl • Thouis (Ray) Jones

• Ozan Çağlayan • jorgeprietoarranz

• Lawrence Chan • josephsalmon

• Adrien Chauve • Greg Kiar

• Robert Cimrman • kikocorreoso

• Christophe Combelles • Vince Knight

• David Cournapeau • LFP6

• Dave • Manuel López-Ibáñez

• dogacan dugmeci • Marco Mangan

• Török Edwin • Nicola Masarone

• egens • John McLaughlin

• Andre Espaze • mhemantha

• André Espaze • michelemaroni89

• Loïc Estève • K. Jarrod Millman

• Corey Farwell • Mohammad


• Tim Gates • Zachary Moon
• Stuart Geiger • Mike Mueller
• Olivier Georg • negm
• Daniel Gerigk • John B Nelson
• Robert Gieseke • nicoguaro
• Philip Gillißen • Sergio Oller
• Ralf Gommers • Theofilos Papapanagiotou
• Emmanuelle Gouillart • patniharshit
• Julia Gustavsen • Fabian Pedregosa
• Omar Gutiérrez • Philippe Pepiot
• Matt Haberland • Tiago M. D. Pereira

19.1. Authors 692


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Nicolas Pettiaux • strpeter


• Didrik Pinte • surfer190
• Evgeny Pogrebnyak • Bartosz Telenczuk
• reverland • tommyod
• Maximilien Riehl • Wes Turner
• Kristian Rother
• Akihiro Uchida
• Nicolas P. Rougier
• Utkarsh Upadhyay
• Pamphile Roy
• Olav Vahtras
• Rutzmoser
• Stéfan van der Walt
• Sander
• Gaël Varoquaux
• João Felipe Santos
• Nelle Varoquaux
• Mark Setchell
• Olivier Verdier
• Helen Sherwood-Taylor
• Shoeboxam • VirgileFritsch

• Simon • Pauli Virtanen

• solarjoe • Yosh Wakeham

• ssmiller • yasutomo57jp
• Scott Staniewicz

19.1. Authors 693


Index

D
diff, 572, 576
differentiation, 572
dsolve, 576

E
equations
algebraic, 574
differential, 576

I
integration, 574

M
Matrix, 576

P
Python Enhancement Proposals
PEP 255, 301
PEP 3118, 340
PEP 3129, 311
PEP 318, 303, 311
PEP 342, 301
PEP 343, 311
PEP 380, 302
PEP 380#id13, 302
PEP 8, 305

S
solve, 574

694
Contents

SciKits Numpy Matplotlib I Getting started with Python for science 2


1 Python scientific computing ecosystem 4
1.1 Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2024
1.2 The scientific Python ecosystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Before starting: Installing a working environment . . . . . . . . . . . . . . . . . . . . . . 7
1.4 The workflow: interactive environments and text editors . . . . . . . . . . . . . . . . . . 8
SciPy Python EDITION
2 The Python language 12
2.1 First steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Basic types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
IP[y]: 2.5 Reusing code: scripts and modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.6 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Cython IPython
2.7 Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.8 Exception handling in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.9 Object-oriented programming (OOP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

3 NumPy: creating and manipulating numerical data 53


Edited by 3.1 The NumPy array object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Scien�fic Python
3.2 Numerical operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Gaël Varoquaux 3.3 More elaborate arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Emmanuelle Gouillart 3.4 Advanced operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Olaf Vahtras

Lectures
3.5 Some exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Pierre de Buyl 3.6 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
K. Jarrod Millman
Stéfan van der Walt 4 Matplotlib: plotting 106
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
4.2 Simple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
lectures.scientific-python.org 4.3 Figures, Subplots, Axes and Ticks .
4.4 Other Types of Plots: examples and
. . . . . .
exercises .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
115
118
4.5 Beyond this tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
4.6 Quick references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
4.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Gaël Varoquaux • Emmanuelle Gouillart • Olav Vahtras
Pierre de Buyl • K. Jarrod Millman • Stéfan van der Walt 5 SciPy : high-level scientific computing 210
5.1 File input/output: scipy.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Christopher Burns • Adrian Chauve • Robert Cimrman • Christophe Combelles 5.2 Special functions: scipy.special . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Ralf Gommers • André Espaze • Zbigniew Jędrzejewski-Szmek
Valen� n Haenel • Michael Hartmann • Gert-Ludwig Ingold • Fabian Pedregosa
Didrik Pinte • Nicolas P. Rougier • Joris Van den Bossche • Pauli Virtanen i

and many others...


5.3 Linear algebra operations: scipy.linalg . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 13.3 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
5.4 Interpolation: scipy.interpolate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 13.4 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . 446
5.5 Optimization and fit: scipy.optimize . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 13.5 Practical guide to optimization with SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . 486
5.6 Statistics and random numbers: scipy.stats . . . . . . . . . . . . . . . . . . . . . . . . 222 13.6 Special case: non-linear least-squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
5.7 Numerical integration: scipy.integrate . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 13.7 Optimization with constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
5.8 Fast Fourier transforms: scipy.fft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13.8 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
5.9 Signal processing: scipy.signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 13.9 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . 491
5.10 Image manipulation: scipy.ndimage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
5.11 Summary exercises on scientific computing . . . . . . . . . . . . . . . . . . . . . . . . . . 236 14 Interfacing with C 492
5.12 Full code examples for the SciPy chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
14.2 Python-C-Api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
6 Getting help and finding documentation 292 14.3 Ctypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
14.4 SWIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
14.5 Cython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
II Advanced topics 295 14.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
14.7 Further Reading and References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
7 Advanced Python Constructs 297 14.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
7.1 Iterators, generator expressions and generators . . . . . . . . . . . . . . . . . . . . . . . . 298
7.2 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
7.3 Context managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 III Packages and applications 517
8 Advanced NumPy 315 15 Statistics in Python 519
8.1 Life of ndarray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 15.1 Data representation and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
8.2 Universal functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 15.2 Hypothesis testing: comparing two groups . . . . . . . . . . . . . . . . . . . . . . . . . . 525
8.3 Interoperability features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 15.3 Linear models, multiple factors, and analysis of variance . . . . . . . . . . . . . . . . . . . 528
8.4 Array siblings: chararray, maskedarray . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 15.4 More visualization: seaborn for statistical exploration . . . . . . . . . . . . . . . . . . . . 534
8.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 15.5 Testing for interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
8.6 Contributing to NumPy/SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 15.6 Full code for the figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
15.7 Solutions to this chapter’s exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
9 Debugging code 349
9.1 Avoiding bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 16 Sympy : Symbolic Mathematics in Python 569
9.2 Debugging workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352 16.1 First Steps with SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
9.3 Using the Python debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 16.2 Algebraic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
9.4 Debugging segmentation faults using gdb . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 16.3 Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
16.4 Equation solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
10 Optimizing code 361 16.5 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
10.1 Optimization workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
10.2 Profiling Python code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 17 scikit-image: image processing 578
10.3 Making code go faster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 17.1 Introduction and concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
10.4 Writing faster numerical code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 17.2 Importing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
17.3 Example data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
11 Sparse Arrays in SciPy 369 17.4 Input/output, data types and colorspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369 17.5 Image preprocessing / enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
11.2 Storage Schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372 17.6 Image segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
11.3 Linear System Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384 17.7 Measuring regions’ properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
11.4 Other Interesting Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390 17.8 Data visualization and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
17.9 Feature extraction for computer vision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
12 Image manipulation and processing using NumPy and SciPy 391
17.10 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
12.1 Opening and writing to image files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
17.11 Examples for the scikit-image chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
12.2 Displaying images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
12.3 Basic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 18 scikit-learn: machine learning in Python 605
12.4 Image filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 18.1 Introduction: problem settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
12.5 Feature extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 18.2 Basic principles of machine learning with scikit-learn . . . . . . . . . . . . . . . . . . . . 610
12.6 Measuring objects properties: scipy.ndimage.measurements . . . . . . . . . . . . . . . . 406 18.3 Supervised Learning: Classification of Handwritten Digits . . . . . . . . . . . . . . . . . . 616
12.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409 18.4 Supervised Learning: Regression of Housing Data . . . . . . . . . . . . . . . . . . . . . . 620
12.8 Examples for the image processing chapter . . . . . . . . . . . . . . . . . . . . . . . . . . 409 18.5 Measuring prediction performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
18.6 Unsupervised Learning: Dimensionality Reduction and Visualization . . . . . . . . . . . . 631
13 Mathematical optimization: finding minima of functions 436
18.7 Parameter selection, Validation, and Testing . . . . . . . . . . . . . . . . . . . . . . . . . 634
13.1 Knowing your problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
18.8 Examples for the scikit-learn chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
13.2 A review of the different optimizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440

ii iii
Scientific Python Lectures, Edition 2024.2rc0.dev0

IV About the Scientific Python Lectures 690


19 About the Scientific Python Lectures 691
19.1 Authors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

Index 694

iv Contents 1
Scientific Python Lectures, Edition 2024.2rc0.dev0

This part of the Scientific Python Lectures is a self-contained introduction to everything that is needed
to use Python for science, from the language itself, to numerical computing or plotting.

Part I

Getting started with Python for


science

2 3
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Efficient code Python numerical modules are computationally efficient. But needless to say that
a very fast code becomes useless if too much time is spent writing it. Python aims for quick
development times and quick execution times.
• Universal Python is a language used for many different problems. Learning Python avoids learning
a new software for each new problem.

1.1.3 How does Python compare to other solutions?

CHAPTER 1 Compiled languages: C, C++, Fortran. . .

Pros
• Very fast. For heavy computations, it’s difficult to outperform these languages.
Cons
• Painful usage: no interactivity during development, mandatory compilation steps,
verbose syntax, manual memory management. These are difficult languages for
non programmers.

Python scientific computing ecosystem Matlab scripting language

Pros
• Very rich collection of libraries with numerous algorithms, for many different do-
mains. Fast execution because these libraries are often written in a compiled lan-
guage.
• Pleasant development environment: comprehensive and help, integrated editor, etc.
Authors: Fernando Perez, Emmanuelle Gouillart, Gaël Varoquaux, Valentin Haenel • Commercial support is available.
Cons
1.1 Why Python? • Base language is quite poor and can become restrictive for advanced users.
• Not free and not everything is open sourced.
1.1.1 The scientist’s needs
Julia
• Get data (simulation, experiment control),
• Manipulate and process data, Pros
• Visualize results, quickly to understand, but also with high quality figures, for reports or publica- • Fast code, yet interactive and simple.
tions.
• Easily connects to Python or C.
Cons
1.1.2 Python’s strengths
• Ecosystem limited to numerical computing.
• Batteries included Rich collection of already existing bricks of classic numerical methods, plot- • Still young.
ting or data processing tools. We don’t want to re-program the plotting of a curve, a Fourier
transform or a fitting algorithm. Don’t reinvent the wheel!
• Easy to learn Most scientists are not paid as programmers, neither have they been trained so.
They need to be able to draw a curve, smooth a signal, do a Fourier transform in a few minutes.
• Easy communication To keep code alive within a lab or a company it should be as readable
as a book by collaborators, students, or maybe customers. Python syntax is simple, avoiding
strange symbols or lengthy routine specifications that would divert the reader from mathematical
or scientific understanding of the code.

4 1.1. Why Python? 5


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Other scripting languages: Scilab, Octave, R, IDL, etc. • NumPy: numerical computing with powerful numerical arrays objects, and routines to manip-
ulate them. https://numpy.org/
Pros
See also:
• Open-source, free, or at least cheaper than Matlab.
chapter on numpy
• Some features can be very advanced (statistics in R, etc.)
• SciPy : high-level numerical routines. Optimization, regression, interpolation, etc https://scipy.
Cons org/
• Fewer available algorithms than in Matlab, and the language is not more advanced. See also:
• Some software are dedicated to one domain. Ex: Gnuplot to draw curves. These chapter on SciPy
programs are very powerful, but they are restricted to a single type of usage, such
• Matplotlib : 2-D visualization, “publication-ready” plots https://matplotlib.org/
as plotting.
See also:

Python chapter on matplotlib


Advanced interactive environments:
Pros
• IPython, an advanced Python console https://ipython.org/
• Very rich scientific computing libraries
• Jupyter, notebooks in the browser https://jupyter.org/
• Well thought out language, allowing to write very readable and well structured code:
we “code what we think”. Domain-specific packages,

• Many libraries beyond scientific computing (web server, serial port access, etc.) • pandas, statsmodels, seaborn for statistics

• Free and open-source software, widely spread, with a vibrant community. • sympy for symbolic computing

• A variety of powerful environments to work in, such as IPython, Spyder, Jupyter • scikit-image for image processing
notebooks, Pycharm, Visual Studio Code • scikit-learn for machine learning
Cons and many more packages not documented in the Scientific Python Lectures.
• Not all the algorithms that can be found in more specialized software or toolboxes. See also:
chapters on advanced topics
1.2 The scientific Python ecosystem chapters on packages and applications

Unlike Matlab, or R, Python does not come with a pre-bundled set of modules for scientific computing.
Below are the basic building blocks that can be combined to obtain a scientific computing environment:
1.3 Before starting: Installing a working environment

Python comes in many flavors, and there are many ways to install it. However, we recommend to install
a scientific-computing distribution, that comes readily with optimized versions of scientific modules.
Python, a generic and modern computing language Under Linux
• The language: flow control, data types (string, int), data collections (lists, dictionaries), etc. If you have a recent distribution, most of the tools are probably packaged, and it is recommended to use
• Modules of the standard library: string processing, file management, simple network protocols. your package manager.

• A large number of specialized modules or applications written in Python: web framework, etc. . . . Other systems
and scientific computing. There are several fully-featured scientific Python distributions:
• Development tools (automatic testing, documentation generation) • Anaconda
See also: • WinPython
chapter on Python language
Core numeric libraries

1.2. The scientific Python ecosystem 6 1.3. Before starting: Installing a working environment 7
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

1.4 The workflow: interactive environments and text editors Some of these are shipped by the various scientific Python distributions, and you can find them in the
menus.
Interactive work to test and understand algorithms: In this section, we describe a workflow As an exercise, create a file my_file.py in a code editor, and add the following lines:
combining interactive work and consolidation.
s = 'Hello world'
Python is a general-purpose language. As such, there is not one blessed environment to work in, and print(s)
not only one way of using it. Although this makes it harder for beginners to find their way, it makes it
possible for Python to be used for programs, in web servers, or embedded devices. Now, you can run it in IPython console or a notebook and explore the resulting variables:

In [3]: %run my_file.py


1.4.1 Interactive work Hello world

We recommend an interactive work with the IPython console, or its offspring, the Jupyter notebook. In [4]: s
They are handy to explore and understand algorithms. Out[4]: 'Hello world'

In [5]: %whos
Under the notebook
Variable Type Data/Info
----------------------------
To execute code, press “shift enter”
s str Hello world

Start ipython:
From a script to functions
In [1]: print('Hello world')
Hello world
While it is tempting to work only with scripts, that is a file full of instructions following each other,
do plan to progressively evolve the script to a set of functions:
Getting help by using the ? operator after an object:
• A script is not reusable, functions are.
In [2]: print?
Signature: print(*args, sep=' ', end='\n', file=None, flush=False) • Thinking in terms of functions helps breaking the problem in small blocks.
Docstring:
Prints the values to a stream, or to sys.stdout by default.
1.4.3 IPython and Jupyter Tips and Tricks
sep
string inserted between values, default a space.
The user manuals contain a wealth of information. Here we give a quick introduction to four useful
end
features: history, tab completion, magic functions, and aliases.
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Type: builtin_function_or_method
Command history Like a UNIX shell, the IPython console supports command history. Type up and
down to navigate previously typed commands:
See also:
In [6]: x = 10
• IPython user manual: https://ipython.readthedocs.io/en/stable/
• Jupyter Notebook QuickStart: https://docs.jupyter.org/en/latest/start/index.html In [7]: <UP>

In [8]: x = 10
1.4.2 Elaboration of the work in an editor

As you move forward, it will be important to not only work interactively, but also to create and reuse
Python files. For this, a powerful code editor will get you far. Here are several good easy-to-use editors:
• Spyder: integrates an IPython console, a debugger, a profiler. . .
• PyCharm: integrates an IPython console, notebooks, a debugger. . . (freely available, but commer- Tab completion Tab completion, is a convenient way to explore the structure of any object you’re
cial) dealing with. Simply type object_name.<TAB> to view the object’s attributes. Besides Python objects
and keywords, tab completion also works on file and directory names.*
• Visual Studio Code: integrates a Python console, notebooks, a debugger, . . .

1.4. The workflow: interactive environments and text editors 8 1.4. The workflow: interactive environments and text editors 9
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


In [9]: x = 10
88 def reset_compiler_flags(self):
In [10]: x.<TAB> ipdb> locals()
as_integer_ratio() conjugate() imag to_bytes() {'self': <IPython.core.compilerop.CachingCompiler object at 0x7f30d02efc10>,
˓→'source': 'x === 10\n', 'filename': '<ipython-input-1-8e8bc565444b>', 'symbol
bit_count() denominator numerator
˓→': 'exec'}
bit_length() from_bytes() real
ipdb>

See also:
Chapter on debugging

Magic functions The console and the notebooks support so-called magic functions by prefixing a
command with the % character. For example, the run and whos functions from the previous section are
magic functions. Note that, the setting automagic, which is enabled by default, allows you to omit the
preceding % sign. Thus, you can just type the magic function and it will work.
Aliases Furthermore IPython ships with various aliases which emulate common UNIX command line
Other useful magic functions are: tools such as ls to list files, cp to copy files and rm to remove files (a full list of aliases is shown when
• %cd to change the current directory. typing alias).

In [11]: cd /tmp
Getting help
/tmp
• The built-in cheat-sheet is accessible via the %quickref magic function.
• %cpaste allows you to paste code, especially code from websites which has been prefixed with the
standard Python prompt (e.g. >>>) or with an ipython prompt, (e.g. in [3]): • A list of all available magic functions is shown when typing %magic.

In [12]: %cpaste

• %timeit allows you to time the execution of short snippets using the timeit module from the
standard library:

In [12]: %timeit x = 10
11.6 ns +- 0.818 ns per loop (mean +- std. dev. of 7 runs, 100,000,000 loops␣
˓→each)

See also:
Chapter on optimizing code
• %debug allows you to enter post-mortem debugging. That is to say, if the code you try to execute,
raises an exception, using %debug will enter the debugger at the point where the exception was
thrown.

In [13]: x === 10
Cell In[13], line 1
x === 10
^
SyntaxError: invalid syntax

In [14]: %debug
> /home/jarrod/.venv/lectures/lib64/python3.11/site-packages/IPython/core/
˓→compilerop.py(86)ast_parse()

84 Arguments are exactly the same as ast.parse (in the standard␣


˓→library),

85 and are passed to the built-in compile function."""


---> 86 return compile(source, filename, symbol, self.flags | PyCF_ONLY_
˓→AST, 1)

87
(continues on next page)

1.4. The workflow: interactive environments and text editors 10 1.4. The workflow: interactive environments and text editors 11
Scientific Python Lectures, Edition 2024.2rc0.dev0

• a language for which a large variety of high-quality packages are available for various applications,
from web frameworks to scientific computing.
• a language very easy to interface with other languages, in particular C and C++.
• Some other features of the language are illustrated just below. For example, Python is an object-
oriented language, with dynamic typing (the same variable can contain objects of different types
during the course of a program).

2
See https://www.python.org/about/ for more information about distinguishing features of Python.

CHAPTER
2.1 First steps

Start the Ipython shell (an enhanced interactive Python shell):


• by typing “ipython” from a Linux/Mac terminal, or from the Windows cmd shell,
• or by starting the program from a menu, e.g. the Anaconda Navigator, the Python(x,y) menu if
you have installed one of these scientific-Python suites.
The Python language
Tip: If you don’t have Ipython installed on your computer, other Python shells are available, such
as the plain Python shell started by typing “python” in a terminal, or the Idle interpreter. However,
we advise to use the Ipython shell because of its enhanced features, especially for interactive scientific
computing.

Once you have started the interpreter, type


Authors: Chris Burns, Christophe Combelles, Emmanuelle Gouillart, Gaël Varoquaux
>>> print("Hello, world!")
Hello, world!
Python for scientific computing

We introduce here the Python language. Only the bare minimum necessary for getting started with Tip: The message “Hello, world!” is then displayed. You just executed your first Python instruction,
NumPy and SciPy is addressed here. To learn more about the language, consider going through the congratulations!
excellent tutorial https://docs.python.org/3/tutorial. Dedicated books are also available, such as Dive
into Python 3.
To get yourself started, type the following stack of instructions

>>> a = 3
>>> b = 2*a
>>> type(b)
<class 'int'>
>>> print(b)
6
Tip: Python is a programming language, as are C, Fortran, BASIC, PHP, etc. Some specific >>> a*b
features of Python are as follows: 18
>>> b = 'hello'
• an interpreted (as opposed to compiled) language. Contrary to e.g. C or Fortran, one does not
>>> type(b)
compile Python code before executing it. In addition, Python can be used interactively: many
<class 'str'>
Python interpreters are available, from which commands and scripts can be executed.
>>> b + b
• a free software released under an open-source license: Python can be used and distributed free 'hellohello'
of charge, even for building commercial software. >>> 2*b
'hellohello'
• multi-platform: Python is available for all major operating systems, Windows, Linux/Unix,
MacOS X, most likely your mobile phone OS, etc.
• a very readable language with clear non-verbose syntax Tip: Two variables a and b have been defined above. Note that one does not declare the type of a
variable before assigning its value. In C, conversely, one should write:

12 2.1. First steps 13


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

int a = 3; >>> 7 * 3.
21.0
In addition, the type of a variable may change, in the sense that at one point in time it can be equal >>> 2**10
to a value of a certain type, and a second point in time, it can be equal to a value of a different type. 1024
b was first equal to an integer, but it became equal to a string when it was assigned the value ‘hello’. >>> 8 % 3
Operations on integers (b=2*a) are coded natively in Python, and so are some operations on strings such 2
as additions and multiplications, which amount respectively to concatenation and repetition.
Type conversion (casting):

>>> float(1)
1.0

2.2 Basic types


2.2.2 Containers
2.2.1 Numerical types
Tip: Python provides many efficient types of containers, in which collections of objects can be stored.
Tip: Python supports the following numerical, scalar types:

Integer Lists

>>> 1 + 1
2 Tip: A list is an ordered collection of objects, that may have different types. For example:
>>> a = 4
>>> type(a)
<class 'int'> >>> colors = ['red', 'blue', 'green', 'black', 'white']
>>> type(colors)
Floats <class 'list'>

>>> c = 2.1 Indexing: accessing individual objects contained in the list:


>>> type(c)
<class 'float'> >>> colors[2]
'green'
Complex
Counting from the end with negative indices:
>>> a = 1.5 + 0.5j
>>> a.real >>> colors[-1]
1.5 'white'
>>> a.imag >>> colors[-2]
0.5 'black'
>>> type(1. + 0j)
<class 'complex'>
Warning: Indexing starts at 0 (as in C), not at 1 (as in Fortran or Matlab)!
Booleans

>>> 3 > 4 Slicing: obtaining sublists of regularly-spaced elements:


False
>>> test = (3 > 4) >>> colors
>>> test ['red', 'blue', 'green', 'black', 'white']
False >>> colors[2:4]
>>> type(test) ['green', 'black']
<class 'bool'>

Warning: Note that colors[start:stop] contains the elements with indices i such as start<=
Tip: A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations i < stop (i ranging from start to stop-1). Therefore, colors[start:stop] has (stop - start)
+, -, *, /, % (modulo) natively implemented elements.

2.2. Basic types 14 2.2. Basic types 15


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Slicing syntax: colors[start:stop:stride] (continued from previous page)


>>> colors
Tip: All slicing parameters are optional: ['red', 'blue', 'green', 'black', 'white']

>>> colors Reverse:


['red', 'blue', 'green', 'black', 'white']
>>> colors[3:] >>> rcolors = colors[::-1]
['black', 'white'] >>> rcolors
>>> colors[:3] ['white', 'black', 'green', 'blue', 'red']
['red', 'blue', 'green'] >>> rcolors2 = list(colors) # new object that is a copy of colors in a different␣
>>> colors[::2] ˓→memory area

['red', 'green', 'white'] >>> rcolors2


['red', 'blue', 'green', 'black', 'white']
>>> rcolors2.reverse() # in-place; reversing rcolors2 does not affect colors
Lists are mutable objects and can be modified: >>> rcolors2
['white', 'black', 'green', 'blue', 'red']
>>> colors[0] = 'yellow'
>>> colors Concatenate and repeat lists:
['yellow', 'blue', 'green', 'black', 'white']
>>> colors[2:4] = ['gray', 'purple'] >>> rcolors + colors
>>> colors ['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white']
['yellow', 'blue', 'gray', 'purple', 'white'] >>> rcolors * 2
['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red']

Note: The elements of a list may have different types:


Tip: Sort:
>>> colors = [3, -200, 'hello']
>>> colors >>> sorted(rcolors) # new object
[3, -200, 'hello'] ['black', 'blue', 'green', 'red', 'white']
>>> colors[1], colors[2] >>> rcolors
(-200, 'hello') ['white', 'black', 'green', 'blue', 'red']
>>> rcolors.sort() # in-place
>>> rcolors
Tip: For collections of numerical data that all have the same type, it is often more efficient to use the ['black', 'blue', 'green', 'red', 'white']
array type provided by the numpy module. A NumPy array is a chunk of memory containing fixed-sized
items. With NumPy arrays, operations on elements can be faster because elements are regularly spaced
in memory and more operations are performed through specialized C functions instead of Python loops.
Methods and Object-Oriented Programming

The notation rcolors.method() (e.g. rcolors.append(3) and colors.pop()) is our first example
of object-oriented programming (OOP). Being a list, the object rcolors owns the method function
Tip: Python offers a large panel of functions to modify lists, or query them. Here are a few examples;
that is called using the notation .. No further knowledge of OOP than understanding the notation .
for more details, see https://docs.python.org/3/tutorial/datastructures.html#more-on-lists
is necessary for going through this tutorial.

Add and remove elements:

>>> colors = ['red', 'blue', 'green', 'black', 'white'] Discovering methods:


>>> colors.append('pink')
>>> colors Reminder: in Ipython: tab-completion (press tab)
['red', 'blue', 'green', 'black', 'white', 'pink'] In [1]: rcolors.<TAB>
>>> colors.pop() # removes and returns the last item append() count() insert() reverse()
'pink' clear() extend() pop() sort()
>>> colors copy() index() remove()
['red', 'blue', 'green', 'black', 'white']
>>> colors.extend(['pink', 'purple']) # extend colors, in-place
>>> colors
['red', 'blue', 'green', 'black', 'white', 'pink', 'purple']
>>> colors = colors[:-2]
(continues on next page)

2.2. Basic types 16 2.2. Basic types 17


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Strings
In [3]: a = "hello, world!"
Different string syntaxes (simple, double or triple quotes):
In [4]: a.replace('l', 'z', 1)
s = 'Hello, how are you?' Out[4]: 'hezlo, world!'
s = "Hi, what's up"
s = '''Hello,
how are you''' # tripling the quotes allows the Tip: Strings have many useful methods, such as a.replace as seen above. Remember the a. object-
# string to span more than one line oriented notation and use tab completion or help(str) to search for new methods.
s = """Hi,
what's up?""" See also:
Python offers advanced possibilities for manipulating strings, looking for patterns or formatting. The
In [2]: 'Hi, what's up?'
interested reader is referred to https://docs.python.org/3/library/stdtypes.html#string-methods and
Cell In[2], line 1
https://docs.python.org/3/library/string.html#format-string-syntax
'Hi, what's up?'
^ String formatting:
SyntaxError: unterminated string literal (detected at line 1)
>>> 'An integer: %i ; a float: %f ; another string: %s ' % (1, 0.1, 'string') # with␣
˓→more values use tuple after %
This syntax error can be avoided by enclosing the string in double quotes instead of single quotes.
Alternatively, one can prepend a backslash to the second single quote. Other uses of the backslash are, 'An integer: 1; a float: 0.100000; another string: string'
e.g., the newline character \n and the tab character \t.
>>> i = 102
>>> filename = 'processing_of_dataset_%d .txt' % i # no need for tuples with just␣
Tip: Strings are collections like lists. Hence they can be indexed and sliced, using the same syntax and ˓→one value after %

rules. >>> filename


'processing_of_dataset_102.txt'
Indexing:

>>> a = "hello" Dictionaries


>>> a[0]
'h'
>>> a[1] Tip: A dictionary is basically an efficient table that maps keys to values.
'e'
>>> a[-1]
'o' >>> tel = {'emmanuelle': 5752, 'sebastian': 5578}
>>> tel['francis'] = 5915
>>> tel
Tip: (Remember that negative indices correspond to counting from the right end.) {'emmanuelle': 5752, 'sebastian': 5578, 'francis': 5915}
>>> tel['sebastian']
5578
Slicing: >>> tel.keys()
>>> a = "hello, world!" dict_keys(['emmanuelle', 'sebastian', 'francis'])
>>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5 >>> tel.values()
'lo,' dict_values([5752, 5578, 5915])
>>> a[2:10:2] # Syntax: a[start:stop:step] >>> 'francis' in tel
'lo o' True
>>> a[::3] # every three characters, from beginning to end
'hl r!'
Tip: It can be used to conveniently store and retrieve values associated with a name (a string for a
date, a name, etc.). See https://docs.python.org/3/tutorial/datastructures.html#dictionaries for more
Tip: Accents and special characters can also be handled as in Python 3 strings consist of Unicode information.
characters. A dictionary can have keys (resp. values) with different types:

>>> d = {'a':1, 'b':2, 3:'hello'}


A string is an immutable object and it is not possible to modify its contents. One may however create >>> d
new strings from the original one. {'a': 1, 'b': 2, 3: 'hello'}

2.2. Basic types 18 2.2. Basic types 19


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

More container types 2.3 Control Flow


Tuples
Controls the order in which the code is executed.
Tuples are basically immutable lists. The elements of a tuple are written between parentheses, or just
separated by commas:
2.3.1 if/elif/else
>>> t = 12345, 54321, 'hello!'
>>> t[0]
>>> if 2**2 == 4:
12345
... print("Obvious!")
>>> t
...
(12345, 54321, 'hello!')
Obvious!
>>> u = (0, 2)
Blocks are delimited by indentation
Sets: unordered, unique items:

>>> s = set(('a', 'b', 'c', 'a')) Tip: Type the following lines in your Python interpreter, and be careful to respect the indentation
>>> s depth. The Ipython shell automatically increases the indentation depth after a colon : sign; to decrease
{'a', 'b', 'c'} the indentation depth, go four spaces to the left with the Backspace key. Press the Enter key twice to
>>> s.difference(('a', 'b')) leave the logical block.
{'c'}

>>> a = 10
2.2.3 Assignment operator
>>> if a == 1:
... print(1)
... elif a == 2:
Tip: Python library reference says:
... print(2)
Assignment statements are used to (re)bind names to values and to modify attributes or ... else:
items of mutable objects. ... print("A lot")
...
In short, it works as follows (simple assignment):
A lot
1. an expression on the right hand side is evaluated, the corresponding object is created/obtained
2. a name on the left hand side is assigned, or bound, to the r.h.s. object Indentation is compulsory in scripts as well. As an exercise, re-type the previous lines with the same
indentation in a script condition.py, and execute the script with run condition.py in Ipython.

Things to note:
2.3.2 for/range
• a single object can have several names bound to it:

In [5]: a = [1, 2, 3] Iterating with an index:

>>> for i in range(4):


• to change a list in place, use indexing/slices: ... print(i)
In [6]: a = [1, 2, 3] 0
1
2
• the key concept here is mutable vs. immutable
3
– mutable objects can be changed in place
– immutable objects cannot be modified once created But most often, it is more readable to iterate over values:

See also: >>> for word in ('cool', 'powerful', 'readable'):


... print('Python is %s ' % word)
A very good and detailed explanation of the above issues can be found in David M. Beazley’s article Python is cool
Types and Objects in Python. Python is powerful
Python is readable

2.2. Basic types 20 2.3. Control Flow 21


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

2.3.3 while/break/continue (continued from previous page)


>>> a is b
Typical C-style while loop (Mandelbrot problem): False
>>> z = 1 + 1j
>>> a = 1
>>> while abs(z) < 100:
>>> b = 1
... z = z**2 + 1
>>> a is b
>>> z
True
(-134+352j)
a in b
More advanced features
For any collection b: b contains a
break out of enclosing for/while loop:
>>> b = [1, 2, 3]
>>> z = 1 + 1j >>> 2 in b
True
>>> while abs(z) < 100: >>> 5 in b
... if z.imag == 0: False
... break
... z = z**2 + 1 If b is a dictionary, this tests that a is a key of b.

continue the next iteration of a loop.:


2.3.5 Advanced iteration
>>> a = [1, 0, 2, 4]
>>> for element in a: Iterate over any sequence
... if element == 0:
... continue You can iterate over any sequence (string, list, keys in a dictionary, lines in a file, . . . ):
... print(1. / element)
1.0 >>> vowels = 'aeiouy'
0.5
0.25 >>> for i in 'powerful':
... if i in vowels:
... print(i)
2.3.4 Conditional Expressions o
e
u
if <OBJECT>
Evaluates to False: >>> message = "Hello how are you?"
• any number equal to zero (0, 0.0, 0+0j) >>> message.split() # returns a list
['Hello', 'how', 'are', 'you?']
• an empty container (list, tuple, set, dictionary, . . . ) >>> for word in message.split():
• False, None ... print(word)
...
Evaluates to True: Hello
• everything else how
are
a == b you?
Tests equality, with logics:

>>> 1 == 1.
True Tip: Few languages (in particular, languages for scientific computing) allow to loop over anything but
integers/indices. With Python it is possible to loop exactly over the objects of interest without bothering
a is b with indices you often don’t care about. This feature can often be used to make code more readable.
Tests identity: both sides are the same object:

>>> a = 1
>>> b = 1. Warning: Not safe to modify the sequence you are iterating over.
>>> a == b
True
(continues on next page)

2.3. Control Flow 22 2.3. Control Flow 23


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Keeping track of enumeration number 2.4 Defining functions


Common task is to iterate over a sequence while keeping track of the item number.
2.4.1 Function definition
• Could use while loop with a counter as above. Or a for loop:

>>> words = ('cool', 'powerful', 'readable') In [1]: def test():


>>> for i in range(0, len(words)): ...: print('in test function')
... print((i, words[i])) ...:
(0, 'cool') ...:
(1, 'powerful')
(2, 'readable') In [2]: test()
in test function
• But, Python provides a built-in function - enumerate - for this:

>>> for index, item in enumerate(words): Warning: Function blocks must be indented as other control-flow blocks.
... print((index, item))
(0, 'cool')
(1, 'powerful')
(2, 'readable') 2.4.2 Return statement

Functions can optionally return values.


Looping over a dictionary In [3]: def disk_area(radius):
...: return 3.14 * radius * radius
Use items: ...:
>>> d = {'a': 1, 'b':1.2, 'c':1j}
In [4]: disk_area(1.5)
>>> for key, val in sorted(d.items()): Out[4]: 7.0649999999999995
... print('Key: %s has value: %s ' % (key, val))
Key: a has value: 1
Key: b has value: 1.2 Note: By default, functions return None.
Key: c has value: 1j

Note: Note the syntax to define a function:


Note: The ordering of a dictionary is random, thus we use sorted() which will sort on the keys.
• the def keyword;
• is followed by the function’s name, then

2.3.6 List Comprehensions • the arguments of the function are given between parentheses followed by a colon.
• the function body;
Instead of creating a list by means of a loop, one can make use of a list comprehension with a rather
self-explaining syntax. • and return object for optionally returning values.

>>> [i**2 for i in range(4)]


[0, 1, 4, 9]
2.4.3 Parameters

Mandatory parameters (positional arguments)


Exercise In [5]: def double_it(x):
...: return x * 2
Compute the decimals of Pi using the Wallis formula: ...:

4𝑖2
In [6]: double_it(3)
∏︁
𝜋=2 2−1
𝑖=1
4𝑖 Out[6]: 6

In [7]: double_it()
---------------------------------------------------------------------------
(continues on next page)

2.3. Control Flow 24 2.4. Defining functions 25


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


TypeError Traceback (most recent call last) Tip: More involved example implementing python’s slicing:
Cell In[7], line 1
In [20]: def slicer(seq, start=None, stop=None, step=None):
----> 1 double_it()
....: """Implement basic python slicing."""
....: return seq[start:stop:step]
TypeError: double_it() missing 1 required positional argument: 'x'
....:
Optional parameters (keyword or named arguments) In [21]: rhyme = 'one fish, two fish, red fish, blue fish'.split()
In [8]: def double_it(x=2):
...: return x * 2 In [22]: rhyme
...: Out[22]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [9]: double_it() In [23]: slicer(rhyme)


Out[9]: 4 Out[23]: ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish']

In [10]: double_it(3) In [24]: slicer(rhyme, step=2)


Out[10]: 6 Out[24]: ['one', 'two', 'red', 'blue']

In [25]: slicer(rhyme, 1, step=2)


Keyword arguments allow you to specify default values.
Out[25]: ['fish,', 'fish,', 'fish,', 'fish']

Warning: Default values are evaluated when the function is defined, not when it is called. This In [26]: slicer(rhyme, start=1, stop=4, step=2)
can be problematic when using mutable types (e.g. dictionary or list) and modifying them in the Out[26]: ['fish,', 'fish,']
function body, since the modifications will be persistent across invocations of the function.
The order of the keyword arguments does not matter:
Using an immutable type in a keyword argument:
In [11]: bigx = 10 In [27]: slicer(rhyme, step=2, start=1, stop=4)
Out[27]: ['fish,', 'fish,']
In [12]: def double_it(x=bigx):
....: return x * 2 but it is good practice to use the same ordering as the function’s definition.
....:
Keyword arguments are a very convenient feature for defining functions with a variable number of argu-
In [13]: bigx = 1e9 # Now really big ments, especially when default values are to be used in most calls to the function.

In [14]: double_it()
Out[14]: 20 2.4.4 Passing by value
Using an mutable type in a keyword argument (and modifying it inside the function body):
In [15]: def add_to_dict(args={'a': 1, 'b': 2}): Tip: Can you modify the value of a variable inside a function? Most languages (C, Java, . . . ) distinguish
....: for i in args.keys(): “passing by value” and “passing by reference”. In Python, such a distinction is somewhat artificial, and
....: args[i] += 1 it is a bit subtle whether your variables are going to be modified or not. Fortunately, there exist clear
....: print(args) rules.
....: Parameters to functions are references to objects, which are passed by value. When you pass a variable
to a function, python passes the reference to the object to which the variable refers (the value). Not the
In [16]: add_to_dict variable itself.
Out[16]: <function __main__.add_to_dict(args={'a': 1, 'b': 2})>

In [17]: add_to_dict() If the value passed in a function is immutable, the function does not modify the caller’s variable. If the
{'a': 2, 'b': 3} value is mutable, the function may modify the caller’s variable in-place:
>>> def try_to_modify(x, y, z):
In [18]: add_to_dict() ... x = 23
{'a': 3, 'b': 4} ... y.append(42)
... z = [99] # new reference
In [19]: add_to_dict() ... print(x)
{'a': 4, 'b': 5} ... print(y)
... print(z)
(continues on next page)

2.4. Defining functions 26 2.4. Defining functions 27


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


...
>>> a = 77 # immutable variable In [35]: setx(10)
>>> b = [99] # mutable variable x is 10
>>> c = [28]
>>> try_to_modify(a, b, c) In [36]: x
23 Out[36]: 10
[99, 42]
[99]
>>> print(a) 2.4.6 Variable number of parameters
77
>>> print(b)
[99, 42] Special forms of parameters:
>>> print(c) • *args: any number of positional arguments packed into a tuple
[28]
• **kwargs: any number of keyword arguments packed into a dictionary
Functions have a local variable table called a local namespace. In [37]: def variable_args(*args, **kwargs):
The variable x only exists within the function try_to_modify. ....: print('args is', args)
....: print('kwargs is', kwargs)
....:
2.4.5 Global variables
In [38]: variable_args('one', 'two', x=1, y=2, z=3)
Variables declared outside the function can be referenced within the function: args is ('one', 'two')
kwargs is {'x': 1, 'y': 2, 'z': 3}
In [28]: x = 5

In [29]: def addx(y):


....: return x + y 2.4.7 Docstrings
....:
Documentation about what the function does and its parameters. General convention:
In [30]: addx(10) In [39]: def funcname(params):
Out[30]: 15 ....: """Concise one-line sentence describing the function.
....:
But these “global” variables cannot be modified within the function, unless declared global in the ....: Extended summary which can contain multiple paragraphs.
function. ....: """
This doesn’t work: ....: # function body
....: pass
In [31]: def setx(y): ....:
....: x = y
....: print('x is %d ' % x) In [40]: funcname?
....: Signature: funcname(params)
....: Docstring:
Concise one-line sentence describing the function.
In [32]: setx(10) Extended summary which can contain multiple paragraphs.
x is 10 File: ~/src/scientific-python-lectures/<ipython-input-13-64e466df6d64>
Type: function
In [33]: x
Out[33]: 5
Note: Docstring guidelines
This works:
For the sake of standardization, the Docstring Conventions webpage documents the semantics and con-
In [34]: def setx(y): ventions associated with Python docstrings.
....: global x
Also, the NumPy and SciPy modules have defined a precise standard for documenting scientific functions,
....: x = y
that you may want to follow for your own functions, with a Parameters section, an Examples section,
....: print('x is %d ' % x)
etc. See https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard
....:
....:
(continues on next page)

2.4. Defining functions 28 2.4. Defining functions 29


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

2.4.8 Functions are objects 2.5 Reusing code: scripts and modules
Functions are first-class objects, which means they can be:
For now, we have typed all instructions in the interpreter. For longer sets of instructions we need to
• assigned to a variable change track and write the code in text files (using a text editor), that we will call either scripts or
modules. Use your favorite text editor (provided it offers syntax highlighting for Python), or the editor
• an item in a list (or any collection)
that comes with the Scientific Python Suite you may be using.
• passed as an argument to another function.

In [41]: va = variable_args 2.5.1 Scripts


In [42]: va('three', x=1, y=2)
args is ('three',) Tip: Let us first write a script, that is a file with a sequence of instructions that are executed each
kwargs is {'x': 1, 'y': 2} time the script is called. Instructions may be e.g. copied-and-pasted from the interpreter (but take care
to respect indentation rules!).

2.4.9 Methods The extension for Python files is .py. Write or copy-and-paste the following lines in a file called test.py

Methods are functions attached to objects. You’ve seen these in our examples on lists, dictionaries, message = "Hello how are you?"
strings, etc. . . for word in message.split():
print(word)

2.4.10 Exercises
Tip: Let us now execute the script interactively, that is inside the Ipython interpreter. This is maybe
the most common use of scripts in scientific computing.
Exercise: Fibonacci sequence

Write a function that displays the n first terms of the Fibonacci sequence, defined by:
Note: in Ipython, the syntax to execute a script is %run script.py. For example,

⎨ 𝑈0 = 0
𝑈1 = 1
In [1]: %run test.py
𝑈𝑛+2 = 𝑈𝑛+1 + 𝑈𝑛

Hello
how
are
Exercise: Quicksort you?

Implement the quicksort algorithm, as defined by wikipedia In [2]: message


Out[2]: 'Hello how are you?'

function quicksort(array) The script has been executed. Moreover the variables defined in the script (such as message) are now
var list less, greater available inside the interpreter’s namespace.
if length(array) < 2
return array
select and remove a pivot value pivot from array Tip: Other interpreters also offer the possibility to execute scripts (e.g., execfile in the plain Python
for each x in array interpreter, etc.).
if x < pivot + 1 then append x to less
else append x to greater It is also possible In order to execute this script as a standalone program, by executing the script inside
return concatenate(quicksort(less), pivot, quicksort(greater)) a shell terminal (Linux/Mac console or cmd Windows console). For example, if we are in the same
directory as the test.py file, we can execute this in a console:

$ python test.py
Hello
how
are
you?

Tip: Standalone scripts may also take command-line arguments

2.4. Defining functions 30 2.5. Reusing code: scripts and modules 31


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

In file.py: (continued from previous page)


'.ICE-unix',
import sys
'profile_d2w42edv',
print(sys.argv)
'profile_4_zbphdf',
'profile_5ph4s0ch',
$ python file.py test arguments 'profile_b9bs2_r8',
['file.py', 'test', 'arguments'] 'profile_ymfgkezo',
'profile_ylf1yz9m',
'profile_ve9ftzec',
Warning: Don’t implement option parsing yourself. Use a dedicated module such as argparse. 'snap-private-tmp',
'profile_b0ttd81w',
'profile_t7xwqh0e',
'profile_vr_ay610',
'profile_559rgua5',
2.5.2 Importing objects from modules 'profile_rhdgkmkd',
'clr-debug-pipe-1604-14840-out',
In [3]: import os 'profile_7oh0cama',
'profile_m3uuj28r',
In [4]: os 'profile_4ks_neaw',
Out[4]: <module 'os' (frozen)> 'profile_7j1ejay_',
'profile_boh6o1ne',
In [5]: os.listdir('.') 'profile_zu2iczx7',
Out[5]: 'dotnet-diagnostic-1604-14840-socket',
['profile_ksttxb2h', 'profile_xk8a882k',
'.XIM-unix', 'www-data-temp-aspnet-0',
'profile_8jyd3wt0', 'profile_lmfhc2sg',
'systemd-private-547c90d23384455997d6600060dd5355-chrony.service-Cs0azH', 'profile_ub0d3066',
'profile_i8ku8_ln', 'profile_hqwvn7hn',
'profile_6c5_7yvi', 'profile_wie_xyqb',
'clr-debug-pipe-589-869-in', 'profile_akajxynt',
'profile_n4tf0uy4', 'profile_c91t6jqc',
'profile_7crnvcpm', 'dotnet-diagnostic-1621-15129-socket',
'profile_ecjb1ld9', 'profile_wihes686',
'profile_m13gl1fv', 'profile_tpdh8hx5',
'profile_1_590dye', '.X11-unix',
'profile_v_p76c0x', 'profile_3kvs0c7h',
'clr-debug-pipe-1621-15129-out', 'profile_jk9kmxtf',
'profile_lvwe1o1z', 'systemd-private-547c90d23384455997d6600060dd5355-systemd-logind.service-w050a8',
'profile_orrts951', 'systemd-private-547c90d23384455997d6600060dd5355-haveged.service-YT5gfq',
'profile_bziy8mt_', 'profile_b1nj99y9',
'profile_0u5120_y', 'profile_owlfwm6o',
'profile_tav_998d', 'profile__5ntcpq1',
'.font-unix', 'profile_xtdrih3r',
'dotnet-diagnostic-589-869-socket', 'clr-debug-pipe-1621-15129-in',
'clr-debug-pipe-589-869-out', 'profile_7klgdeg6',
'profile_ujz8liq0', 'profile_dckcrseq',
'profile_rqn3apk7', 'profile_yrvcipb_']
'profile_f3qz57ee',
'profile_v5h87_cl', And also:
'profile_g8aplujp',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-resolved.service-qwjgaC', In [6]: from os import listdir
'.Test-unix',
'profile_orda1vei', Importing shorthands:
'profile_zwgjajcz',
In [7]: import numpy as np
'clr-debug-pipe-1604-14840-in',
'profile_rd6ks_2m',
'profile_hsd6fbf4',
(continues on next page)

2.5. Reusing code: scripts and modules 32 2.5. Reusing code: scripts and modules 33
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Warning: In [8]: import demo

from os import * In [9]: demo.print_a()


a
This is called the star import and please, Do not use it
• Makes the code harder to read and understand: where do symbols come from? In [10]: demo.print_b()
b
• Makes it impossible to guess the functionality by the context and the name (hint: os.name is
the name of the OS), and to profit usefully from tab completion.
Importing the module gives access to its objects, using the module.object syntax. Don’t forget to put
• Restricts the variable names you can use: os.name might override name, or vise-versa. the module’s name before the object’s name, otherwise Python won’t recognize the instruction.
• Creates possible name clashes between modules. Introspection
• Makes the code impossible to statically check for undefined symbols. In [11]: demo?
Type: module
Base Class: <type 'module'>
Tip: Modules are thus a good way to organize code in a hierarchical way. Actually, all the scientific String Form: <module 'demo' from 'demo.py'>
computing tools we are going to use are modules: Namespace: Interactive
File: /home/varoquau/Projects/Python_talks/scipy_2009_tutorial/source/
>>> import numpy as np # data arrays ˓→demo.py

>>> np.linspace(0, 10, 6) Docstring:


array([ 0., 2., 4., 6., 8., 10.]) A demo module.
>>> import scipy as sp # scientific computing
In [12]: who
demo

In [13]: whos
2.5.3 Creating modules
Variable Type Data/Info
------------------------------
demo module <module 'demo' from 'demo.py'>
Tip: If we want to write larger and better organized programs (compared to simple scripts), where
some objects are defined, (variables, functions, classes) and that we want to reuse several times, we have
In [14]: dir(demo)
to create our own modules.
Out[14]:
['__builtins__',
Let us create a module demo contained in the file demo.py: '__doc__',
'__file__',
"A demo module." '__name__',
'__package__',
'c',
def print_b(): 'd',
"Prints b." 'print_a',
print("b") 'print_b']

In [15]: demo.<TAB>
def print_a(): demo.c demo.print_a demo.py
"Prints a." demo.d demo.print_b demo.pyc
print("a")
Importing objects from modules into the main namespace

c = 2 In [16]: from demo import print_a, print_b


d = 2
In [17]: whos
Variable Type Data/Info
Tip: In this file, we defined two functions print_a and print_b. Suppose we want to call the print_a --------------------------------
function from the interpreter. We could execute the file as a script, but since we just want to have access demo module <module 'demo' from 'demo.py'>
to the function print_a, we are rather going to import it as a module. The syntax is as follows. print_a function <function print_a at 0xb7421534>
print_b function <function print_b at 0xb74214c4>

(continues on next page)

2.5. Reusing code: scripts and modules 34 2.5. Reusing code: scripts and modules 35
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 2.5.5 Scripts or modules? How to organize your code
In [18]: print_a()
a
Note: Rule of thumb
• Sets of instructions that are called several times should be written inside functions for better code
Warning: Module caching reusability.
Modules are cached: if you modify demo.py and re-import it in the old session, you will • Functions (or other bits of code) that are called from several scripts should be written inside a
get the old one. module, so that only the module is imported in the different scripts (do not copy-and-paste your
functions in the different scripts!).
Solution:
In [10]: importlib.reload(demo)

How modules are found and imported

2.5.4 ‘__main__’ and module loading When the import mymodule statement is executed, the module mymodule is searched in a given list of
directories. This list includes a list of installation-dependent default path (e.g., /usr/lib64/python3.
11) as well as the list of directories specified by the environment variable PYTHONPATH.
Tip: Sometimes we want code to be executed when a module is run directly, but not when it is imported
The list of directories searched by Python is given by the sys.path variable
by another module. if __name__ == '__main__' allows us to check whether the module is being run
directly. In [22]: import sys

File demo2.py: In [23]: sys.path


Out[23]:
def print_b(): ['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
"Prints b." '/opt/hostedtoolcache/Python/3.11.9/x64/lib/python311.zip',
print("b") '/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/lib-dynload',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages']
def print_a():
"Prints a." Modules must be located in the search path, therefore you can:
print("a")
• write your own modules within directories already defined in the search path (e.g. $HOME/.venv/
lectures/lib64/python3.11/site-packages). You may use symbolic links (on Linux) to keep
the code somewhere else.
# print_b() runs on import
print_b() • modify the environment variable PYTHONPATH to include the directories containing the user-defined
modules.
if __name__ == "__main__":
# print_a() is only executed when the module is run directly.
Tip: On Linux/Unix, add the following line to a file read by the shell at startup (e.g. /etc/profile,
print_a()
.profile)
Importing it: export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules
In [19]: import demo2
On Windows, https://support.microsoft.com/kb/310519 explains how to handle environment vari-
b
ables.
In [20]: import demo2
• or modify the sys.path variable itself within a Python script.
Running it:

In [21]: %run demo2 Tip:


b
import sys
a
new_path = '/home/emma/user_defined_modules'
if new_path not in sys.path:
sys.path.append(new_path)

2.5. Reusing code: scripts and modules 36 2.5. Reusing code: scripts and modules 37
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

This method is not very robust, however, because it makes the code less portable (user-dependent 2.5.7 Good practices
path) and because you have to add the directory to your sys.path each time you want to import
from a module in this directory. • Use meaningful object names
• Indentation: no choice!
See also:
See https://docs.python.org/3/tutorial/modules.html for more information about modules. Tip: Indenting is compulsory in Python! Every command block following a colon bears an
additional indentation level with respect to the previous line with a colon. One must therefore
indent after def f(): or while:. At the end of such logical blocks, one decreases the indentation
2.5.6 Packages depth (and re-increases it if a new block is entered, etc.)

A directory that contains many modules is called a package. A package is a module with submodules Strict respect of indentation is the price to pay for getting rid of { or ; characters that delineate
(which can have submodules themselves, etc.). A special file called __init__.py (which may be empty) logical blocks in other languages. Improper indentation leads to errors such as
tells Python that the directory is a Python package, from which modules can be imported. ------------------------------------------------------------
$ ls IndentationError: unexpected indent (test.py, line 2)
_build_utils/ fft/ _lib/ odr/ spatial/
cluster/ fftpack/ linalg/ optimize/ special/ All this indentation business can be a bit confusing in the beginning. However, with the clear
conftest.py __init__.py linalg.pxd optimize.pxd special.pxd indentation, and in the absence of extra characters, the resulting code is very nice to read compared
constants/ integrate/ meson.build setup.py stats/ to other languages.
datasets/ interpolate/ misc/ signal/
_distributor_init.py io/ ndimage/ sparse/ • Indentation depth: Inside your text editor, you may choose to indent with any positive number
$ cd ndimage of spaces (1, 2, 3, 4, . . . ). However, it is considered good practice to indent with 4 spaces. You
$ ls may configure your editor to map the Tab key to a 4-space indentation.
_filters.py __init__.py _measurements.py morphology.py src/
filters.py _interpolation.py measurements.py _ni_docstrings.py tests/ • Style guidelines
_fourier.py interpolation.py meson.build _ni_support.py utils/ Long lines: you should not write very long lines that span over more than (e.g.) 80 characters.
fourier.py LICENSE.txt _morphology.py setup.py Long lines can be broken with the \ character

From Ipython: >>> long_line = "Here is a very very long line \


... that we break in two parts."
In [24]: import scipy as sp
Spaces
In [25]: sp.__file__
Out[25]: '/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/scipy/__ Write well-spaced code: put whitespaces after commas, around arithmetic operators, etc.:
˓→init__.py'
>>> a = 1 # yes
>>> a=1 # too cramped
In [26]: sp.version.version
Out[26]: '1.13.1'
A certain number of rules for writing “beautiful” code (and more importantly using the same
conventions as anybody else!) are given in the Style Guide for Python Code.
In [27]: sp.ndimage.morphology.binary_dilation?
Signature:
sp.ndimage.morphology.binary_dilation(
input, Quick read
structure=None,
iterations=1, If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you
mask=None, can directly skip to the next chapter: NumPy: creating and manipulating numerical data.
output=None,
border_value=0, The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
origin=0, come back and finish this chapter later.
brute_force=False,
)
Docstring:
Multidimensional binary dilation with the given structuring element.
...

2.5. Reusing code: scripts and modules 38 2.5. Reusing code: scripts and modules 39
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

2.6 Input and Output 2.7 Standard Library

To be exhaustive, here are some information about input and output in Python. Since we will use the
NumPy methods to read and write files, you may skip this chapter at first reading. Note: Reference document for this section:
We write or read strings to/from files (other types must be converted to strings). To write in a file: • The Python Standard Library documentation: https://docs.python.org/3/library/index.html

>>> f = open('workfile', 'w') # opens the workfile file • Python Essential Reference, David Beazley, Addison-Wesley Professional
>>> type(f)
<class '_io.TextIOWrapper'>
>>> f.write('This is a test \nand another test')
2.7.1 os module: operating system functionality
>>> f.close()
“A portable way of using operating system dependent functionality.”
To read from a file

In [1]: f = open('workfile', 'r') Directory and file manipulation

In [2]: s = f.read() Current directory:

In [3]: print(s) In [1]: import os


This is a test
and another test In [2]: os.getcwd()
Out[2]: '/tmp'
In [4]: f.close()
List a directory:
See also:
In [3]: os.listdir(os.curdir)
For more details: https://docs.python.org/3/tutorial/inputoutput.html Out[3]:
['profile_ksttxb2h',
'profile_crwqcy2d',
2.6.1 Iterating over a file '.XIM-unix',
'profile_8jyd3wt0',
In [5]: f = open('workfile', 'r') 'systemd-private-547c90d23384455997d6600060dd5355-chrony.service-Cs0azH',
'profile_i8ku8_ln',
In [6]: for line in f: 'profile_6c5_7yvi',
...: print(line) 'clr-debug-pipe-589-869-in',
...: 'profile_n4tf0uy4',
This is a test 'profile_rwsw_k2b',
and another test 'profile_7crnvcpm',
'profile_ecjb1ld9',
In [7]: f.close() 'profile_m13gl1fv',
'profile_1_590dye',
'profile_v_p76c0x',
File modes 'clr-debug-pipe-1621-15129-out',
'profile_lvwe1o1z',
• Read-only: r 'profile_orrts951',
'profile_bziy8mt_',
• Write-only: w 'profile_0u5120_y',
– Note: Create a new file or overwrite existing file. 'profile_tav_998d',
'.font-unix',
• Append a file: a 'dotnet-diagnostic-589-869-socket',
• Read and Write: r+ 'clr-debug-pipe-589-869-out',
'profile_ujz8liq0',
• Binary mode: b 'profile_rqn3apk7',
– Note: Use for binary files, especially on Windows. 'profile_f3qz57ee',
'profile_v5h87_cl',
'profile_g8aplujp',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-resolved.service-qwjgaC',
(continues on next page)

2.6. Input and Output 40 2.7. Standard Library 41


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


'profile_1fx2p0i0', 'clr-debug-pipe-1621-15129-in',
'.Test-unix', 'profile_7klgdeg6',
'profile_orda1vei', 'profile_dckcrseq',
'profile_63ekqtw4', 'profile_yrvcipb_',
'profile_zwgjajcz', 'profile_ho2189dy']
'clr-debug-pipe-1604-14840-in',
'profile_rd6ks_2m', Make a directory:
'profile_hsd6fbf4',
'.ICE-unix', In [4]: os.mkdir('junkdir')
'profile_peh59e70',
'profile_d2w42edv', In [5]: 'junkdir' in os.listdir(os.curdir)
'profile_4_zbphdf', Out[5]: True
'profile_s35fv1zi',
'profile_5ph4s0ch', Rename the directory:
'profile_b9bs2_r8',
In [6]: os.rename('junkdir', 'foodir')
'profile_ymfgkezo',
'profile_ylf1yz9m',
In [7]: 'junkdir' in os.listdir(os.curdir)
'profile_ve9ftzec',
Out[7]: False
'snap-private-tmp',
'profile_b0ttd81w',
In [8]: 'foodir' in os.listdir(os.curdir)
'profile_t7xwqh0e',
Out[8]: True
'profile_vr_ay610',
'profile_559rgua5',
In [9]: os.rmdir('foodir')
'profile_rhdgkmkd',
'clr-debug-pipe-1604-14840-out',
In [10]: 'foodir' in os.listdir(os.curdir)
'profile_7oh0cama',
Out[10]: False
'profile_m3uuj28r',
'profile_4ks_neaw',
Delete a file:
'profile_2yyxi31b',
'profile_7j1ejay_', In [11]: fp = open('junk.txt', 'w')
'profile_boh6o1ne',
'profile_nz20vb7_', In [12]: fp.close()
'profile_zu2iczx7',
'dotnet-diagnostic-1604-14840-socket', In [13]: 'junk.txt' in os.listdir(os.curdir)
'profile_xk8a882k', Out[13]: True
'profile_l6786qpx',
'www-data-temp-aspnet-0', In [14]: os.remove('junk.txt')
'profile_lmfhc2sg',
'profile_ub0d3066', In [15]: 'junk.txt' in os.listdir(os.curdir)
'profile_hqwvn7hn', Out[15]: False
'profile_wie_xyqb',
'profile_akajxynt',
'profile_c91t6jqc',
os.path: path manipulations
'dotnet-diagnostic-1621-15129-socket',
'profile_wihes686',
os.path provides common operations on pathnames.
'profile_j7p1hjid',
'profile_tpdh8hx5', In [16]: fp = open('junk.txt', 'w')
'.X11-unix',
'profile_3kvs0c7h', In [17]: fp.close()
'profile_jk9kmxtf',
'systemd-private-547c90d23384455997d6600060dd5355-systemd-logind.service-w050a8', In [18]: a = os.path.abspath('junk.txt')
'systemd-private-547c90d23384455997d6600060dd5355-haveged.service-YT5gfq',
'profile_b1nj99y9', In [19]: a
'profile_owlfwm6o', Out[19]: '/tmp/junk.txt'
'profile__5ntcpq1',
'profile_xtdrih3r', In [20]: os.path.split(a)
(continues on next page) (continues on next page)

2.7. Standard Library 42 2.7. Standard Library 43


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Walking a directory


Out[20]: ('/tmp', 'junk.txt')
os.path.walk generates a list of filenames in a directory tree.
In [21]: os.path.dirname(a)
In [33]: for dirpath, dirnames, filenames in os.walk(os.curdir):
Out[21]: '/tmp'
....: for fp in filenames:
....: print(os.path.abspath(fp))
In [22]: os.path.basename(a)
....:
Out[22]: 'junk.txt'
....:
/tmp/clr-debug-pipe-589-869-in
In [23]: os.path.splitext(os.path.basename(a))
/tmp/junk.txt
Out[23]: ('junk', '.txt')
/tmp/clr-debug-pipe-1621-15129-out
/tmp/dotnet-diagnostic-589-869-socket
In [24]: os.path.exists('junk.txt')
/tmp/clr-debug-pipe-589-869-out
Out[24]: True
/tmp/clr-debug-pipe-1604-14840-in
/tmp/clr-debug-pipe-1604-14840-out
In [25]: os.path.isfile('junk.txt')
/tmp/dotnet-diagnostic-1604-14840-socket
Out[25]: True
/tmp/dotnet-diagnostic-1621-15129-socket
/tmp/clr-debug-pipe-1621-15129-in
In [26]: os.path.isdir('junk.txt')
/tmp/README
Out[26]: False
/tmp/README
/tmp/README
In [27]: os.path.expanduser('~/local')
/tmp/README
Out[27]: '/home/runner/local'
/tmp/README
/tmp/README
In [28]: os.path.join(os.path.expanduser('~'), 'local', 'bin')
/tmp/README
Out[28]: '/home/runner/local/bin'
/tmp/README
/tmp/README
/tmp/README
Running an external command /tmp/README
/tmp/README
In [29]: os.system('ls') /tmp/README
Out[29]: 0 /tmp/README
/tmp/README
/tmp/README
Note: Alternative to os.system /tmp/README
/tmp/README
A noteworthy alternative to os.system is the sh module. Which provides much more convenient ways
/tmp/README
to obtain the output, error stream and exit code of the external command.
/tmp/README
In [30]: import sh /tmp/README
In [31]: com = sh.ls() /tmp/README
/tmp/README
In [31]: print(com) /tmp/README
basic_types.rst exceptions.rst oop.rst standard_library.rst /tmp/README
control_flow.rst first_steps.rst python_language.rst /tmp/README
demo2.py functions.rst python-logo.png /tmp/README
demo.py io.rst reusing_code.rst /tmp/README
/tmp/README
In [32]: type(com) /tmp/README
Out[32]: str /tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
/tmp/README
(continues on next page)

2.7. Standard Library 44 2.7. Standard Library 45


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 2.7.2 shutil: high-level file operations


/tmp/README
/tmp/README The shutil provides useful file operations:
/tmp/README • shutil.rmtree: Recursively delete a directory tree.
/tmp/README
/tmp/README • shutil.move: Recursively move a file or directory to another location.
/tmp/README • shutil.copy: Copy files or directories.
/tmp/README
/tmp/README
/tmp/README 2.7.3 glob: Pattern matching on files
/tmp/README
/tmp/README The glob module provides convenient file pattern matching.
/tmp/README
/tmp/README Find all files ending in .txt:
/tmp/README
In [36]: import glob
/tmp/README
/tmp/README
In [37]: glob.glob('*.txt')
/tmp/dhist
Out[37]: ['junk.txt']
/tmp/bookmarks
/tmp/README
/tmp/README
/tmp/README 2.7.4 sys module: system-specific information
/tmp/README
/tmp/README System-specific information related to the Python interpreter.
/tmp/README • Which version of python are you running and where is it installed:
/tmp/README
/tmp/README In [38]: import sys
/tmp/README
/tmp/README In [39]: sys.platform
/tmp/README Out[39]: 'linux'
/tmp/README
/tmp/README In [40]: sys.version
/tmp/README Out[40]: '3.11.9 (main, May 9 2024, 14:13:20) [GCC 11.4.0]'
/tmp/README
/tmp/README In [41]: sys.prefix
/tmp/README Out[41]: '/opt/hostedtoolcache/Python/3.11.9/x64'
/tmp/README
/tmp/README • List of command line arguments passed to a Python script:
/tmp/README
/tmp/README In [42]: sys.argv
/tmp/README Out[42]:
/tmp/README ['/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sphinx/__main__.
/tmp/README ˓→py',

'-b',
'latex',
Environment variables: '-d',
'build/doctrees',
'.',
In [34]: os.environ.keys()
'build/latex']
Out[34]: KeysView(environ({'SHELL': '/bin/bash', 'COLORTERM': 'truecolor', ...}))
sys.path is a list of strings that specifies the search path for modules. Initialized from PYTHONPATH:
In [35]: os.environ['SHELL']
Out[35]: '/bin/bash' In [43]: sys.path
Out[43]:
['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python311.zip',
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11',
(continues on next page)

2.7. Standard Library 46 2.7. Standard Library 47


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/lib-dynload', ---------------------------------------------------------------------------
'/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages'] TypeError Traceback (most recent call last)
Cell In[2], line 1
----> 1 1 + 'e'
2.7.5 pickle: easy persistence
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Useful to store arbitrary objects to a file. Not safe or fast!
In [3]: d = {1:1, 2:2}
In [44]: import pickle
In [4]: d[3]
In [45]: l = [1, None, 'Stan'] ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
In [46]: with open('test.pkl', 'wb') as file: Cell In[4], line 1
....: pickle.dump(l, file) ----> 1 d[3]
....:
KeyError: 3
In [47]: with open('test.pkl', 'rb') as file:
....: out = pickle.load(file) In [5]: l = [1, 2, 3]
....:
In [6]: l[4]
In [48]: out ---------------------------------------------------------------------------
Out[48]: [1, None, 'Stan'] IndexError Traceback (most recent call last)
Cell In[6], line 1
----> 1 l[4]
Exercise
IndexError: list index out of range
Write a program to search your PYTHONPATH for the module site.py.
In [7]: l.foobar
---------------------------------------------------------------------------
path_site AttributeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 l.foobar

AttributeError: 'list' object has no attribute 'foobar'


2.8 Exception handling in Python
As you can see, there are different types of exceptions for different errors.
It is likely that you have raised Exceptions if you have typed all the previous commands of the tutorial.
For example, you may have raised an exception if you entered a command with a typo.
2.8.2 Catching exceptions
Exceptions are raised by different kinds of errors arising when executing Python code. In your own code,
you may also catch errors, or define custom error types. You may want to look at the descriptions of the
the built-in Exceptions when looking for the right exception type. try/except

In [8]: while True:


2.8.1 Exceptions ...: try:
...: x = int(input('Please enter a number: '))
Exceptions are raised by errors in Python: ...: break
...: except ValueError:
In [1]: 1/0 ...: print('That was no valid number. Try again...')
--------------------------------------------------------------------------- ...:
ZeroDivisionError Traceback (most recent call last) Please enter a number: a
Cell In[1], line 1 That was no valid number. Try again...
----> 1 1/0 Please enter a number: 1

ZeroDivisionError: division by zero In [9]: x


Out[9]: 1
In [2]: 1 + 'e'
(continues on next page)

2.8. Exception handling in Python 48 2.8. Exception handling in Python 49


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

try/finally (continued from previous page)


OK, Gaël
In [10]: try: Out[16]: 'Gaël'
....: x = int(input('Please enter a number: '))
....: finally: In [17]: filter_name('Stéfan')
....: print('Thank you for your input') ---------------------------------------------------------------------------
....: UnicodeEncodeError Traceback (most recent call last)
Please enter a number: a Cell In[17], line 1
Thank you for your input ----> 1 filter_name('Stéfan')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last) Cell In[15], line 8, in filter_name(name)
Cell In[10], line 2 6 print('OK, Gaël')
1 try: 7 else:
----> 2 x = int(input('Please enter a number: ')) ----> 8 raise e
3 finally: 9 return name
4 print('Thank you for your input')
ValueError: invalid literal for int() with base 10: 'a' Cell In[15], line 3, in filter_name(name)
1 def filter_name(name):
Important for resource management (e.g. closing a file) 2 try:
----> 3 name = name.encode('ascii')
4 except UnicodeError as e:
Easier to ask for forgiveness than for permission 5 if name == 'Gaël':

In [11]: def print_sorted(collection): UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 2:␣
....: try: ˓→ordinal not in range(128)

....: collection.sort()
....: except AttributeError: • Exceptions to pass messages between parts of the code:
....: pass # The pass statement does nothing
....: print(collection) In [18]: def achilles_arrow(x):
....: ....: if abs(x - 1) < 1e-3:
....: raise StopIteration
In [12]: print_sorted([1, 3, 2]) ....: x = 1 - (1-x)/2.
[1, 2, 3] ....: return x
....:
In [13]: print_sorted(set((1, 3, 2)))
{1, 2, 3} In [19]: x = 0

In [14]: print_sorted('132') In [20]: while True:


132 ....: try:
....: x = achilles_arrow(x)
....: except StopIteration:
....: break
2.8.3 Raising exceptions ....:
....:
• Capturing and reraising an exception:

In [15]: def filter_name(name): In [21]: x


....: try: Out[21]: 0.9990234375
....: name = name.encode('ascii')
....: except UnicodeError as e: Use exceptions to notify certain conditions are met (e.g. StopIteration) or not (e.g. custom error raising)
....: if name == 'Gaël':
....: print('OK, Gaël')
....: else:
....: raise e
....: return name
....:

In [16]: filter_name('Gaël')
(continues on next page)

2.8. Exception handling in Python 50 2.8. Exception handling in Python 51


Scientific Python Lectures, Edition 2024.2rc0.dev0

2.9 Object-oriented programming (OOP)

Python supports object-oriented programming (OOP). The goals of OOP are:


• to organize the code, and
• to reuse code in similar contexts.
Here is a small example: we create a Student class, which is an object gathering several custom functions
(methods) and variables (attributes), we will be able to use:

>>>
...
...
...
...
class Student(object):
def __init__(self, name):
self.name = name
def set_age(self, age):
self.age = age
CHAPTER 3
... def set_major(self, major):
... self.major = major
...
>>> anna = Student('anna')
>>> anna.set_age(21)
>>> anna.set_major('physics')

In the previous example, the Student class has __init__, set_age and set_major methods. Its at-
NumPy: creating and manipulating
tributes are name, age and major. We can call these methods and attributes with the following notation:
classinstance.method or classinstance.attribute. The __init__ constructor is a special method
numerical data
we call with: MyClass(init parameters if any).
Now, suppose we want to create a new class MasterStudent with the same methods and attributes as
the previous one, but with an additional internship attribute. We won’t copy the previous class, but
inherit from it:

>>> class MasterStudent(Student):


... internship = 'mandatory, from March to June' Authors: Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen
...
>>> james = MasterStudent('james') This chapter gives an overview of NumPy, the core tool for performant numerical computing with Python.
>>> james.internship
'mandatory, from March to June'
>>> james.set_age(23)
>>> james.age
23 3.1 The NumPy array object

The MasterStudent class inherited from the Student attributes and methods.
Section contents
Thanks to classes and object-oriented programming, we can organize code with different classes corre-
sponding to different objects we encounter (an Experiment class, an Image class, a Flow class, etc.), with
• What are NumPy and NumPy arrays?
their own methods and attributes. Then we can use inheritance to consider variations around a base
class and reuse code. Ex : from a Flow base class, we can create derived StokesFlow, TurbulentFlow, • Creating arrays
PotentialFlow, etc.
• Basic data types
• Basic visualization
• Indexing and slicing
• Copies and views
• Fancy indexing

2.9. Object-oriented programming (OOP) 52 53


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3.1.1 What are NumPy and NumPy arrays? NumPy Reference documentation

NumPy arrays • On the web: https://numpy.org/doc/


• Interactive help:
Python objects
In [5]: np.array?
• high-level number objects: integers, floating point
Docstring:
• containers: lists (costless insertion and append), dictionaries (fast lookup) array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
like=None)
NumPy provides
• extension package to Python for multi-dimensional arrays Create an array.
• closer to hardware (efficiency)
Parameters
• designed for scientific computation (convenience) ----------
object : array_like
• Also known as array oriented computing
An array, any object exposing the array interface, an object whose
``__array__`` method returns an array, or any (nested) sequence.
If object is a scalar, a 0-dimensional array containing object is
returned.
dtype : data-type, optional
The desired data-type for the array. If not given, NumPy will try to use
>>> import numpy as np a default ``dtype`` that can represent the values (by applying promotion
>>> a = np.array([0, 1, 2, 3]) rules when necessary.)
>>> a copy : bool, optional
array([0, 1, 2, 3]) If true (default), then the object is copied. Otherwise, a copy will
only be made if ``__array__`` returns a copy, if obj is a nested
sequence, or if a copy is needed to satisfy any of the other
Tip: For example, An array containing: requirements (``dtype``, ``order``, etc.).
• values of an experiment/simulation at discrete time steps order : {'K', 'A', 'C', 'F'}, optional
Specify the memory layout of the array. If object is not an array, the
• signal recorded by a measurement device, e.g. sound wave newly created array will be in C order (row major) unless 'F' is
• pixels of an image, grey-level or colour specified, in which case it will be in Fortran order (column major).
If object is an array the following holds.
• 3-D data measured at different X-Y-Z positions, e.g. MRI scan
• ... ===== ========= ===================================================
order no copy copy=True
===== ========= ===================================================
Why it is useful: Memory-efficient container that provides fast numerical operations. 'K' unchanged F & C order preserved, otherwise most similar order
'A' unchanged F order if input is F and not C, otherwise C order
In [1]: L = range(1000)
'C' C order C order
'F' F order F order
In [2]: %timeit [i**2 for i in L]
===== ========= ===================================================
43.6 us +- 592 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each)
When ``copy=False`` and a copy is made for other reasons, the result is
In [3]: a = np.arange(1000)
the same as if ``copy=True``, with some exceptions for 'A', see the
Notes section. The default order is 'K'.
In [4]: %timeit a**2
subok : bool, optional
892 ns +- 1.46 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be prepended to the shape as
needed to meet this requirement.
like : array_like, optional
Reference object to allow the creation of arrays which are not
NumPy arrays. If an array-like passed in as ``like`` supports
the ``__array_function__`` protocol, the result will be defined
(continues on next page)

3.1. The NumPy array object 54 3.1. The NumPy array object 55
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


by it. In this case, it ensures the creation of an array object >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
compatible with that passed in via this argument. >>> x['a']
array([1, 3])
.. versionadded:: 1.20.0
Creating an array from sub-classes:
Returns
------- >>> np.array(np.mat('1 2; 3 4'))
out : ndarray array([[1, 2],
An array object satisfying the specified requirements. [3, 4]])

See Also >>> np.array(np.mat('1 2; 3 4'), subok=True)


-------- matrix([[1, 2],
empty_like : Return an empty array with shape and type of input. [3, 4]])
ones_like : Return an array of ones with shape and type of input. Type: builtin_function_or_method
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value. • Looking for something:
empty : Return a new uninitialized array.
ones : Return a new array setting values to one. >>> np.lookfor('create array')
zeros : Return a new array setting values to zero. Search results for 'create array'
full : Return a new array of given shape filled with value. ---------------------------------
numpy.array
Create an array.
Notes numpy.memmap
----- Create a memory-map to an array stored in a *binary* file on disk.
When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,
and a copy is forced by a change in dtype, then the order of the result is In [6]: np.con*?
not necessarily 'C' as expected. This is likely a bug. np.concatenate
np.conj
Examples np.conjugate
-------- np.convolve
>>> np.array([1, 2, 3])
array([1, 2, 3])
Import conventions
Upcasting:
The recommended convention to import NumPy is:
>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.]) >>> import numpy as np

More than one dimension:

>>> np.array([[1, 2], [3, 4]])


3.1.2 Creating arrays
array([[1, 2],
[3, 4]]) Manual construction of arrays

Minimum dimensions 2: • 1-D:

>>> a = np.array([0, 1, 2, 3])


>>> np.array([1, 2, 3], ndmin=2)
>>> a
array([[1, 2, 3]])
array([0, 1, 2, 3])
>>> a.ndim
Type provided:
1
>>> a.shape
>>> np.array([1, 2, 3], dtype=complex)
(4,)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
>>> len(a)
4
Data-type consisting of more than one element:
• 2-D, 3-D, . . . :
(continues on next page)

3.1. The NumPy array object 56 3.1. The NumPy array object 57
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array >>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple
>>> b >>> a
array([[0, 1, 2], array([[1., 1., 1.],
[3, 4, 5]]) [1., 1., 1.],
>>> b.ndim [1., 1., 1.]])
2 >>> b = np.zeros((2, 2))
>>> b.shape >>> b
(2, 3) array([[0., 0.],
>>> len(b) # returns the size of the first dimension [0., 0.]])
2 >>> c = np.eye(3)
>>> c
>>> c = np.array([[[1], [2]], [[3], [4]]]) array([[1., 0., 0.],
>>> c [0., 1., 0.],
array([[[1], [0., 0., 1.]])
[2]], >>> d = np.diag(np.array([1, 2, 3, 4]))
>>> d
[[3], array([[1, 0, 0, 0],
[4]]]) [0, 2, 0, 0],
>>> c.shape [0, 0, 3, 0],
(2, 2, 1) [0, 0, 0, 4]])

• np.random: random numbers (Mersenne Twister PRNG):


Exercise: Simple arrays
>>> rng = np.random.default_rng(27446968)
• Create a simple two dimensional array. First, redo the examples from above. And then create >>> a = rng.random(4) # uniform in [0, 1]
your own: how about odd numbers counting backwards on the first row, and even numbers on >>> a
the second? array([0.64613018, 0.48984931, 0.50851229, 0.22563948])

• Use the functions len(), numpy.shape() on these arrays. How do they relate to each other? >>> b = rng.standard_normal(4) # Gaussian
And to the ndim attribute of the arrays? >>> b
array([-0.38250769, -0.61536465, 0.98131732, 0.59353096])

Functions for creating arrays


Exercise: Creating arrays using functions

Tip: In practice, we rarely enter items one by one. . . • Experiment with arange, linspace, ones, zeros, eye and diag.
• Create different kinds of arrays with random numbers.
• Evenly spaced: • Try setting the seed before creating an array with random values.
>>> a = np.arange(10) # 0 .. n-1 (!) • Look at the function np.empty. What does it do? When might this be useful?
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.arange(1, 9, 2) # start, end (exclusive), step
>>> b 3.1.3 Basic data types
array([1, 3, 5, 7])
You may have noticed that, in some instances, array elements are displayed with a trailing dot (e.g. 2.
• or by number of points: vs 2). This is due to a difference in the data-type used:

>>> c = np.linspace(0, 1, 6) # start, end, num-points >>> a = np.array([1, 2, 3])


>>> c >>> a.dtype
array([0. , 0.2, 0.4, 0.6, 0.8, 1. ]) dtype('int64')
>>> d = np.linspace(0, 1, 5, endpoint=False)
>>> d >>> b = np.array([1., 2., 3.])
array([0. , 0.2, 0.4, 0.6, 0.8]) >>> b.dtype
dtype('float64')
• Common arrays:
Tip: Different data-types allow us to store data more compactly in memory, but most of the time we

3.1. The NumPy array object 58 3.1. The NumPy array object 59
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

simply work with floating point numbers. Note that, in the example above, NumPy auto-detects the
>>> %matplotlib
data-type from the input.
Or, from the notebook, enable plots in the notebook:

>>> %matplotlib inline


You can explicitly specify which data-type you want:
The inline is important for the notebook, so that plots are displayed in the notebook and not in a new
>>> c = np.array([1, 2, 3], dtype=float)
window.
>>> c.dtype
dtype('float64') Matplotlib is a 2D plotting package. We can import its functions as below:

The default data type is floating point: >>> import matplotlib.pyplot as plt # the tidy way

>>> a = np.ones((3, 3)) And then use (note that you have to use show explicitly if you have not enabled interactive plots with
>>> a.dtype %matplotlib):
dtype('float64')
>>> plt.plot(x, y) # line plot
There are also other types: >>> plt.show() # <-- shows the plot (not needed with interactive plots)

Complex Or, if you have enabled interactive plots with %matplotlib:


>>> d = np.array([1+2j, 3+4j, 5+6*1j]) >>> plt.plot(x, y) # line plot
>>> d.dtype
dtype('complex128') • 1D plotting:

Bool >>> x = np.linspace(0, 3, 20)


>>> y = np.linspace(0, 9, 20)
>>> e = np.array([True, False, False, True]) >>> plt.plot(x, y) # line plot
>>> e.dtype [<matplotlib.lines.Line2D object at ...>]
dtype('bool') >>> plt.plot(x, y, 'o') # dot plot
[<matplotlib.lines.Line2D object at ...>]
Strings

>>> f = np.array(['Bonjour', 'Hello', 'Hallo'])


>>> f.dtype # <--- strings containing max. 7 letters
dtype('<U7')

Much more
• int32
• int64
• uint32
• uint64
• 2D arrays (such as images):
3.1.4 Basic visualization >>> rng = np.random.default_rng(27446968)
>>> image = rng.random((30, 30))
Now that we have our first data arrays, we are going to visualize them. >>> plt.imshow(image, cmap=plt.cm.hot)
Start by launching IPython: <matplotlib.image.AxesImage object at ...>
>>> plt.colorbar()
$ ipython # or ipython3 depending on your install <matplotlib.colorbar.Colorbar object at ...>

Or the notebook:

$ jupyter notebook

Once IPython has started, enable interactive plots:

3.1. The NumPy array object 60 3.1. The NumPy array object 61
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


array([[ 0, 0, 0],
[ 0, 1, 0],
[ 0, 10, 2]])
>>> a[1]
array([0, 1, 0])

Note:
• In 2D, the first dimension corresponds to rows, the second to columns.
• for multidimensional a, a[0] is interpreted by taking all elements in the unspecified dimensions.

Slicing: Arrays, like other Python sequences can also be sliced:


See also:
>>> a = np.arange(10)
More in the: matplotlib chapter >>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Exercise: Simple visualizations >>> a[2:9:3] # [start:end:step]
array([2, 5, 8])
• Plot some simple arrays: a cosine as a function of time and a 2D matrix.
Note that the last index is not included! :
• Try using the gray colormap on the 2D matrix.
>>> a[:4]
array([0, 1, 2, 3])

3.1.5 Indexing and slicing All three slice components are not required: by default, start is 0, end is the last and step is 1:

The items of an array can be accessed and assigned to the same way as other Python sequences (e.g. >>> a[1:3]
lists): array([1, 2])
>>> a[::2]
>>> a = np.arange(10) array([0, 2, 4, 6, 8])
>>> a >>> a[3:]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) array([3, 4, 5, 6, 7, 8, 9])
>>> a[0], a[2], a[-1]
(0, 2, 9) A small illustrated summary of NumPy indexing and slicing. . .
>>> a[0, 3:5]
Warning: Indices begin at 0, like other Python sequences (and C/C++). In contrast, in Fortran array([3, 4]) 0 1 2 3 4 5
or Matlab, indices begin at 1.
>>> a[4:, 4:]
10 11 12 13 14 15
The usual python idiom for reversing a sequence is supported: array([[44, 55],
[54, 55]]) 20 21 22 23 24 25
>>> a[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) >>> a[:, 2]
30 31 32 33 34 35
a([2, 12, 22, 32, 42, 52])
For multidimensional arrays, indices are tuples of integers:
>>> a[2::2, ::2] 40 41 42 43 44 45
>>> a = np.diag(np.arange(3))
>>> a array([[20, 22, 24],
array([[0, 0, 0], 50 51 52 53 54 55
[40, 42, 44]])
[0, 1, 0],
[0, 0, 2]]) You can also combine assignment and slicing:
>>> a[1, 1]
1 >>> a = np.arange(10)
>>> a[2, 1] = 10 # third line, second column >>> a[5:] = 10
>>> a >>> a
(continues on next page) (continues on next page)

3.1. The NumPy array object 62 3.1. The NumPy array object 63
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 3.1.6 Copies and views


array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10])
>>> b = np.arange(5) A slicing operation creates a view on the original array, which is just a way of accessing array data.
>>> a[5:] = b[::-1] Thus the original array is not copied in memory. You can use np.may_share_memory() to check if two
>>> a arrays share the same memory block. Note however, that this uses heuristics and may give you false
array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0]) positives.
When modifying the view, the original array is modified as well:

Exercise: Indexing and slicing >>> a = np.arange(10)


>>> a
• Try the different flavours of slicing, using start, end and step: starting from a linspace, try to array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
obtain odd numbers counting backwards, and even numbers counting forwards. >>> b = a[::2]
>>> b
• Reproduce the slices in the diagram above. You may use the following expression to create the array([0, 2, 4, 6, 8])
array: >>> np.may_share_memory(a, b)
>>> np.arange(6) + np.arange(0, 51, 10)[:, np.newaxis] True
array([[ 0, 1, 2, 3, 4, 5], >>> b[0] = 12
[10, 11, 12, 13, 14, 15], >>> b
[20, 21, 22, 23, 24, 25], array([12, 2, 4, 6, 8])
[30, 31, 32, 33, 34, 35], >>> a # (!)
[40, 41, 42, 43, 44, 45], array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9])
[50, 51, 52, 53, 54, 55]])
>>> a = np.arange(10)
>>> c = a[::2].copy() # force a copy
>>> c[0] = 12
Exercise: Array creation >>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Create the following arrays (with correct data types):
>>> np.may_share_memory(a, c)
[[1, 1, 1, 1],
False
[1, 1, 1, 1],
[1, 1, 1, 2],
This behavior can be surprising at first sight. . . but it allows to save both memory and time.
[1, 6, 1, 1]]

[[0., 0., 0., 0., 0.], Worked example: Prime number sieve
[2., 0., 0., 0., 0.],
[0., 3., 0., 0., 0.],
[0., 0., 4., 0., 0.],
[0., 0., 0., 5., 0.],
[0., 0., 0., 0., 6.]]

Par on course: 3 statements for each


Hint: Individual array elements can be accessed similarly to a list, e.g. a[1] or a[1, 2].
Hint: Examine the docstring for diag.

Exercise: Tiling for array creation

Skim through the documentation for np.tile, and use this function to construct the array:
[[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1],
[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1]] Compute prime numbers in 0–99, with a sieve
• Construct a shape (100,) boolean array is_prime, filled with True in the beginning:
>>> is_prime = np.ones((100,), dtype=bool)

3.1. The NumPy array object 64 3.1. The NumPy array object 65
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Cross out 0 and 1 which are not primes: Indexing with an array of integers

>>> is_prime[:2] = 0
>>> a = np.arange(0, 100, 10)
• For each integer j starting from 2, cross out its higher multiples: >>> a
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
>>> N_max = int(np.sqrt(len(is_prime) - 1))
>>> for j in range(2, N_max + 1):
Indexing can be done with an array of integers, where the same index is repeated several time:
... is_prime[2*j::j] = False
>>> a[[2, 3, 2, 4, 2]] # note: [2, 3, 2, 4, 2] is a Python list
• Skim through help(np.nonzero), and print the prime numbers
array([20, 30, 20, 40, 20])
• Follow-up:
New values can be assigned with this kind of indexing:
– Move the above code into a script file named prime_sieve.py
– Run it to check it works >>> a[[9, 7]] = -100
>>> a
– Use the optimization suggested in the sieve of Eratosthenes: array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100])
1. Skip j which are already known to not be primes
2. The first number to cross out is 𝑗 2 Tip: When a new array is created by indexing with an array of integers, the new array has the same
shape as the array of integers:

>>> a = np.arange(10)
3.1.7 Fancy indexing >>> idx = np.array([[3, 4], [9, 7]])
>>> idx.shape
(2, 2)
Tip: NumPy arrays can be indexed with slices, but also with boolean or integer arrays (masks). This >>> a[idx]
method is called fancy indexing. It creates copies not views. array([[3, 4],
[9, 7]])

Using boolean masks

>>> rng = np.random.default_rng(27446968) The image below illustrates various fancy indexing applications
>>> a = rng.integers(0, 21, 15)
>>> a >>> a[(0,1,2,3,4), (1,2,3,4,5)]
array([ 3, 13, 12, 10, 10, 10, 18, 4, 8, 5, 6, 11, 12, 17, 3]) 0 1 2 3 4 5
array([1, 12, 23, 34, 45])
>>> (a % 3 == 0)
array([ True, False, True, False, False, False, True, False, False, 10 11 12 13 14 15
>>> a[3:, [0,2,5]]
False, True, False, True, False, True])
>>> mask = (a % 3 == 0) array([[30, 32, 35],
20 21 22 23 24 25
>>> extract_from_a = a[mask] # or, a[a%3==0] [40, 42, 45],
>>> extract_from_a # extract a sub-array with the mask [50, 52, 55]])
30 31 32 33 34 35
array([ 3, 12, 18, 6, 12, 3])
>>> mask = np.array([1,0,1,0,0,1], dtype=bool)
>>> a[mask, 2] 40 41 42 43 44 45
Indexing with a mask can be very useful to assign a new value to a sub-array:
array([2, 22, 52])
>>> a[a % 3 == 0] = -1 50 51 52 53 54 55
>>> a
array([-1, 13, -1, 10, 10, 10, -1, 4, 8, 5, -1, 11, -1, 17, -1])
Exercise: Fancy indexing

• Again, reproduce the fancy indexing shown in the diagram above.


• Use fancy indexing on the left and array creation on the right to assign values into an array, for
instance by setting parts of the array in the diagram above to zero.

3.1. The NumPy array object 66 3.1. The NumPy array object 67
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3.2 Numerical operations on arrays


Note: Matrix multiplication:

>>> c @ c
Section contents array([[3., 3., 3.],
[3., 3., 3.],
• Elementwise operations [3., 3., 3.]])
• Basic reductions
• Broadcasting
• Array shape manipulation Exercise: Elementwise operations

• Sorting data • Try simple arithmetic elementwise operations: add even elements with odd elements
• Summary • Time them against their pure python counterparts using %timeit.
• Generate:
– [2**0, 2**1, 2**2, 2**3, 2**4]
3.2.1 Elementwise operations
– a_j = 2^(3*j) - j
Basic operations

With scalars: Other operations


>>> a = np.array([1, 2, 3, 4])
>>> a + 1 Comparisons:
array([2, 3, 4, 5]) >>> a = np.array([1, 2, 3, 4])
>>> 2**a >>> b = np.array([4, 2, 2, 4])
array([ 2, 4, 8, 16]) >>> a == b
array([False, True, False, True])
All arithmetic operates elementwise: >>> a > b
array([False, False, True, False])
>>> b = np.ones(4) + 1
>>> a - b
array([-1., 0., 1., 2.])
Tip: Array-wise comparisons:
>>> a * b
array([2., 4., 6., 8.]) >>> a = np.array([1, 2, 3, 4])
>>> b = np.array([4, 2, 2, 4])
>>> j = np.arange(5) >>> c = np.array([1, 2, 3, 4])
>>> 2**(j + 1) - j >>> np.array_equal(a, b)
array([ 2, 3, 6, 13, 28]) False
>>> np.array_equal(a, c)
These operations are of course much faster than if you did them in pure python: True
>>> a = np.arange(10000)
>>> %timeit a + 1
Logical operations:
10000 loops, best of 3: 24.3 us per loop
>>> l = range(10000) >>> a = np.array([1, 1, 0, 0], dtype=bool)
>>> %timeit [i+1 for i in l] >>> b = np.array([1, 0, 1, 0], dtype=bool)
1000 loops, best of 3: 861 us per loop >>> np.logical_or(a, b)
array([ True, True, True, False])
>>> np.logical_and(a, b)
Warning: Array multiplication is not matrix multiplication: array([ True, False, False, False])
>>> c = np.ones((3, 3))
>>> c * c # NOT matrix multiplication! Transcendental functions:
array([[1., 1., 1.],
>>> a = np.arange(5)
[1., 1., 1.],
>>> np.sin(a)
[1., 1., 1.]])
array([ 0. , 0.84147098, 0.90929743, 0.14112001, -0.7568025 ])
(continues on next page)

3.2. Numerical operations on arrays 68 3.2. Numerical operations on arrays 69


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 3.2.2 Basic reductions


>>> np.exp(a)
array([ 1. , 2.71828183, 7.3890561 , 20.08553692, 54.59815003]) Computing sums
>>> np.log(np.exp(a))
array([0., 1., 2., 3., 4.]) >>> x = np.array([1, 2, 3, 4])
>>> np.sum(x)
Shape mismatches 10
>>> x.sum()
>>> a = np.arange(4)
10
>>> a + np.array([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (2,)

Broadcasting? We’ll return to that later.


Transposition:

>>> a = np.triu(np.ones((3, 3)), 1) # see help(np.triu)


>>> a
array([[0., 1., 1.],
[0., 0., 1.],
[0., 0., 0.]])
>>> a.T
array([[0., 0., 0.],
[1., 0., 0.],
[1., 1., 0.]])
Sum by rows and by columns:

Note: The transposition is a view >>> x = np.array([[1, 1], [2, 2]])


>>> x
The transpose returns a view of the original array: array([[1, 1],
[2, 2]])
>>> a = np.arange(9).reshape(3, 3)
>>> x.sum(axis=0) # columns (first dimension)
>>> a.T[0, 2] = 999
array([3, 3])
>>> a.T
>>> x[:, 0].sum(), x[:, 1].sum()
array([[ 0, 3, 999],
(3, 3)
[ 1, 4, 7],
>>> x.sum(axis=1) # rows (second dimension)
[ 2, 5, 8]])
array([2, 4])
>>> a
>>> x[0, :].sum(), x[1, :].sum()
array([[ 0, 1, 2],
(2, 4)
[ 3, 4, 5],
[999, 7, 8]])
Tip: Same idea in higher dimensions:

>>> rng = np.random.default_rng(27446968)


Note: Linear algebra >>> x = rng.random((2, 2, 2))
The sub-module numpy.linalg implements basic linear algebra, such as solving linear systems, singular >>> x.sum(axis=2)[0, 1]
value decomposition, etc. However, it is not guaranteed to be compiled using efficient routines, and thus 0.73415...
we recommend the use of scipy.linalg, as detailed in section Linear algebra operations: scipy.linalg >>> x[0, 1, :].sum()
0.73415...

Exercise other operations

• Look at the help for np.allclose. When might this be useful?


• Look at the help for np.triu and np.tril.

3.2. Numerical operations on arrays 70 3.2. Numerical operations on arrays 71


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Other reductions • Given there is a sum, what other function might you expect to see?

— works the same way (and take axis=) • What is the difference between sum and cumsum?

Extrema:

>>> x = np.array([1, 3, 2]) Worked Example: diffusion using a random walk algorithm
>>> x.min()
1
>>> x.max()
3

>>> x.argmin() # index of minimum Tip: Let us consider a simple 1D random walk process: at each time step a walker jumps right or
0 left with equal probability.
>>> x.argmax() # index of maximum We are interested in finding the typical distance from the origin of a random walker after t left or
1 right jumps? We are going to simulate many “walkers” to find this law, and we are going to do so
using array computing tricks: we are going to create a 2D array with the “stories” (each walker has a
Logical operations: story) in one direction, and the time in the other:
>>> np.all([True, True, False])
False
>>> np.any([True, True, False])
True

Note: Can be used for array comparisons:

>>> a = np.zeros((100, 100))


>>> np.any(a != 0)
False
>>> np.all(a == a)
True

>>> a = np.array([1, 2, 3, 2])


>>> b = np.array([2, 2, 3, 2]) >>> n_stories = 1000 # number of walkers
>>> c = np.array([6, 4, 4, 5]) >>> t_max = 200 # time during which we follow the walker
>>> ((a <= b) & (b <= c)).all()
We randomly choose all the steps 1 or -1 of the walk:
True
>>> t = np.arange(t_max)
>>> rng = np.random.default_rng()
Statistics: >>> steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1 # +1 because the␣
˓→high value is exclusive

>>> x = np.array([1, 2, 3, 1]) >>> np.unique(steps) # Verification: all steps are 1 or -1


>>> y = np.array([[1, 2, 3], [5, 6, 1]]) array([-1, 1])
>>> x.mean()
1.75 We build the walks by summing steps along the time:
>>> np.median(x) >>> positions = np.cumsum(steps, axis=1) # axis = 1: dimension of time
1.5 >>> sq_distance = positions**2
>>> np.median(y, axis=-1) # last axis
array([2., 5.]) We get the mean in the axis of the stories:
>>> mean_sq_distance = np.mean(sq_distance, axis=0)
>>> x.std() # full population standard dev.
0.82915619758884995 Plot the results:
>>> plt.figure(figsize=(4, 3))
. . . and many more (best to learn as you go). <Figure size ... with 0 Axes>
>>> plt.plot(t, np.sqrt(mean_sq_distance), 'g.', t, np.sqrt(t), 'y-')
Exercise: Reductions [<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel(r"$t$")
Text(...'$t$')
>>> plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$")
Text(...'$\\sqrt{\\langle (\\delta x)^2 \\rangle}$')
3.2. Numerical operations on arrays 72 >>> Numerical
3.2. plt.tight_layout()
operations #onprovide
arrays sufficient space for labels 73
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T


>>> a
array([[ 0, 0, 0],
[10, 10, 10],
[20, 20, 20],
[30, 30, 30]])
>>> b = np.array([0, 1, 2])
>>> a + b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])

We have already used broadcasting without knowing it!:


We find a well-known result in physics: the RMS distance grows as the square root of the time! >>> a = np.ones((4, 5))
>>> a[0] = 2 # we assign an array of dimension 0 to an array of dimension 1
>>> a
array([[2., 2., 2., 2., 2.],
3.2.3 Broadcasting
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
• Basic operations on numpy arrays (addition, etc.) are elementwise
[1., 1., 1., 1., 1.]])
• This works on arrays of the same size.
A useful trick:
Nevertheless, It’s also possible to do operations on arrays of different
sizes if NumPy can transform these arrays so that they all have >>> a = np.arange(0, 40, 10)
the same size: this conversion is called broadcasting. >>> a.shape
(4,)
The image below gives an example of broadcasting:
>>> a = a[:, np.newaxis] # adds a new axis -> 2D array
>>> a.shape
(4, 1)
>>> a
array([[ 0],
[10],
[20],
[30]])
>>> a + b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])

Tip: Broadcasting seems a bit magical, but it is actually quite natural to use it when we want to solve
a problem whose output data is an array with more dimensions than input data.

Worked Example: Broadcasting

Let’s construct an array of distances (in miles) between cities of Route 66: Chicago, Springfield,
Saint-Louis, Tulsa, Oklahoma City, Amarillo, Santa Fe, Albuquerque, Flagstaff and Los Angeles.
>>> mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544,
... 1913, 2448])
>>> distance_array = np.abs(mileposts - mileposts[:, np.newaxis])
>>> distance_array
array([[ 0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448],
[ 198, 0, 105, 538, 673, 977, 1277, 1346, 1715, 2250],
Let’s verify:

3.2. Numerical operations on arrays 74 3.2. Numerical operations on arrays 75


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

[ 303, 105, 0, 433, 568, 872, 1172, 1241, 1610, 2145],


[ 736, 538, 433, 0, 135, 439, 739, 808, 1177, 1712],
[ 871, 673, 568, 135, 0, 304, 604, 673, 1042, 1577],
[1175, 977, 872, 439, 304, 0, 300, 369, 738, 1273],
[1475, 1277, 1172, 739, 604, 300, 0, 69, 438, 973],
[1544, 1346, 1241, 808, 673, 369, 69, 0, 369, 904],
[1913, 1715, 1610, 1177, 1042, 738, 438, 369, 0, 535],
[2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535, 0]])

Remark : the numpy.ogrid() function allows to directly create vectors x and y of the previous example,
with two “significant dimensions”:

>>> x, y = np.ogrid[0:5, 0:5]


>>> x, y
(array([[0],
[1],
[2],
[3],
[4]]), array([[0, 1, 2, 3, 4]]))
>>> x.shape, y.shape
((5, 1), (1, 5))
>>> distance = np.sqrt(x ** 2 + y ** 2)
A lot of grid-based or network-based problems can also use broadcasting. For instance, if we want to
compute the distance from the origin of points on a 5x5 grid, we can do
Tip: So, np.ogrid is very useful as soon as we have to handle computations on a grid. On the other
>>> x, y = np.arange(5), np.arange(5)[:, np.newaxis] hand, np.mgrid directly provides matrices full of indices for cases where we can’t (or don’t want to)
>>> distance = np.sqrt(x ** 2 + y ** 2) benefit from broadcasting:
>>> distance
array([[0. , 1. , 2. , 3. , 4. ], >>> x, y = np.mgrid[0:4, 0:4]
[1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], >>> x
[2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], array([[0, 0, 0, 0],
[3. , 3.16227766, 3.60555128, 4.24264069, 5. ], [1, 1, 1, 1],
[4. , 4.12310563, 4.47213595, 5. , 5.65685425]]) [2, 2, 2, 2],
[3, 3, 3, 3]])
>>> y
Or in color:
array([[0, 1, 2, 3],
>>> plt.pcolor(distance) [0, 1, 2, 3],
<matplotlib.collections.PolyQuadMesh object at ...> [0, 1, 2, 3],
>>> plt.colorbar() [0, 1, 2, 3]])
<matplotlib.colorbar.Colorbar object at ...>

See also:
Broadcasting: discussion of broadcasting in the Advanced NumPy chapter.

3.2. Numerical operations on arrays 76 3.2. Numerical operations on arrays 77


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3.2.4 Array shape manipulation Adding a dimension

Flattening Indexing with the np.newaxis object allows us to add an axis to an array (you have seen this already
above in the broadcasting section):
>>> a = np.array([[1, 2, 3], [4, 5, 6]]) >>> z = np.array([1, 2, 3])
>>> a.ravel() >>> z
array([1, 2, 3, 4, 5, 6]) array([1, 2, 3])
>>> a.T
array([[1, 4], >>> z[:, np.newaxis]
[2, 5], array([[1],
[3, 6]]) [2],
>>> a.T.ravel() [3]])
array([1, 4, 2, 5, 3, 6])
>>> z[np.newaxis, :]
Higher dimensions: last dimensions ravel out “first”. array([[1, 2, 3]])

Reshaping
Dimension shuffling
The inverse operation to flattening:
>>> a = np.arange(4*3*2).reshape(4, 3, 2)
>>> a.shape >>> a.shape
(2, 3) (4, 3, 2)
>>> b = a.ravel() >>> a[0, 2, 1]
>>> b = b.reshape((2, 3)) 5
>>> b >>> b = a.transpose(1, 2, 0)
array([[1, 2, 3], >>> b.shape
[4, 5, 6]]) (3, 2, 4)
>>> b[2, 1, 0]
Or, 5
>>> a.reshape((2, -1)) # unspecified (-1) value is inferred
array([[1, 2, 3], Also creates a view:
[4, 5, 6]]) >>> b[2, 1, 0] = -1
>>> a[0, 2, 1]
-1
Warning: ndarray.reshape may return a view (cf help(np.reshape))), or copy

Resizing
Tip:
Size of an array can be changed with ndarray.resize:
>>> b[0, 0] = 99
>>> a >>> a = np.arange(4)
array([[99, 2, 3], >>> a.resize((8,))
[ 4, 5, 6]]) >>> a
array([0, 1, 2, 3, 0, 0, 0, 0])
Beware: reshape may also return a copy!:
However, it must not be referred to somewhere else:
>>> a = np.zeros((3, 2))
>>> b = a.T.reshape(3*2) >>> b = a
>>> b[0] = 9 >>> a.resize((4,))
>>> a Traceback (most recent call last):
array([[0., 0.], File "<stdin>", line 1, in <module>
[0., 0.], ValueError: cannot resize an array that references or is referenced
[0., 0.]]) by another array in this way.
Use the np.resize function or refcheck=False
To understand this you need to learn more about the memory layout of a NumPy array.

3.2. Numerical operations on arrays 78 3.2. Numerical operations on arrays 79


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise: Shape manipulations • Look at the axis keyword for sort and rewrite the previous exercise.

• Look at the docstring for reshape, especially the notes section which has some more information
about copies and views.
3.2.6 Summary
• Use flatten as an alternative to ravel. What is the difference? (Hint: check which one returns
a view and which a copy) What do you need to know to get started?
• Experiment with transpose for dimension shuffling. • Know how to create arrays : array, arange, ones, zeros.
• Know the shape of the array with array.shape, then use slicing to obtain different views of the
array: array[::2], etc. Adjust the shape of the array using reshape or flatten it with ravel.
3.2.5 Sorting data
• Obtain a subset of the elements of an array and/or modify their values with masks
Sorting along an axis: >>> a[a < 0] = 0
>>> a = np.array([[4, 3, 5], [1, 2, 1]])
>>> b = np.sort(a, axis=1) • Know miscellaneous operations on arrays, such as finding the mean or max (array.max(), array.
>>> b mean()). No need to retain everything, but have the reflex to search in the documentation (online
array([[3, 4, 5], docs, help(), lookfor())!!
[1, 1, 2]]) • For advanced use: master the indexing with arrays of integers, as well as broadcasting. Know more
NumPy functions to handle various array operations.

Note: Sorts each row separately!


Quick read

In-place sort: If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you
can directly skip to the next chapter: Matplotlib: plotting.
>>> a.sort(axis=1)
>>> a The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
array([[3, 4, 5], come back and finish this chapter, as well as to do some more exercices.
[1, 1, 2]])

Sorting with fancy indexing:

>>> a = np.array([4, 3, 1, 2])


>>> j = np.argsort(a) 3.3 More elaborate arrays
>>> j
array([2, 3, 1, 0])
>>> a[j] Section contents
array([1, 2, 3, 4])
• More data types
Finding minima and maxima:
• Structured data types
>>> a = np.array([4, 3, 1, 2])
• maskedarray: dealing with (propagation of) missing data
>>> j_max = np.argmax(a)
>>> j_min = np.argmin(a)
>>> j_max, j_min
(0, 2) 3.3.1 More data types

Casting
Exercise: Sorting
“Bigger” type wins in mixed-type operations:
• Try both in-place and out-of-place sorting.
• Try creating arrays with different dtypes and sorting them. >>> np.array([1, 2, 3]) + 1.5
array([2.5, 3.5, 4.5])
• Use all or array_equal to check the results.
• Look at np.random.shuffle for a way to create sortable input quicker. Assignment never changes the type!

• Combine ravel, sort and reshape.

3.2. Numerical operations on arrays 80 3.3. More elaborate arrays 81


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> a = np.array([1, 2, 3])


float16 16 bits
>>> a.dtype
float32 32 bits
dtype('int64')
float64 64 bits (same as float)
>>> a[0] = 1.9 # <-- float is truncated to integer
float96 96 bits, platform-dependent (same as np.longdouble)
>>> a
float128 128 bits, platform-dependent (same as np.longdouble)
array([1, 2, 3])

Forced casts: >>> np.finfo(np.float32).eps


1.1920929e-07
>>> a = np.array([1.7, 1.2, 1.6])
>>> np.finfo(np.float64).eps
>>> b = a.astype(int) # <-- truncates to integer
2.2204460492503131e-16
>>> b
array([1, 1, 1])
>>> np.float32(1e-8) + np.float32(1) == 1
True
Rounding: >>> np.float64(1e-8) + np.float64(1) == 1
>>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5]) False
>>> b = np.around(a)
>>> b # still floating-point Complex floating-point numbers:
array([1., 2., 2., 2., 4., 4.])
>>> c = np.around(a).astype(int) complex64 two 32-bit floats
>>> c complex128 two 64-bit floats
array([1, 2, 2, 2, 4, 4]) complex192 two 96-bit floats, platform-dependent
complex256 two 128-bit floats, platform-dependent

Different data type sizes


Smaller data types
Integers (signed):
If you don’t know you need special data types, then you probably don’t.
int8 8 bits Comparison on using float32 instead of float64:
int16 16 bits
• Half the size in memory and on disk
int32 32 bits (same as int on 32-bit platform)
int64 64 bits (same as int on 64-bit platform) • Half the memory bandwidth required (may be a bit faster in some operations)
In [1]: a = np.zeros((int(1e6),), dtype=np.float64)
>>> np.array([1], dtype=int).dtype
dtype('int64') In [2]: b = np.zeros((int(1e6),), dtype=np.float32)
>>> np.iinfo(np.int32).max, 2**31 - 1
(2147483647, 2147483647) In [3]: %timeit a*a
268 us +- 2.15 us per loop (mean +- std. dev. of 7 runs, 1,000 loops each)
Unsigned integers:
In [4]: %timeit b*b
133 us +- 138 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each)
uint8 8 bits
uint16 16 bits • But: bigger rounding errors — sometimes in surprising places (i.e., don’t use them unless you
uint32 32 bits really need them)
uint64 64 bits

>>> np.iinfo(np.uint32).max, 2**32 - 1


(4294967295, 4294967295)

Floating-point numbers:

3.3. More elaborate arrays 82 3.3. More elaborate arrays 83


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3.3.2 Structured data types 3.3.3 maskedarray: dealing with (propagation of) missing data

• For floats one could use NaN’s, but masks work for all types:
sensor_code (4-character string)
position (float) >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
value (float) >>> x
masked_array(data=[1, --, 3, --],
mask=[False, True, False, True],
>>> samples = np.zeros((6,), dtype=[('sensor_code', 'S4'), fill_value=999999)
... ('position', float), ('value', float)])
>>> samples.ndim
1 >>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1])
>>> samples.shape >>> x + y
(6,) masked_array(data=[2, --, --, --],
>>> samples.dtype.names mask=[False, True, True, True],
('sensor_code', 'position', 'value') fill_value=999999)
>>> samples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13),
... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)] • Masking versions of common functions:
>>> samples
array([(b'ALFA', 1. , 0.37), (b'BETA', 1. , 0.11), (b'TAU', 1. , 0.13), >>> np.ma.sqrt([1, -1, 2, -2])
(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11), (b'TAU', 1.2, 0.13)], masked_array(data=[1.0, --, 1.41421356237... --],
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')]) mask=[False, True, False, True],
fill_value=1e+20)
Field access works by indexing with field names:

>>> samples['sensor_code'] Note: There are other useful array siblings


array([b'ALFA', b'BETA', b'TAU', b'ALFA', b'ALFA', b'TAU'], dtype='|S4')
>>> samples['value']
array([0.37, 0.11, 0.13, 0.37, 0.11, 0.13])
>>> samples[0] While it is off topic in a chapter on NumPy, let’s take a moment to recall good coding practice, which
(b'ALFA', 1., 0.37) really do pay off in the long run:

>>> samples[0]['sensor_code'] = 'TAU'


>>> samples[0] Good practices
(b'TAU', 1., 0.37)
• Explicit variable names (no need of a comment to explain what is in the variable)
Multiple fields at once: • Style: spaces after commas, around =, etc.
>>> samples[['position', 'value']] A certain number of rules for writing “beautiful” code (and, more importantly, using the same
array([(1. , 0.37), (1. , 0.11), (1. , 0.13), (1.5, 0.37), conventions as everybody else!) are given in the Style Guide for Python Code and the Docstring
(3. , 0.11), (1.2, 0.13)], Conventions page (to manage help strings).
dtype={'names': ['position', 'value'], 'formats': ['<f8', '<f8'], 'offsets': [4, • Except some rare cases, variable names and comments in English.
˓→ 12], 'itemsize': 20})

Fancy indexing works, as usual:

>>> samples[samples['sensor_code'] == b'ALFA']


array([(b'ALFA', 1.5, 0.37), (b'ALFA', 3. , 0.11)], 3.4 Advanced operations
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')])

Section contents
Note: There are a bunch of other syntaxes for constructing structured arrays, see here and here.
• Polynomials
• Loading data files

3.3. More elaborate arrays 84 3.4. Advanced operations 85


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3.4.1 Polynomials (continued from previous page)


>>> y = np.cos(x) + 0.3*rng.random(2000)
NumPy also contains polynomials in different bases: >>> p = np.polynomial.Chebyshev.fit(x, y, 90)
For example, 3𝑥2 + 2𝑥 − 1:
>>> plt.plot(x, y, 'r.')
>>> p = np.poly1d([3, 2, -1]) [<matplotlib.lines.Line2D object at ...>]
>>> p(0) >>> plt.plot(x, p(x), 'k-', lw=3)
-1 [<matplotlib.lines.Line2D object at ...>]
>>> p.roots
array([-1. , 0.33333333])
>>> p.order
2

>>> x = np.linspace(0, 1, 20)


>>> rng = np.random.default_rng()
>>> y = np.cos(x) + 0.3*rng.random(20)
>>> p = np.poly1d(np.polyfit(x, y, 3))

>>> t = np.linspace(0, 1, 200) # use a larger number of points for smoother plotting
>>> plt.plot(x, y, 'o', t, p(t), '-')
[<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]

The Chebyshev polynomials have some advantages in interpolation.

3.4.2 Loading data files

Text files

Example: populations.txt:
# year hare lynx carrot
1900 30e3 4e3 48300
1901 47.2e3 6.1e3 48200
1902 70.2e3 9.8e3 41500
1903 77.4e3 35.2e3 38200
See https://numpy.org/doc/stable/reference/routines.polynomials.poly1d.html for more.

>>> data = np.loadtxt('data/populations.txt')


More polynomials (with more bases) >>> data
array([[ 1900., 30000., 4000., 48300.],
NumPy also has a more sophisticated polynomial interface, which supports e.g. the Chebyshev basis. [ 1901., 47200., 6100., 48200.],
3𝑥2 + 2𝑥 − 1: [ 1902., 70200., 9800., 41500.],
...
>>> p = np.polynomial.Polynomial([-1, 2, 3]) # coefs in different order!
>>> p(0) >>> np.savetxt('pop2.txt', data)
-1.0 >>> data2 = np.loadtxt('pop2.txt')
>>> p.roots()
array([-1. , 0.33333333])
>>> p.degree() # In general polynomials do not always expose 'order' Note: If you have a complicated text file, what you can try are:
2
• np.genfromtxt
Example using polynomials in Chebyshev basis, for polynomials in range [-1, 1]: • Using Python’s I/O functions and e.g. regexps for parsing (Python is quite well suited for this)
>>> x = np.linspace(-1, 1, 2000)
>>> rng = np.random.default_rng()
(continues on next page)

3.4. Advanced operations 86 3.4. Advanced operations 87


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Reminder: Navigating the filesystem with IPython >>> import imageio.v3 as iio
>>> iio.imwrite('tiny_elephant.png', (img[::6,::6] * 255).astype(np.uint8))
In [1]: pwd # show current directory >>> plt.imshow(plt.imread('tiny_elephant.png'), interpolation='nearest')
Out[1]: '/tmp' <matplotlib.image.AxesImage object at ...>

Images

Using Matplotlib:

>>> img = plt.imread('data/elephant.png')


>>> img.shape, img.dtype
((200, 300, 3), dtype('float32'))
>>> plt.imshow(img)
<matplotlib.image.AxesImage object at ...>
>>> plt.savefig('plot.png')

>>> plt.imsave('red_elephant.png', img[:,:,0], cmap=plt.cm.gray)

NumPy’s own format

NumPy has its own binary format, not portable but with efficient I/O:

>>> data = np.ones((3, 3))


>>> np.save('pop.npy', data)
>>> data3 = np.load('pop.npy')

Well-known (& more obscure) file formats

• HDF5: h5py, PyTables


• NetCDF: scipy.io.netcdf_file, netcdf4-python, . . .
This saved only one channel (of RGB):
• Matlab: scipy.io.loadmat, scipy.io.savemat
>>> plt.imshow(plt.imread('red_elephant.png'))
• MatrixMarket: scipy.io.mmread, scipy.io.mmwrite
<matplotlib.image.AxesImage object at ...>
• IDL: scipy.io.readsav
. . . if somebody uses it, there’s probably also a Python library for it.

Exercise: Text data files

Write a Python script that loads data from populations.txt:: and drop the last column and the first
5 rows. Save the smaller dataset to pop2.txt.

NumPy internals

If you are interested in the NumPy internals, there is a good discussion in Advanced NumPy.

Other libraries:

3.4. Advanced operations 88 3.4. Advanced operations 89


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3.5 Some exercises • Create an array of the image with a narrower centering
[for example,] remove 100 pixels from all the borders of the image. To check the result, display
this new array with imshow.
3.5.1 Array manipulations
>>> crop_face = face[100:-100, 100:-100]
1. Form the 2-D array (without typing it in explicitly):
• We will now frame the face with a black locket. For this, we
[[1, 6, 11], need to create a mask corresponding to the pixels we want to be black. The center of the face
[2, 7, 12], is around (660, 330), so we defined the mask by this condition (y-300)**2 + (x-660)**2
[3, 8, 13],
[4, 9, 14], >>> sy, sx = face.shape
[5, 10, 15]] >>> y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels
>>> y.shape, x.shape
and generate a new array containing its 2nd and 4th rows. ((768, 1), (1, 1024))
>>> centerx, centery = (660, 300) # center of the image
2. Divide each column of the array: >>> mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle
>>> import numpy as np
>>> a = np.arange(25).reshape(5, 5) then we assign the value 0 to the pixels of the image corresponding to the mask. The syntax
is extremely simple and intuitive:
elementwise with the array b = np.array([1., 5, 10, 15, 20]). (Hint: np.newaxis). >>> face[mask] = 0
3. Harder one: Generate a 10 x 3 array of random numbers (in range [0,1]). For each row, pick the >>> plt.imshow(face)
number closest to 0.5. <matplotlib.image.AxesImage object at 0x...>

• Use abs and argmin to find the column j closest for each row. • Follow-up: copy all instructions of this exercise in a script called
• Use fancy indexing to extract the numbers. (Hint: a[i,j] – the array i must contain the face_locket.py then execute this script in IPython with %run face_locket.py.
row numbers corresponding to stuff in j.) Change the circle to an ellipsoid.

3.5.2 Picture manipulation: Framing a Face 3.5.3 Data statistics


Let’s do some manipulations on NumPy arrays by starting with an image of a raccoon. scipy provides The data in populations.txt describes the populations of hares and lynxes (and carrots) in northern
a 2D array of this image with the scipy.datasets.face function: Canada during 20 years:
>>> import scipy as sp >>> data = np.loadtxt('data/populations.txt')
>>> face = sp.datasets.face(gray=True) # 2D grayscale image >>> year, hares, lynxes, carrots = data.T # trick: columns to variables

Here are a few images we will be able to obtain with our manipulations: use different colormaps, crop >>> import matplotlib.pyplot as plt
the image, change some parts of the image. >>> plt.axes([0.2, 0.1, 0.5, 0.8])
<Axes: >
>>> plt.plot(year, hares, year, lynxes, year, carrots)
[<matplotlib.lines.Line2D object at ...>, ...]
>>> plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5))
<matplotlib.legend.Legend object at ...>

• Let’s use the imshow function of matplotlib to display the image.

>>> import matplotlib.pyplot as plt


>>> face = sp.datasets.face(gray=True)
>>> plt.imshow(face)
<matplotlib.image.AxesImage object at 0x...>

• The face is displayed in false colors. A colormap must be


specified for it to be displayed in grey.

>>> plt.imshow(face, cmap=plt.cm.gray)


<matplotlib.image.AxesImage object at 0x...>

3.5. Some exercises 90 3.5. Some exercises 91


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Computes and print, based on the data in populations.txt. . .


N_max = 50
1. The mean and std of the populations of each species for the years in the period. some_threshold = 50
2. Which year each species had the largest population.
c = x + 1j*y
3. Which species has the largest population for each year. (Hint: argsort & fancy indexing of
np.array(['H', 'L', 'C'])) z = 0
for j in range(N_max):
4. Which years any of the populations is above 50000. (Hint: comparisons and np.any)
z = z**2 + c
5. The top 2 years for each species when they had the lowest populations. (Hint: argsort, fancy
indexing) Point (x, y) belongs to the Mandelbrot set if |𝑧| < some_threshold.
6. Compare (plot) the change in hare population (see help(np.gradient)) and the number of lynxes. Do this computation by:
Check correlation (see help(np.corrcoef)).
1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5]
. . . all without for-loops.
2. Do the iteration
Solution: Python source file
3. Form the 2-d boolean mask indicating which points are in the set
4. Save the result to an image with:
3.5.4 Crude integral approximations
>>> import matplotlib.pyplot as plt
Write a function f(a, b, c) that returns 𝑎𝑏 −𝑐. Form a 24x12x6 array containing its values in parameter >>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5])
ranges [0,1] x [0,1] x [0,1]. <matplotlib.image.AxesImage object at ...>
>>> plt.gray()
Approximate the 3-d integral >>> plt.savefig('mandelbrot.png')
∫︁ 1 ∫︁ 1 ∫︁ 1
(𝑎𝑏 − 𝑐)𝑑𝑎 𝑑𝑏 𝑑𝑐 Solution: Python source file
0 0 0

over this volume with the mean. The exact result is: ln 2 − 21 ≈ 0.1931 . . . — what is your relative error?
3.5.6 Markov chain
(Hints: use elementwise operations and broadcasting. You can make np.ogrid give a number of points
in given range with np.ogrid[0:1:20j].)
Reminder Python functions:

def f(a, b, c):


return some_result

Solution: Python source file

3.5.5 Mandelbrot set

Markov chain transition matrix P, and probability distribution on the states p:


1. 0 <= P[i,j] <= 1: probability to go from state i to state j
2. Transition rule: 𝑝𝑛𝑒𝑤 = 𝑃 𝑇 𝑝𝑜𝑙𝑑
3. all(sum(P, axis=1) == 1), p.sum() == 1: normalization
Write a script that works with 5 states, and:
• Constructs a random matrix, and normalizes each row so that it is a transition matrix.
Write a script that computes the Mandelbrot fractal. The Mandelbrot iteration:
• Starts from a random (normalized) probability distribution p and takes 50 steps => p_50

3.5. Some exercises 92 3.5. Some exercises 93


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Computes the stationary distribution: the eigenvector of P.T with eigenvalue 1 (numerically: closest (continued from previous page)
to 1) => p_stationary plt.plot(x, y, "o")
Remember to normalize the eigenvector — I didn’t. . . plt.show()

• Checks if p_50 and p_stationary are equal to tolerance 1e-5 Total running time of the script: (0 minutes 0.057 seconds)
Toolbox: np.random, @, np.linalg.eig, reductions, abs(), argmin, comparisons, all, np.linalg.norm,
etc.
Solution: Python source file
2D plotting

Plot a basic 2D figure

3.6 Full code examples

3.6.1 Full code examples for the numpy chapter

1D plotting

Plot a basic 1D figure

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng()
image = rng.random((30, 30))
plt.imshow(image, cmap=plt.cm.hot)
plt.colorbar()
plt.show()

import numpy as np Total running time of the script: (0 minutes 0.080 seconds)
import matplotlib.pyplot as plt

x = np.linspace(0, 3, 20)
y = np.linspace(0, 9, 20)
plt.plot(x, y)
(continues on next page)

3.6. Full code examples 94 3.6. Full code examples 95


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Distances exercise Fitting to polynomial

Plot distances in a grid Plot noisy data and their polynomial fit

import numpy as np import numpy as np


import matplotlib.pyplot as plt import matplotlib.pyplot as plt

x, y = np.arange(5), np.arange(5)[:, np.newaxis] rng = np.random.default_rng(27446968)


distance = np.sqrt(x**2 + y**2)
plt.pcolor(distance) x = np.linspace(0, 1, 20)
plt.colorbar() y = np.cos(x) + 0.3 * rng.random(20)
plt.show() p = np.poly1d(np.polyfit(x, y, 3))

Total running time of the script: (0 minutes 0.074 seconds) t = np.linspace(0, 1, 200)
plt.plot(x, y, "o", t, p(t), "-")
plt.show()

Total running time of the script: (0 minutes 0.056 seconds)

3.6. Full code examples 96 3.6. Full code examples 97


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Fitting in Chebyshev basis Population exercise

Plot noisy data and their polynomial fit in a Chebyshev basis Plot populations of hares, lynxes, and carrots

import numpy as np import numpy as np


import matplotlib.pyplot as plt import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968) data = np.loadtxt("../../../data/populations.txt")


year, hares, lynxes, carrots = data.T
x = np.linspace(-1, 1, 2000)
y = np.cos(x) + 0.3 * rng.random(2000) plt.axes([0.2, 0.1, 0.5, 0.8])
p = np.polynomial.Chebyshev.fit(x, y, 90) plt.plot(year, hares, year, lynxes, year, carrots)
plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5))
plt.plot(x, y, "r.") plt.show()
plt.plot(x, p(x), "k-", lw=3)
plt.show() Total running time of the script: (0 minutes 0.072 seconds)

Total running time of the script: (0 minutes 0.085 seconds)

3.6. Full code examples 98 3.6. Full code examples 99


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Reading and writing an elephant

Read and write images

import numpy as np
import matplotlib.pyplot as plt

original figure

plt.figure()
img = plt.imread("../../../data/elephant.png")
plt.imshow(img)

<matplotlib.image.AxesImage object at 0x7f49549dd9d0>

lower resolution

plt.figure()
img_tiny = img[::6, ::6]
plt.imshow(img_tiny, interpolation="nearest")

plt.show()

<matplotlib.image.AxesImage object at 0x7f4954da60d0>

red channel displayed in grey

plt.figure()
img_red = img[:, :, 0]
plt.imshow(img_red, cmap=plt.cm.gray)

3.6. Full code examples 100 3.6. Full code examples 101
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.296 seconds) import numpy as np
import matplotlib.pyplot as plt
from numpy import newaxis
import warnings
Mandelbrot set

Compute the Mandelbrot fractal and plot it def compute_mandelbrot(N_max, some_threshold, nx, ny):
# A grid of c-values
x = np.linspace(-2, 1, nx)
y = np.linspace(-1.5, 1.5, ny)

c = x[:, newaxis] + 1j * y[newaxis, :]

# Mandelbrot iteration

z = c

# The code below overflows in many regions of the x-y grid, suppress
# warnings temporarily
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for j in range(N_max):
z = z**2 + c
mandelbrot_set = abs(z) < some_threshold

return mandelbrot_set

(continues on next page)

3.6. Full code examples 102 3.6. Full code examples 103
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) # grows as a square root of time t.
plt.figure(figsize=(4, 3))
plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) plt.plot(t, np.sqrt(mean_sq_distance), "g.", t, np.sqrt(t), "y-")
plt.gray() plt.xlabel(r"$t$")
plt.show() plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$")
plt.tight_layout()
Total running time of the script: (0 minutes 0.073 seconds) plt.show()

Total running time of the script: (0 minutes 0.066 seconds)

Random walk exercise

Plot distance as a function of time for a random walk together with the theoretical result

import numpy as np
import matplotlib.pyplot as plt

# We create 1000 realizations with 200 steps each


n_stories = 1000
t_max = 200

t = np.arange(t_max)
# Steps can be -1 or 1 (note that randint excludes the upper limit)
rng = np.random.default_rng()
steps = 2 * rng.integers(0, 1 + 1, (n_stories, t_max)) - 1

# The time evolution of the position is obtained by successively


# summing up individual steps. This is done for each of the
# realizations, i.e. along axis 1.
positions = np.cumsum(steps, axis=1)

# Determine the time evolution of the mean square distance.


sq_distance = positions**2
mean_sq_distance = np.mean(sq_distance, axis=0)

# Plot the distance d from the origin as a function of time and


# compare with the theoretically expected result where d(t)
(continues on next page)

3.6. Full code examples 104 3.6. Full code examples 105
Scientific Python Lectures, Edition 2024.2rc0.dev0

4.1 Introduction

Tip: Matplotlib is probably the most used Python package for 2D-graphics. It provides both a quick
way to visualize data from Python and publication-quality figures in many formats. We are going to
explore matplotlib in interactive mode covering most common cases.

CHAPTER 4 4.1.1 IPython, Jupyter, and matplotlib modes

Tip: The Jupyter notebook and the IPython enhanced interactive Python, are tuned for the scientific-
computing workflow in Python, in combination with Matplotlib:

For interactive matplotlib sessions, turn on the matplotlib mode


IPython console
When using the IPython console, use:

In [1]: %matplotlib
Matplotlib: plotting
Jupyter notebook
In the notebook, insert, at the beginning of the notebook the following magic:

%matplotlib inline

4.1.2 pyplot
Thanks
Tip: pyplot provides a procedural interface to the matplotlib object-oriented plotting library. It is
Many thanks to Bill Wing and Christoph Deil for review and corrections.
modeled closely after Matlab™. Therefore, the majority of plotting commands in pyplot have Matlab™
analogs with similar arguments. Important commands are explained with interactive examples.
Authors: Nicolas Rougier, Mike Müller, Gaël Varoquaux

import matplotlib.pyplot as plt


Chapter contents

• Introduction
• Simple plot
4.2 Simple plot
• Figures, Subplots, Axes and Ticks
• Other Types of Plots: examples and exercises Tip: In this section, we want to draw the cosine and sine functions on the same plot. Starting from
the default settings, we’ll enrich the figure step by step to make it nicer.
• Beyond this tutorial
First step is to get the data for the sine and cosine functions:
• Quick references
• Full code examples
import numpy as np

X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X)

X is now a numpy array with 256 values ranging from −𝜋 to +𝜋 (included). C is the cosine (256 values)
and S is the sine (256 values).
To run the example, you can type them in an IPython interactive session:

106 4.1. Introduction 107


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

$ ipython --matplotlib
4.2.2 Instantiating defaults

This brings us to the IPython prompt:

IPython 0.13 -- An enhanced Interactive Python.


? -> Introduction to IPython's features.
%magic -> Information about IPython's 'magic' % functions.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

Tip: You can also download each of the examples and run it using regular python, but you will lose
interactive data manipulation:

$ python plot_exercise_1.py

You can get source for each step by clicking on the corresponding figure.
Hint: Documentation
• Customizing matplotlib

4.2.1 Plotting with default settings


In the script below, we’ve instantiated (and commented) all the figure settings that influence the ap-
pearance of the plot.

Tip: The settings have been explicitly set to their default values, but now you can interactively play
with the values to explore their affect (see Line properties and Line styles below).

import numpy as np
import matplotlib.pyplot as plt

# Create a figure of size 8x6 inches, 80 dots per inch


plt.figure(figsize=(8, 6), dpi=80)
Hint: Documentation
• plot tutorial # Create a new subplot from a grid of 1x1
plt.subplot(1, 1, 1)
• plot() command
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
Tip: Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You
can control the defaults of almost every property in matplotlib: figure size and dpi, line width, color and # Plot cosine with a blue continuous line of width 1 (pixels)
style, axes, axis and grid properties, text and font properties and so on. plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")

# Plot sine with a green continuous line of width 1 (pixels)


plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")
import numpy as np
# Set x limits
import matplotlib.pyplot as plt
plt.xlim(-4.0, 4.0)
X = np.linspace(-np.pi, np.pi, 256)
# Set x ticks
C, S = np.cos(X), np.sin(X)
plt.xticks(np.linspace(-4, 4, 9))
plt.plot(X, C)
# Set y limits
plt.plot(X, S)
plt.ylim(-1.0, 1.0)
plt.show()
# Set y ticks
(continues on next page)

4.2. Simple plot 108 4.2. Simple plot 109


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.yticks(np.linspace(-1, 1, 5)) Hint: Documentation
• xlim() command
# Save figure using 72 dots per inch
# plt.savefig("exercise_2.png", dpi=72) • ylim() command

# Show result on screen


plt.show() Tip: Current limits of the figure are a bit too tight and we want to make some space in order to clearly
see all data points.

4.2.3 Changing colors and line widths

...
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)
...

4.2.5 Setting ticks

Hint: Documentation
• Controlling line properties
• Line2D API

Tip: First step, we want to have the cosine in blue and the sine in red and a slightly thicker line for
both of them. We’ll also slightly alter the figure size to make it more horizontal.
Hint: Documentation
• xticks() command

... • yticks() command


plt.figure(figsize=(10, 6), dpi=80) • Tick container
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") • Tick locating and formatting
...

Tip: Current ticks are not ideal because they do not show the interesting values (±𝜋,:math:pm pi/2)
4.2.4 Setting limits for sine and cosine. We’ll change them such that they show only these values.

...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.yticks([-1, 0, +1])
...

4.2. Simple plot 110 4.2. Simple plot 111


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.2.6 Setting tick labels • Axis container


• Transformations tutorial

Tip: Spines are the lines connecting the axis tick marks and noting the boundaries of the data area.
They can be placed at arbitrary positions and until now, they were on the border of the axis. We’ll change
that since we want to have them in the middle. Since there are four of them (top/bottom/left/right),
we’ll discard the top and right by setting their color to none and we’ll move the bottom and left ones to
coordinate 0 in data space coordinates.

...
Hint: Documentation ax = plt.gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
• Working with text ax.spines['top'].set_color('none')
• xticks() command ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
• yticks() command ax.yaxis.set_ticks_position('left')
• set_xticklabels() ax.spines['left'].set_position(('data',0))
...
• set_yticklabels()

4.2.8 Adding a legend


Tip: Ticks are now properly placed but their label is not very explicit. We could guess that 3.142 is 𝜋
but it would be better to make it explicit. When we set tick values, we can also provide a corresponding
label in the second argument list. Note that we’ll use latex to allow for nice rendering of the label.

...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
...
Hint: Documentation
• Legend guide
4.2.7 Moving spines
• legend() command
• legend API

Tip: Let’s add a legend in the upper left corner. This only requires adding the keyword argument label
(that will be used in the legend box) to the plot commands.

...
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
Hint: Documentation
(continues on next page)
• spines API

4.2. Simple plot 112 4.2. Simple plot 113


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 4.2.10 Devil is in the details


plt.legend(loc='upper left')
...

4.2.9 Annotate some points

Hint: Documentation
• artist API
• set_bbox() method

Hint: Documentation
Tip: The tick labels are now hardly visible because of the blue and red lines. We can make them
• Annotating axis bigger and we can also adjust their properties such that they’ll be rendered on a semi-transparent white
• annotate() command background. This will allow us to see both the data and the labels.

Tip: Let’s annotate some interesting points using the annotate command. We chose the 2𝜋/3 value
and we want to annotate both the sine and the cosine. We’ll first draw a marker on the curve as well as ...
a straight dotted line. Then, we’ll use the annotate command to display some text with an arrow. for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
...
...

t = 2 * np.pi / 3 4.3 Figures, Subplots, Axes and Ticks


plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
A “figure” in matplotlib means the whole window in the user interface. Within this figure there can be
plt.annotate(r'$cos(\frac{2\pi}{3} )=-\frac{1} {2} $', “subplots”.
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16, Tip: So far we have used implicit figure and axes creation. This is handy for fast plots. We can have
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) more control over the display using figure, subplot, and axes explicitly. While subplot positions the plots
in a regular grid, axes allows free placement within the figure. Both can be useful depending on your
plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") intention. We’ve already worked with figures and subplots without explicitly calling them. When we
plt.scatter([t, ],[np.sin(t), ], 50, color='red') call plot, matplotlib calls gca() to get the current axes and gca in turn calls gcf() to get the current
figure. If there is none it calls figure() to make one, strictly speaking, to make a subplot(111). Let’s
plt.annotate(r'$sin(\frac{2\pi}{3} )=\frac{\sqrt{3} }{2} $', look at the details.
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
...

4.2. Simple plot 114 4.3. Figures, Subplots, Axes and Ticks 115
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.3.1 Figures

Tip: A figure is the windows in the GUI that has “Figure #” as title. Figures are numbered starting
from 1 as opposed to the normal Python way starting from 0. This is clearly MATLAB-style. There are
several parameters that determine what the figure looks like:

Argument Default Description


num 1 number of figure
figsize figure.figsize figure size in inches (width, height)
dpi figure.dpi resolution in dots per inch
facecolor figure.facecolor color of the drawing background
edgecolor figure.edgecolor color of edge around the drawing background
frameon True draw figure frame or not 4.3.3 Axes

Axes are very similar to subplots but allow placement of plots at any location in the figure. So if we
want to put a smaller plot inside a bigger one we do so with axes.
Tip: The defaults can be specified in the resource file and will be used most of the time. Only the
number of the figure is frequently changed.
As with other objects, you can set figure properties also setp or with the set_something methods.
When you work with the GUI you can close a figure by clicking on the x in the upper right corner. But
you can close a figure programmatically by calling close. Depending on the argument it closes (1) the
current figure (no argument), (2) a specific figure (figure number or figure instance as argument), or (3)
all figures ("all" as argument).

plt.close(1) # Closes figure 1

4.3.2 Subplots

Tip: With subplot you can arrange plots in a regular grid. You need to specify the number of rows and
columns and the number of the plot. Note that the gridspec command is a more powerful alternative.

4.3. Figures, Subplots, Axes and Ticks 116 4.3. Figures, Subplots, Axes and Ticks 117
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.3.4 Ticks

Well formatted ticks are an important part of publishing-ready figures. Matplotlib provides a totally
configurable system for ticks. There are tick locators to specify where ticks should appear and tick
formatters to give ticks the appearance you want. Major and minor ticks can be located and formatted
independently from each other. Per default minor ticks are not shown, i.e. there is only an empty list
for them because it is as NullLocator (see below).

Tick Locators

Tick locators control the positions of the ticks. They are set as follows:

ax = plt.gca()
ax.xaxis.set_major_locator(eval(locator))

There are several locators for different kind of requirements:

All of these locators derive from the base class matplotlib.ticker.Locator. You can make your own
locator deriving from it. Handling dates as ticks can be especially tricky. Therefore, matplotlib provides
special locators in matplotlib.dates.

4.4 Other Types of Plots: examples and exercises

4.4. Other Types of Plots: examples and exercises 118 4.4. Other Types of Plots: examples and exercises 119
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.1 Regular Plots

Starting from the code below, try to reproduce the graphic taking care of filled areas:

Hint: You need to use the fill_between() command.

n = 256
X = np.linspace(-np.pi, np.pi, n)
(continues on next page)

4.4. Other Types of Plots: examples and exercises 120 4.4. Other Types of Plots: examples and exercises 121
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


n = 12
Y = np.sin(2 * X) X = np.arange(n)
rng = np.random.default_rng()
plt.plot(X, Y + 1, color='blue', alpha=1.00) Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)
plt.plot(X, Y - 1, color='blue', alpha=1.00) Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n)

Click on the figure for solution. plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')


plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
4.4.2 Scatter Plots for x, y in zip(X, Y1):
plt.text(x + 0.4, y + 0.05, '%.2f ' % y, ha='center', va='bottom')

plt.ylim(-1.25, +1.25)

Click on figure for solution.

4.4.4 Contour Plots

Starting from the code below, try to reproduce the graphic taking care of marker size, color and trans-
parency.

Hint: Color is given by angle of (X,Y).

n = 1024
rng = np.random.default_rng()
X = rng.normal(0,1,n) Starting from the code below, try to reproduce the graphic taking care of the colormap (see Colormaps
Y = rng.normal(0,1,n) below).

plt.scatter(X,Y)
Hint: You need to use the clabel() command.
Click on figure for solution.
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2)
4.4.3 Bar Plots
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet')


C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)

Click on figure for solution.

Starting from the code below, try to reproduce the graphic by adding labels for red bars.

Hint: You need to take care of text alignment.

4.4. Other Types of Plots: examples and exercises 122 4.4. Other Types of Plots: examples and exercises 123
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.5 Imshow 4.4.7 Quiver Plots

Starting from the code below, try to reproduce the graphic taking care of colormap, image interpolation Starting from the code below, try to reproduce the graphic taking care of colors and orientations.
and origin.
Hint: You need to draw arrows twice.
Hint: You need to take care of the origin of the image in the imshow command and use a colorbar()

n = 8
def f(x, y): X, Y = np.mgrid[0:n, 0:n]
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) plt.quiver(X, Y)

n = 10 Click on figure for solution.


x = np.linspace(-3, 3, 4 * n)
y = np.linspace(-3, 3, 3 * n)
X, Y = np.meshgrid(x, y) 4.4.8 Grids
plt.imshow(f(X, Y))

Click on the figure for the solution.

4.4.6 Pie Charts

Starting from the code below, try to reproduce the graphic taking care of line styles.

axes = plt.gca()
axes.set_xlim(0, 4)
axes.set_ylim(0, 3)
axes.set_xticklabels([])
Starting from the code below, try to reproduce the graphic taking care of colors and slices size. axes.set_yticklabels([])

Click on figure for solution.


Hint: You need to modify Z.

rng = np.random.default_rng()
Z = rng.uniform(0, 1, 20)
plt.pie(Z)

Click on the figure for the solution.

4.4. Other Types of Plots: examples and exercises 124 4.4. Other Types of Plots: examples and exercises 125
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.4.9 Multi Plots 4.4.11 3D Plots

Starting from the code below, try to reproduce the graphic. Starting from the code below, try to reproduce the graphic.

Hint: You can use several subplots with different partition. Hint: You need to use contourf()

plt.subplot(2, 2, 1) from mpl_toolkits.mplot3d import Axes3D


plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4) fig = plt.figure()
ax = Axes3D(fig)
Click on figure for solution. X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
4.4.10 Polar Axis R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot')

Click on figure for solution.

4.4.12 Text

Hint: You only need to modify the axes line

Starting from the code below, try to reproduce the graphic.

plt.axes([0, 0, 1, 1])

N = 20
theta = np.arange(0., 2 * np.pi, 2 * np.pi / N) Try to do the same from scratch !
rng = np.random.default_rng()
radii = 10 * rng.random(N) Hint: Have a look at the matplotlib logo.
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
Click on figure for solution.
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.jet(r / 10.))
bar.set_alpha(0.5)

Click on figure for solution.

4.4. Other Types of Plots: examples and exercises 126 4.4. Other Types of Plots: examples and exercises 127
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.5.3 Code documentation

The code is well documented and you can quickly access a specific command from within a python
session:
Quick read
>>> import matplotlib.pyplot as plt
If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you >>> help(plt.plot)
can directly skip to the next chapter: SciPy : high-level scientific computing. Help on function plot in module matplotlib.pyplot:
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
come back and finish this chapter later. plot(*args: ...) -> 'list[Line2D]'
Plot y versus x as lines and/or markers.

Call signatures::
4.5 Beyond this tutorial plot([x], y, [fmt], *, data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
Matplotlib benefits from extensive documentation as well as a large community of users and developers. ...
Here are some links of interest:

4.5.1 Tutorials 4.5.4 Galleries

The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each
• Pyplot tutorial • Customizing your objects example comes with its source.
• Introduction • Object containers
• Controlling line properties • Figure container
• Working with multiple figures and axes • Axes container 4.5.5 Mailing lists
• Working with text • Axis containers
• Image tutorial • Tick containers Finally, there is a user mailing list where you can ask for help and a developers mailing list that is more
• Startup commands • Path tutorial technical.
• Importing image data into NumPy arrays • Introduction
• Plotting NumPy arrays as images • Bézier example
• Text tutorial • Compound paths 4.6 Quick references
• Text introduction • Transforms tutorial
• Basic text commands • Introduction
• Text properties and layout • Data coordinates Here is a set of tables that show main properties and styles.
• Writing mathematical expressions • Axes coordinates
• Text rendering With LaTeX • Blended transformations
• Annotating text • Using offset transforms to create a shadow
• Artist tutorial effect
• Introduction • The transformation pipeline

4.5.2 Matplotlib documentation

• User guide • How-To


• FAQ • Troubleshooting
• Installation • Environment Variables
• Usage • Screenshots

4.5. Beyond this tutorial 128 4.6. Quick references 129


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.6.1 Line properties 4.6.3 Markers

Property Description Appearance

alpha (or a) alpha transparency on 0-1


scale
antialiased True or False - use antialised
rendering

color (or c) matplotlib color arg


linestyle (or ls) see Line properties
linewidth (or lw) float, the line width in points
solid_capstyle Cap style for solid lines
solid_joinstyle Join style for solid lines
dash_capstyle Cap style for dashes
dash_joinstyle Join style for dashes
marker see Markers
markeredgewidth line width around the
(mew) marker symbol 4.6.4 Colormaps
markeredgecolor edge color if a marker is used
(mec) All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.
markerfacecolor face color if a marker is used If you want to know more about colormaps, check the documentation on Colormaps in matplotlib.
(mfc)
markersize (ms) size of the marker in points

4.6.2 Line styles

4.6. Quick references 130 4.6. Quick references 131


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4.7 Full code examples

4.7.1 Code samples for Matplotlib A simple, good-looking plot

The examples here are only examples relevant to the points raised in this chapter. The matplotlib Demoing some simple features of matplotlib
documentation comes with a much more exhaustive gallery.

Pie chart

A simple pie chart example with matplotlib.

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 4), dpi=72)


axes = fig.add_axes([0.01, 0.01, 0.98, 0.98])
X = np.linspace(0, 2, 200)
Y = np.sin(2 * np.pi * X)
import numpy as np plt.plot(X, Y, lw=2)
import matplotlib.pyplot as plt plt.ylim(-1.1, 1.1)
plt.grid()
n = 20
Z = np.ones(n) plt.show()
Z[-1] *= 2
Total running time of the script: (0 minutes 0.058 seconds)
plt.axes([0.025, 0.025, 0.95, 0.95])

plt.pie(Z, explode=Z * 0.05, colors=[f"{ i / float(n): f} " for i in range(n)])


plt.axis("equal")
plt.xticks([])
plt.yticks()

plt.show()

Total running time of the script: (0 minutes 0.050 seconds)

4.7. Full code examples 132 4.7. Full code examples 133
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting a scatter of points Subplots

A simple example showing how to plot a scatter of points with matplotlib. Show multiple subplots in matplotlib.

import numpy as np import matplotlib.pyplot as plt


import matplotlib.pyplot as plt
fig = plt.figure()
n = 1024 fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975)
rng = np.random.default_rng()
X = rng.normal(0, 1, n) plt.subplot(2, 1, 1)
Y = rng.normal(0, 1, n) plt.xticks([]), plt.yticks([])
T = np.arctan2(Y, X)
plt.subplot(2, 3, 4)
plt.axes([0.025, 0.025, 0.95, 0.95]) plt.xticks([])
plt.scatter(X, Y, s=75, c=T, alpha=0.5) plt.yticks([])

plt.xlim(-1.5, 1.5) plt.subplot(2, 3, 5)


plt.xticks([]) plt.xticks([])
plt.ylim(-1.5, 1.5) plt.yticks([])
plt.yticks([])
plt.subplot(2, 3, 6)
plt.show() plt.xticks([])
plt.yticks([])
Total running time of the script: (0 minutes 0.058 seconds)
plt.show()

Total running time of the script: (0 minutes 0.042 seconds)

4.7. Full code examples 134 4.7. Full code examples 135
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Horizontal arrangement of subplots Subplot plot arrangement vertical

An example showing horizontal arrangement of subplots with matplotlib. An example showing vertical arrangement of subplots with matplotlib.

import matplotlib.pyplot as plt import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.subplot(2, 1, 1) plt.figure(figsize=(6, 4))
plt.xticks([]) plt.subplot(1, 2, 1)
plt.yticks([]) plt.xticks([])
plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5) plt.yticks([])
plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5)
plt.subplot(2, 1, 2)
plt.xticks([]) plt.subplot(1, 2, 2)
plt.yticks([]) plt.xticks([])
plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5) plt.yticks([])
plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5)
plt.tight_layout()
plt.show() plt.tight_layout()
plt.show()
Total running time of the script: (0 minutes 0.049 seconds)
Total running time of the script: (0 minutes 0.046 seconds)

4.7. Full code examples 136 4.7. Full code examples 137
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

A simple plotting example Simple axes example

A plotting example with a few simple tweaks This example shows a couple of simple usage of axes.

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 4), dpi=72) plt.axes([0.1, 0.1, 0.8, 0.8])


axes = fig.add_axes([0.01, 0.01, 0.98, 0.98]) plt.xticks([])
x = np.linspace(0, 2, 200) plt.yticks([])
y = np.sin(2 * np.pi * x) plt.text(
plt.plot(x, y, lw=0.25, c="k") 0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20,␣
plt.xticks(np.arange(0.0, 2.0, 0.1)) ˓→alpha=0.5
plt.yticks(np.arange(-1.0, 1.0, 0.1)) )
plt.grid()
plt.show() plt.axes([0.2, 0.2, 0.3, 0.3])
plt.xticks([])
Total running time of the script: (0 minutes 0.077 seconds) plt.yticks([])
plt.text(
0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16,␣
˓→alpha=0.5

plt.show()

Total running time of the script: (0 minutes 0.040 seconds)

4.7. Full code examples 138 4.7. Full code examples 139
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

3D plotting Imshow elaborate

A simple example of 3D plotting. An example demoing imshow and styling the figure.

import numpy as np import numpy as np


import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

ax = plt.figure().add_subplot(projection="3d") def f(x, y):


X = np.arange(-4, 4, 0.25) return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2) n = 10
Z = np.sin(R) x = np.linspace(-3, 3, int(3.5 * n))
y = np.linspace(-3, 3, int(3.0 * n))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot) X, Y = np.meshgrid(x, y)
ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap=plt.cm.hot) Z = f(X, Y)
ax.set_zlim(-2, 2)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.show() plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower")
plt.colorbar(shrink=0.92)
Total running time of the script: (0 minutes 0.125 seconds)
plt.xticks([])
plt.yticks([])
plt.show()

Total running time of the script: (0 minutes 0.130 seconds)

4.7. Full code examples 140 4.7. Full code examples 141
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting a vector field: quiver A example of plotting not quite right

A simple example showing how to plot a vector field (quiver) with matplotlib. An “ugly” example of plotting.

import numpy as np
import matplotlib

matplotlib.use("Agg")
import numpy as np import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
matplotlib.rc("grid", color="black", linestyle="-", linewidth=1)
n = 8
X, Y = np.mgrid[0:n, 0:n] fig = plt.figure(figsize=(5, 4), dpi=72)
T = np.arctan2(Y - n / 2.0, X - n / 2.0) axes = fig.add_axes([0.01, 0.01, 0.98, 0.98], facecolor=".75")
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) X = np.linspace(0, 2, 40)
U, V = R * np.cos(T), R * np.sin(T) Y = np.sin(2 * np.pi * X)
plt.plot(X, Y, lw=0.05, c="b", antialiased=False)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.quiver(X, Y, U, V, R, alpha=0.5) plt.xticks([])
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) plt.yticks(np.arange(-1.0, 1.0, 0.2))
plt.grid()
plt.xlim(-1, n) ax = plt.gca()
plt.xticks([])
plt.ylim(-1, n) plt.show()
plt.yticks([])
Total running time of the script: (0 minutes 0.032 seconds)
plt.show()

Total running time of the script: (0 minutes 0.040 seconds)

4.7. Full code examples 142 4.7. Full code examples 143
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Displaying the contours of a function Plotting in polar coordinates

An example showing how to display the contours of a function with matplotlib. A simple example showing how to plot in polar coordinates with matplotlib.

import numpy as np import numpy as np


import matplotlib.pyplot as plt import matplotlib.pyplot as plt

ax = plt.axes([0.025, 0.025, 0.95, 0.95], polar=True)


def f(x, y):
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2) N = 20
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
n = 256 radii = 10 * rng.random(N)
x = np.linspace(-3, 3, n) width = np.pi / 4 * rng.random(N)
y = np.linspace(-3, 3, n) bars = plt.bar(theta, radii, width=width, bottom=0.0)
X, Y = np.meshgrid(x, y)
for r, bar in zip(radii, bars, strict=True):
plt.axes([0.025, 0.025, 0.95, 0.95]) bar.set_facecolor(plt.cm.jet(r / 10.0))
bar.set_alpha(0.5)
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5) ax.set_xticklabels([])
plt.clabel(C, inline=1, fontsize=10) ax.set_yticklabels([])
plt.show()
plt.xticks([])
plt.yticks([]) Total running time of the script: (0 minutes 0.104 seconds)
plt.show()

Total running time of the script: (0 minutes 0.087 seconds)

4.7. Full code examples 144 4.7. Full code examples 145
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Plot and filled plots Subplot grid

Simple example of plots and filling between them with matplotlib. An example showing the subplot grid in matplotlib.

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.subplot(2, 2, 1)
import numpy as np plt.xticks([])
import matplotlib.pyplot as plt plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5)
n = 256
X = np.linspace(-np.pi, np.pi, n) plt.subplot(2, 2, 2)
Y = np.sin(2 * X) plt.xticks([])
plt.yticks([])
plt.axes([0.025, 0.025, 0.95, 0.95]) plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5)

plt.plot(X, Y + 1, color="blue", alpha=1.00) plt.subplot(2, 2, 3)


plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25) plt.xticks([])
plt.yticks([])
plt.plot(X, Y - 1, color="blue", alpha=1.00)
plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25) plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5)
plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25)
plt.subplot(2, 2, 4)
plt.xlim(-np.pi, np.pi) plt.xticks([])
plt.xticks([]) plt.yticks([])
plt.ylim(-2.5, 2.5) plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5)
plt.yticks([])
plt.tight_layout()
plt.show() plt.show()

Total running time of the script: (0 minutes 0.031 seconds) Total running time of the script: (0 minutes 0.075 seconds)

4.7. Full code examples 146 4.7. Full code examples 147
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Bar plots Total running time of the script: (0 minutes 0.050 seconds)

An example of bar plots with matplotlib.

Axes

This example shows various axes command to position matplotlib axes.

import numpy as np
import matplotlib.pyplot as plt

n = 12
X = np.arange(n) import matplotlib.pyplot as plt
rng = np.random.default_rng()
Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) plt.axes([0.1, 0.1, 0.5, 0.5])
Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) plt.xticks([])
plt.yticks([])
plt.axes([0.025, 0.025, 0.95, 0.95]) plt.text(
plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") 0.1, 0.1, "axes([0.1, 0.1, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") )

for x, y in zip(X, Y1, strict=True): plt.axes([0.2, 0.2, 0.5, 0.5])


plt.text(x + 0.4, y + 0.05, f"{ y: .2f} ", ha="center", va="bottom") plt.xticks([])
plt.yticks([])
for x, y in zip(X, Y2, strict=True): plt.text(
plt.text(x + 0.4, -y - 0.05, f"{ y: .2f} ", ha="center", va="top") 0.1, 0.1, "axes([0.2, 0.2, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5
)
plt.xlim(-0.5, n)
plt.xticks([]) plt.axes([0.3, 0.3, 0.5, 0.5])
plt.ylim(-1.25, 1.25) plt.xticks([])
plt.yticks([]) plt.yticks([])
plt.text(
plt.show() (continues on next page)

4.7. Full code examples 148 4.7. Full code examples 149
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


0.1, 0.1, "axes([0.3, 0.3, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5 ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
) ax.yaxis.set_major_locator(plt.MultipleLocator(1.0))
ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))
plt.axes([0.4, 0.4, 0.5, 0.5]) ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75")
plt.xticks([]) ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75")
plt.yticks([]) ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75")
plt.text( ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75")
0.1, 0.1, "axes([0.4, 0.4, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5 ax.set_xticklabels([])
) ax.set_yticklabels([])

plt.show() plt.show()

Total running time of the script: (0 minutes 0.069 seconds) Total running time of the script: (0 minutes 0.089 seconds)

Grid 3D plotting

Displaying a grid on the axes in matploblib. Demo 3D plotting with matplotlib and style the figure.

import matplotlib.pyplot as plt import matplotlib.pyplot as plt


from mpl_toolkits.mplot3d import axes3d
ax = plt.axes([0.025, 0.025, 0.95, 0.95])
ax = plt.figure().add_subplot(projection="3d")
ax.set_xlim(0, 4) X, Y, Z = axes3d.get_test_data(0.05)
ax.set_ylim(0, 3) cset = ax.contourf(X, Y, Z)
ax.xaxis.set_major_locator(plt.MultipleLocator(1.0)) ax.clabel(cset, fontsize=9, inline=1)
(continues on next page) (continues on next page)

4.7. Full code examples 150 4.7. Full code examples 151
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.xticks([])
plt.yticks([])
ax.set_zticks([])

ax.text2D(
-0.05,
1.05,
" 3D plots \n",
horizontalalignment="left",
verticalalignment="top",
bbox={"facecolor": "white", "alpha": 1.0},
family="DejaVu Sans",
size="x-large",
transform=plt.gca().transAxes,
)

ax.text2D(
-0.05,
0.975,
" Plot 2D or 3D data",
horizontalalignment="left",
verticalalignment="top",
family="DejaVu Sans", import matplotlib.pyplot as plt
size="medium", from matplotlib import gridspec
transform=plt.gca().transAxes,
) plt.figure(figsize=(6, 4))
G = gridspec.GridSpec(3, 3)
plt.show()
axes_1 = plt.subplot(G[0, :])
Total running time of the script: (0 minutes 0.060 seconds) plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5)

axes_2 = plt.subplot(G[1, :-1])


GridSpec
plt.xticks([])
plt.yticks([])
An example demoing gridspec
plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5)

axes_3 = plt.subplot(G[1:, -1])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5)

axes_4 = plt.subplot(G[-1, 0])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5)

axes_5 = plt.subplot(G[-1, -2])


plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5)

plt.tight_layout()
plt.show()

4.7. Full code examples 152 4.7. Full code examples 153
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.073 seconds) (continued from previous page)

rng = np.random.default_rng()

Demo text printing for i in range(24):


index = rng.integers(0, len(eqs))
A example showing off elaborate text printing with matplotlib. eq = eqs[index]
size = np.random.uniform(12, 32)
x, y = np.random.uniform(0, 1, 2)
alpha = np.random.uniform(0.25, 0.75)
plt.text(
x,
y,
eq,
ha="center",
va="center",
color="#11557c",
alpha=alpha,
transform=plt.gca().transAxes,
fontsize=size,
clip_on=True,
)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.503 seconds)

4.7.2 Code for the chapter’s exercises

4.7.3 Example demoing choices for an option

4.7.4 Code generating the summary figures with a title


import numpy as np
import matplotlib.pyplot as plt Code for the chapter’s exercises

Exercise 1
eqs = []
eqs.append(
Solution of the exercise 1 with matplotlib.
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}
˓→ {8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\

˓→delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \

˓→sigma_2}}\right]$"

)
eqs.append(
r"$\frac{d\rho}{d t} + \rho \vec{v} \cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \
˓→vec{v} + \rho \vec{g} $"

)
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")
eqs.append(r"$F_G = G\frac{m_1m_2} {r^2}$")

plt.axes([0.025, 0.025, 0.95, 0.95])


(continues on next page)

4.7. Full code examples 154 4.7. Full code examples 155
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 4

Exercise 4 with matplotlib.

import numpy as np
import numpy as np import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 5), dpi=80)
n = 256 plt.subplot(111)
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X) X = np.linspace(-np.pi, np.pi, 256)
plt.plot(X, C) S = np.sin(X)
plt.plot(X, S) C = np.cos(X)

plt.show() plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
Total running time of the script: (0 minutes 0.052 seconds)
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.ylim(C.min() * 1.1, C.max() * 1.1)

plt.show()

Total running time of the script: (0 minutes 0.049 seconds)

4.7. Full code examples 156 4.7. Full code examples 157
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 3 Exercise 5

Exercise 3 with matplotlib. Exercise 5 with matplotlib.

import numpy as np import numpy as np


import matplotlib.pyplot as plt import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80) plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111) plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256) X = np.linspace(-np.pi, np.pi, 256)


C, S = np.cos(X), np.sin(X) S = np.sin(X)
C = np.cos(X)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(-4.0, 4.0)
plt.xticks(np.linspace(-4, 4, 9)) plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi])
plt.ylim(-1.0, 1.0)
plt.yticks(np.linspace(-1, 1, 5)) plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.yticks([-1, 0, +1])
plt.show()
plt.show()
Total running time of the script: (0 minutes 0.043 seconds)
Total running time of the script: (0 minutes 0.035 seconds)

4.7. Full code examples 158 4.7. Full code examples 159
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise 6 Exercise 2

Exercise 6 with matplotlib. Exercise 2 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)
import numpy as np
X = np.linspace(-np.pi, np.pi, 256) import matplotlib.pyplot as plt
C = np.cos(X)
S = np.sin(X) # Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") # Create a new subplot from a grid of 1x1
plt.subplot(111)
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks( X = np.linspace(-np.pi, np.pi, 256)
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], C, S = np.cos(X), np.sin(X)
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
) # Plot cosine using blue color with a continuous line of width 1 (pixels)
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")
plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"]) # Plot sine using green color with a continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")
plt.show()
# Set x limits
Total running time of the script: (0 minutes 0.045 seconds) plt.xlim(-4.0, 4.0)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

(continues on next page)

4.7. Full code examples 160 4.7. Full code examples 161
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


# Set y limits ax.spines["right"].set_color("none")
plt.ylim(-1.0, 1.0) ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
# Set y ticks ax.spines["bottom"].set_position(("data", 0))
plt.yticks(np.linspace(-1, 1, 5)) ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))
# Show result on screen
plt.show() plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks(
Total running time of the script: (0 minutes 0.045 seconds) [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

Exercise 7 plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, 0, +1], [r"$-1$", r"$0$", r"$+1$"])
Exercise 7 with matplotlib
plt.show()

Total running time of the script: (0 minutes 0.050 seconds)

Exercise 8

Exercise 8 with matplotlib.

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(8, 5), dpi=80)


plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)


C = np.cos(X)
S = np.sin(X)
import numpy as np
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") import matplotlib.pyplot as plt
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.figure(figsize=(8, 5), dpi=80)
ax = plt.gca() plt.subplot(111)
(continues on next page) (continues on next page)

4.7. Full code examples 162 4.7. Full code examples 163
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)


C = np.cos(X)
S = np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

ax = plt.gca()
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, +1], [r"$-1$", r"$+1$"]) import numpy as np
import matplotlib.pyplot as plt
plt.legend(loc="upper left")
plt.figure(figsize=(8, 5), dpi=80)
plt.show() plt.subplot(111)

Total running time of the script: (0 minutes 0.054 seconds) X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C = np.cos(X)
S = np.sin(X)

Exercise 9 plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")


plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
Exercise 9 with matplotlib.
ax = plt.gca()
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, +1], [r"$-1$", r"$+1$"])

t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--")
plt.scatter(
(continues on next page)

4.7. Full code examples 164 4.7. Full code examples 165
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Exercise


[
t, Exercises with matplotlib.
],
[
np.cos(t),
],
50,
color="blue",
)
plt.annotate(
r"$sin(\frac{2\pi}{3} )=\frac{\sqrt{3} }{2} $",
xy=(t, np.sin(t)),
xycoords="data",
xytext=(+10, +30),
textcoords="offset points",
fontsize=16,
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"},
)

plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--")


plt.scatter(
[
t,
],
[
np.sin(t),
],
50, import numpy as np
color="red", import matplotlib.pyplot as plt
)
plt.annotate( plt.figure(figsize=(8, 5), dpi=80)
r"$cos(\frac{2\pi}{3} )=-\frac{1} {2} $", plt.subplot(111)
xy=(t, np.cos(t)),
xycoords="data", X = np.linspace(-np.pi, np.pi, 256)
xytext=(-90, -50), C, S = np.cos(X), np.sin(X)
textcoords="offset points",
fontsize=16, plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
)
ax = plt.gca()
plt.legend(loc="upper left") ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
plt.show() ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
Total running time of the script: (0 minutes 0.110 seconds) ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

plt.xlim(X.min() * 1.1, X.max() * 1.1)


plt.xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$+\pi$"],
)

plt.ylim(C.min() * 1.1, C.max() * 1.1)


plt.yticks([-1, 1], [r"$-1$", r"$+1$"])

(continues on next page)

4.7. Full code examples 166 4.7. Full code examples 167
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Example demoing choices for an option


plt.legend(loc="upper left")
The colors matplotlib line plots
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--") An example demoing the various colors taken by matplotlib’s plot.
plt.scatter(
[
t,
], import matplotlib.pyplot as plt
[
np.cos(t), size = 256, 16
], dpi = 72.0
50, figsize = size[0] / float(dpi), size[1] / float(dpi)
color="blue", fig = plt.figure(figsize=figsize, dpi=dpi)
) fig.patch.set_alpha(0)
plt.annotate( plt.axes([0, 0.1, 1, 0.8], frameon=False)
r"$sin(\frac{2\pi}{3} )=\frac{\sqrt{3} }{2} $",
xy=(t, np.sin(t)), for i in range(1, 11):
xycoords="data", plt.plot([i, i], [0, 1], lw=1.5)
xytext=(10, 30),
textcoords="offset points", plt.xlim(0, 11)
fontsize=16, plt.xticks([])
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"}, plt.yticks([])
) plt.show()

plt.plot([t, t], [0, np.sin(t)], color="red", linewidth=1.5, linestyle="--") Total running time of the script: (0 minutes 0.013 seconds)
plt.scatter(
[
t,
], Linewidth
[
np.sin(t),
Plot various linewidth with matplotlib.
],
50,
color="red",
) import matplotlib.pyplot as plt
plt.annotate(
r"$cos(\frac{2\pi}{3} )=-\frac{1} {2} $", size = 256, 16
xy=(t, np.cos(t)), dpi = 72.0
xycoords="data", figsize = size[0] / float(dpi), size[1] / float(dpi)
xytext=(-90, -50), fig = plt.figure(figsize=figsize, dpi=dpi)
textcoords="offset points", fig.patch.set_alpha(0)
fontsize=16, plt.axes([0, 0.1, 1, 0.8], frameon=False)
arrowprops={"arrowstyle": "->", "connectionstyle": "arc3,rad=.2"},
) for i in range(1, 11):
plt.plot([i, i], [0, 1], color="b", lw=i / 2.0)
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16) plt.xlim(0, 11)
label.set_bbox({"facecolor": "white", "edgecolor": "None", "alpha": 0.65}) plt.ylim(0, 1)
plt.xticks([])
plt.show() plt.yticks([])

Total running time of the script: (0 minutes 0.116 seconds) plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

4.7. Full code examples 168 4.7. Full code examples 169
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Alpha: transparency Aliased versus anti-aliased

This example demonstrates using alpha for transparency. The example shows aliased versus anti-aliased text.

import matplotlib.pyplot as plt import matplotlib.pyplot as plt

size = 256, 16 size = 128, 16


dpi = 72.0 dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi) figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi) fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0) fig.patch.set_alpha(0)
plt.axes([0, 0.1, 1, 0.8], frameon=False) plt.axes([0, 0, 1, 1], frameon=False)

for i in range(1, 11): plt.rcParams["text.antialiased"] = True


plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0) plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center")

plt.xlim(0, 11) plt.xlim(0, 1)


plt.xticks([]) plt.ylim(0, 1)
plt.yticks([]) plt.xticks([])
plt.show() plt.yticks([])

Total running time of the script: (0 minutes 0.016 seconds) plt.show()

Total running time of the script: (0 minutes 0.011 seconds)

Aliased versus anti-aliased

Marker size
This example demonstrates aliased versus anti-aliased text.

Demo the marker size control in matplotlib.

import matplotlib.pyplot as plt

size = 128, 16 import matplotlib.pyplot as plt


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi) size = 256, 16
fig = plt.figure(figsize=figsize, dpi=dpi) dpi = 72.0
fig.patch.set_alpha(0) figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
plt.axes([0, 0, 1, 1], frameon=False) fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)
plt.rcParams["text.antialiased"] = False
plt.text(0.5, 0.5, "Aliased", ha="center", va="center") for i in range(1, 11):
plt.plot(
plt.xlim(0, 1) [
plt.ylim(0, 1) i,
plt.xticks([]) ],
plt.yticks([]) [
1,
plt.show() ],
"s",
Total running time of the script: (0 minutes 0.010 seconds) markersize=i,
markerfacecolor="w",
markeredgewidth=0.5,
markeredgecolor="k",
(continues on next page)

4.7. Full code examples 170 4.7. Full code examples 171
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Colormaps


)
An example plotting the matplotlib colormaps.
plt.xlim(0, 11)
plt.xticks([])
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

Marker edge width

Demo the marker edge widths of matplotlib’s markers.

import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi) import numpy as np
fig = plt.figure(figsize=figsize, dpi=dpi) import matplotlib.pyplot as plt
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False) plt.rc("text", usetex=False)
a = np.outer(np.arange(0, 1, 0.01), np.ones(10))
for i in range(1, 11):
plt.plot( plt.figure(figsize=(10, 5))
[ plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)
i, maps = [m for m in plt.cm.datad if not m.endswith("_r")]
], maps.sort()
[ l = len(maps) + 1
1,
], for i, m in enumerate(maps):
"s", plt.subplot(1, l, i + 1)
markersize=5, plt.axis("off")
markeredgewidth=1 + i / 10.0, plt.imshow(a, aspect="auto", cmap=plt.get_cmap(m), origin="lower")
markeredgecolor="k", plt.title(m, rotation=90, fontsize=10, va="bottom")
markerfacecolor="w",
) plt.show()
plt.xlim(0, 11)
plt.xticks([]) Total running time of the script: (0 minutes 1.352 seconds)
plt.yticks([])

plt.show()

Total running time of the script: (0 minutes 0.014 seconds)

4.7. Full code examples 172 4.7. Full code examples 173
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Solid joint style (continued from previous page)


plt.plot(
An example showing the different solid joint styles in matplotlib. 10 + np.arange(4),
np.ones(4),
color="blue",
linewidth=8,
import numpy as np solid_capstyle="projecting",
import matplotlib.pyplot as plt )

size = 256, 16 plt.xlim(0, 14)


dpi = 72.0 plt.xticks([])
figsize = size[0] / float(dpi), size[1] / float(dpi) plt.yticks([])
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0) plt.show()
plt.axes([0, 0, 1, 1], frameon=False)
Total running time of the script: (0 minutes 0.011 seconds)
plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter")
plt.plot(
4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="bevel"
) Marker edge color
plt.plot(
8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="round"
) Demo the marker edge color of matplotlib’s markers.

plt.xlim(0, 12)
plt.ylim(-1, 2)
import numpy as np
plt.xticks([])
import matplotlib.pyplot as plt
plt.yticks([])
size = 256, 16
plt.show()
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
Total running time of the script: (0 minutes 0.012 seconds)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

Solid cap style rng = np.random.default_rng()

An example demoing the solide cap style in matplotlib. for i in range(1, 11):
r, g, b = np.random.uniform(0, 1, 3)
plt.plot(
[
import numpy as np i,
import matplotlib.pyplot as plt ],
[
size = 256, 16 1,
dpi = 72.0 ],
figsize = size[0] / float(dpi), size[1] / float(dpi) "s",
fig = plt.figure(figsize=figsize, dpi=dpi) markersize=5,
fig.patch.set_alpha(0) markerfacecolor="w",
plt.axes([0, 0, 1, 1], frameon=False) markeredgewidth=1.5,
markeredgecolor=(r, g, b, 1),
plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt") )

plt.plot( plt.xlim(0, 11)


5 + np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="round" plt.xticks([])
) plt.yticks([])
(continues on next page)
(continues on next page)

4.7. Full code examples 174 4.7. Full code examples 175
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Dash capstyle

plt.show() An example demoing the dash capstyle.

Total running time of the script: (0 minutes 0.014 seconds)

import numpy as np
import matplotlib.pyplot as plt
Marker face color
size = 256, 16
dpi = 72.0
Demo the marker face color of matplotlib’s markers. figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)
import numpy as np
import matplotlib.pyplot as plt
plt.plot(
np.arange(4),
size = 256, 16
np.ones(4),
dpi = 72.0
color="blue",
figsize = size[0] / float(dpi), size[1] / float(dpi)
dashes=[15, 15],
fig = plt.figure(figsize=figsize, dpi=dpi)
linewidth=8,
fig.patch.set_alpha(0)
dash_capstyle="butt",
plt.axes([0, 0, 1, 1], frameon=False)
)
rng = np.random.default_rng()
plt.plot(
5 + np.arange(4),
for i in range(1, 11):
np.ones(4),
r, g, b = np.random.uniform(0, 1, 3)
color="blue",
plt.plot(
dashes=[15, 15],
[
linewidth=8,
i,
dash_capstyle="round",
],
)
[
1,
plt.plot(
],
10 + np.arange(4),
"s",
np.ones(4),
markersize=8,
color="blue",
markerfacecolor=(r, g, b, 1),
dashes=[15, 15],
markeredgewidth=0.1,
linewidth=8,
markeredgecolor=(0, 0, 0, 0.5),
dash_capstyle="projecting",
)
)
plt.xlim(0, 11)
plt.xticks([])
plt.xlim(0, 14)
plt.yticks([])
plt.xticks([])
plt.show()
plt.yticks([])
Total running time of the script: (0 minutes 0.014 seconds)
plt.show()

Total running time of the script: (0 minutes 0.011 seconds)

4.7. Full code examples 176 4.7. Full code examples 177
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Dash join style Markers

Example demoing the dash join style. Show the different markers of matplotlib.

import numpy as np
import matplotlib.pyplot as plt

size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)

plt.plot(
np.arange(3),
[0, 1, 0],
color="blue",
dashes=[12, 5],
linewidth=8,
dash_joinstyle="miter", import numpy as np
) import matplotlib.pyplot as plt
plt.plot(
4 + np.arange(3),
[0, 1, 0], def marker(m, i):
color="blue", X = i * 0.5 * np.ones(11)
dashes=[12, 5], Y = np.arange(11)
linewidth=8,
dash_joinstyle="bevel", plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1))
) plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom")
plt.plot(
8 + np.arange(3),
[0, 1, 0], markers = [
color="blue", 0,
dashes=[12, 5], 1,
linewidth=8, 2,
dash_joinstyle="round", 3,
) 4,
5,
plt.xlim(0, 12) 6,
plt.ylim(-1, 2) 7,
plt.xticks([]) "o",
plt.yticks([]) "h",
"_",
plt.show() "1",
"2",
Total running time of the script: (0 minutes 0.012 seconds) "3",
"4",
"8",
"p",
"^",
"v",
"<",
">",
"|",
(continues on next page)

4.7. Full code examples 178 4.7. Full code examples 179
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


"d",
",",
"+",
"s",
"*",
"|",
"x",
"D",
"H",
".",
]

n_markers = len(markers)

size = 20 * n_markers, 300


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
plt.axes([0, 0.01, 1, 0.9], frameon=False)

for i, m in enumerate(markers):
marker(m, i)
import numpy as np
plt.xlim(-0.2, 0.2 + 0.5 * n_markers) import matplotlib.pyplot as plt
plt.xticks([])
plt.yticks([])
def linestyle(ls, i):
plt.show() X = i * 0.5 * np.ones(11)
Y = np.arange(11)
Total running time of the script: (0 minutes 0.058 seconds) plt.plot(
X,
Y,
ls,
Linestyles color=(0.0, 0.0, 1, 1),
lw=3,
Plot the different line styles. ms=8,
mfc=(0.75, 0.75, 1, 1),
mec=(0, 0, 1, 1),
)
plt.text(0.5 * i, 10.25, ls, rotation=90, fontsize=15, va="bottom")

linestyles = [
"-",
"--",
":",
"-.",
".",
",",
"o",
"^",
"v",
"<",
">",
"s",
"+",
(continues on next page)

4.7. Full code examples 180 4.7. Full code examples 181
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


"x",
"d",
"1",
"2",
"3",
"4",
"h",
"p",
"|",
"_",
"D",
"H",
]
n_lines = len(linestyles)

size = 20 * n_lines, 300


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
plt.axes([0, 0.01, 1, 0.9], frameon=False)
import numpy as np
for i, ls in enumerate(linestyles): import matplotlib.pyplot as plt
linestyle(ls, i)

plt.xlim(-0.2, 0.2 + 0.5 * n_lines) def tickline():


plt.xticks([]) plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([])
plt.yticks([]) ax = plt.gca()
ax.spines["right"].set_color("none")
plt.show() ax.spines["left"].set_color("none")
ax.spines["top"].set_color("none")
Total running time of the script: (0 minutes 0.039 seconds) ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))
ax.yaxis.set_ticks_position("none")
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
Locators for tick on axis ax.plot(np.arange(11), np.zeros(11))
return ax
An example demoing different locators to position ticks on axis for matplotlib.

locators = [
"plt.NullLocator()",
"plt.MultipleLocator(1.0)",
"plt.FixedLocator([0, 2, 8, 9, 10])",
"plt.IndexLocator(3, 1)",
"plt.LinearLocator(5)",
"plt.LogLocator(2, [1.0])",
"plt.AutoLocator()",
]

n_locators = len(locators)

size = 512, 40 * n_locators


dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)

(continues on next page)

4.7. Full code examples 182 4.7. Full code examples 183
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


ax = Axes3D(fig)
for i, locator in enumerate(locators): X = np.arange(-4, 4, 0.25)
plt.subplot(n_locators, 1, i + 1) Y = np.arange(-4, 4, 0.25)
ax = tickline() X, Y = np.meshgrid(X, Y)
ax.xaxis.set_major_locator(eval(locator)) R = np.sqrt(X**2 + Y**2)
plt.text(5, 0.3, locator[3:], ha="center") Z = np.sin(R)

plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)


plt.show() ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2, 2)
Total running time of the script: (0 minutes 0.791 seconds) plt.xticks([])
plt.yticks([])
ax.set_zticks([])

ax.text2D(
0.05,
Code generating the summary figures with a title 0.93,
" 3D plots \n",
3D plotting vignette horizontalalignment="left",
verticalalignment="top",
Demo 3D plotting with matplotlib and decorate the figure. size="xx-large",
bbox={"facecolor": "white", "alpha": 1.0},
transform=plt.gca().transAxes,
)

ax.text2D(
0.05,
0.87,
" Plot 2D or 3D data",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.042 seconds)

Plotting in polar, decorated

An example showing how to plot in polar coordinate, and some decorations.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
(continues on next page)

4.7. Full code examples 184 4.7. Full code examples 185
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.text(
-0.2,
1.01,
"\n\n Plot anything using polar axis ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.120 seconds)

Plot example vignette

An example of plots with matplotlib, and added annotations.

import numpy as np
import matplotlib.pyplot as plt

plt.subplot(1, 1, 1, polar=True)

N = 20
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
radii = 10 * rng.random(N)
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars, strict=True):
bar.set_facecolor(plt.cm.jet(r / 10.0))
bar.set_alpha(0.5)
plt.gca().set_xticklabels([])
plt.gca().set_yticklabels([])

plt.text(
-0.2,
1.02,
" Polar Axis \n",
horizontalalignment="left", import numpy as np
verticalalignment="top", import matplotlib.pyplot as plt
size="xx-large",
bbox={"facecolor": "white", "alpha": 1.0}, n = 256
transform=plt.gca().transAxes, X = np.linspace(0, 2, n)
) Y = np.sin(2 * np.pi * X)
(continues on next page) (continues on next page)

4.7. Full code examples 186 4.7. Full code examples 187
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Multiple plots vignette

plt.plot(X, Y, lw=2, color="violet") Demo multiple plots and style the figure.
plt.xlim(-0.2, 2.2)
plt.xticks([])
plt.ylim(-1.2, 1.2)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Regular Plot: plt.plot(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large", import matplotlib.pyplot as plt
transform=plt.gca().transAxes,
) ax = plt.subplot(2, 1, 1)
ax.set_xticklabels([])
plt.text( ax.set_yticklabels([])
-0.05,
1.01,
"\n\n Plot lines and/or markers ", # Add a title and a box around it
horizontalalignment="left", from matplotlib.patches import FancyBboxPatch
verticalalignment="top",
size="large", ax = plt.gca()
transform=plt.gca().transAxes, ax.add_patch(
) FancyBboxPatch(
(-0.05, 0.72),
plt.show() width=0.66,
height=0.34,
Total running time of the script: (0 minutes 0.028 seconds) clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)
(continues on next page)

4.7. Full code examples 188 4.7. Full code examples 189
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

plt.text(
-0.05,
1.02,
" Multiplot: plt.subplot(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=ax.transAxes,
)
plt.text(
-0.05,
1.01,
"\n\n Plot several plots at once ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=ax.transAxes,
)

ax = plt.subplot(2, 2, 3)
ax.set_xticklabels([])
ax.set_yticklabels([])
import numpy as np
ax = plt.subplot(2, 2, 4) import matplotlib.pyplot as plt
ax.set_xticklabels([])
ax.set_yticklabels([])
fig = plt.figure(figsize=(8, 5))
plt.show() axes = plt.subplot(111)

Total running time of the script: (0 minutes 0.090 seconds) n = 5


Z = np.zeros((n, 4))
X = np.linspace(0, 2, n)
rng = np.random.default_rng()
Boxplot with matplotlib Y = rng.random((n, 4))
plt.boxplot(Y)
An example of doing box plots with matplotlib
plt.xticks([])
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
(continues on next page)

4.7. Full code examples 190 4.7. Full code examples 191
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


)
)

plt.text(
-0.05,
1.02,
" Box Plot: plt.boxplot(...)\n ",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=axes.transAxes,
)

plt.text(
-0.04,
0.98,
"\n Make a box and whisker plot ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=axes.transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.039 seconds)

import numpy as np
Plot scatter decorated import matplotlib.pyplot as plt

n = 1024
An example showing the scatter function, with decorations.
rng = np.random.default_rng()
X = rng.normal(0, 1, n)
Y = rng.normal(0, 1, n)

T = np.arctan2(Y, X)

plt.scatter(X, Y, s=75, c=T, alpha=0.5)


plt.xlim(-1.5, 1.5)
plt.xticks([])
plt.ylim(-1.5, 1.5)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
(continues on next page)

4.7. Full code examples 192 4.7. Full code examples 193
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Scatter Plot: plt.scatter(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Make a scatter plot of x versus y ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()
import numpy as np
Total running time of the script: (0 minutes 0.059 seconds) import matplotlib.pyplot as plt

n = 20
X = np.ones(n)
Pie chart vignette X[-1] *= 2
plt.pie(X, explode=X * 0.05, colors=[f"{ i / float(n): f} " for i in range(n)])
Demo pie chart with matplotlib and style the figure.
fig = plt.gcf()
w, h = fig.get_figwidth(), fig.get_figheight()
r = h / float(w)

plt.xlim(-1.5, 1.5)
plt.ylim(-1.5 * r, 1.5 * r)
plt.xticks([])
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
(continues on next page)

4.7. Full code examples 194 4.7. Full code examples 195
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Pie Chart: plt.pie(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Make a pie chart of an array ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show() import numpy as np


import matplotlib.pyplot as plt
Total running time of the script: (0 minutes 0.052 seconds)

def f(x, y):


return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)
Imshow demo

n = 10
Demoing imshow
x = np.linspace(-3, 3, 8 * n)
y = np.linspace(-3, 3, 6 * n)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower")
plt.xticks([])
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
(continues on next page)

4.7. Full code examples 196 4.7. Full code examples 197
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Imshow: plt.imshow(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Display an image to current axes ",
horizontalalignment="left",
verticalalignment="top",
family="DejaVu Sans",
size="large",
transform=plt.gca().transAxes,
)
import numpy as np
plt.show() import matplotlib.pyplot as plt

Total running time of the script: (0 minutes 0.035 seconds) n = 16


X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Bar plot advanced plt.bar(X, Y1, facecolor="#9999ff", edgecolor="white")
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")
plt.xlim(-0.5, n)
An more elaborate bar plot example
plt.xticks([])
plt.ylim(-1, 1)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
(continues on next page)

4.7. Full code examples 198 4.7. Full code examples 199
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Bar Plot: plt.bar(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Make a bar plot with rectangles ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

plt.show()

Total running time of the script: (0 minutes 0.045 seconds)


import numpy as np
import matplotlib.pyplot as plt

Plotting quiver decorated n = 8


X, Y = np.mgrid[0:n, 0:n]
T = np.arctan2(Y - n / 2.0, X - n / 2.0)
An example showing quiver with decorations.
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)
U, V = R * np.cos(T), R * np.sin(T)

plt.quiver(X, Y, U, V, R, alpha=0.5)
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5)

plt.xlim(-1, n)
plt.xticks([])
plt.ylim(-1, n)
plt.yticks([])

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
(continues on next page)

4.7. Full code examples 200 4.7. Full code examples 201
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Quiver Plot: plt.quiver(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Plot a 2-D field of arrows ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)

/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/
plt.show() ˓→matplotlib/examples/pretty_plots/plot_contour_ext.py:24: UserWarning: The following␣

˓→kwargs were not used by contour: 'linewidth'

Total running time of the script: (0 minutes 0.043 seconds) C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5)

Display the contours of a function

An example demoing how to plot the contours of a function, with additional layout tweaks. import numpy as np
import matplotlib.pyplot as plt

def f(x, y):


return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)


C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5)
plt.clabel(C, inline=1, fontsize=10)
plt.xticks([])
plt.yticks([])
(continues on next page)

4.7. Full code examples 202 4.7. Full code examples 203
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Grid elaborate

An example displaying a grid on the axes and tweaking the layout.


# Add a title and a box around it
from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Contour Plot: plt.contour(..)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01, Text(-0.05, 1.01, '\n\n Draw ticks and grid ')
"\n\n Draw contour lines and filled contours ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
)
import matplotlib.pyplot as plt
plt.show() from matplotlib.ticker import MultipleLocator

Total running time of the script: (0 minutes 0.089 seconds) fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white")
axes = plt.subplot(111)
axes.set_xlim(0, 4)
axes.set_ylim(0, 3)

axes.xaxis.set_major_locator(MultipleLocator(1.0))
axes.xaxis.set_minor_locator(MultipleLocator(0.1))
axes.yaxis.set_major_locator(MultipleLocator(1.0))
axes.yaxis.set_minor_locator(MultipleLocator(0.1))
axes.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75")
axes.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75")
axes.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75")
axes.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75")
axes.set_xticklabels([])
(continues on next page)

4.7. Full code examples 204 4.7. Full code examples 205
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Text printing decorated


axes.set_yticklabels([])
An example showing text printing and decorating the resulting figure.

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Grid: plt.grid(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=axes.transAxes,
)

plt.text(
-0.05, import numpy as np
1.01, import matplotlib.pyplot as plt
"\n\n Draw ticks and grid ",
horizontalalignment="left", fig = plt.figure()
verticalalignment="top", plt.xticks([])
size="large", plt.yticks([])
transform=axes.transAxes,
) eqs = []
eqs.append(
Total running time of the script: (0 minutes 0.089 seconds) r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}
˓→ {8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\

˓→delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \

˓→sigma_2}}\right]$"

)
eqs.append(
r"$\frac{d\rho}{d t} + \rho \vec{v} \cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \
˓→vec{v} + \rho \vec{g} $"

)
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")
eqs.append(r"$F_G = G\frac{m_1m_2} {r^2}$")

rng = np.random.default_rng()

(continues on next page)

4.7. Full code examples 206 4.7. Full code examples 207
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


for i in range(24): )
index = rng.integers(0, len(eqs))
eq = eqs[index] plt.show()
size = rng.uniform(12, 32)
x, y = rng.uniform(0, 1, 2) Total running time of the script: (0 minutes 0.481 seconds)
alpha = rng.uniform(0.25, 0.75)
plt.text(
x,
y,
eq,
ha="center",
va="center",
color="#11557c",
alpha=alpha,
transform=plt.gca().transAxes,
fontsize=size,
clip_on=True,
)

# Add a title and a box around it


from matplotlib.patches import FancyBboxPatch

ax = plt.gca()
ax.add_patch(
FancyBboxPatch(
(-0.05, 0.87),
width=0.66,
height=0.165,
clip_on=False,
boxstyle="square,pad=0",
zorder=3,
facecolor="white",
alpha=1.0,
transform=plt.gca().transAxes,
)
)

plt.text(
-0.05,
1.02,
" Text: plt.text(...)\n",
horizontalalignment="left",
verticalalignment="top",
size="xx-large",
transform=plt.gca().transAxes,
)

plt.text(
-0.05,
1.01,
"\n\n Draw any kind of text ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=plt.gca().transAxes,
(continues on next page)

4.7. Full code examples 208 4.7. Full code examples 209
Scientific Python Lectures, Edition 2024.2rc0.dev0

• Optimization and fit: scipy.optimize


• Statistics and random numbers: scipy.stats
• Numerical integration: scipy.integrate
• Fast Fourier transforms: scipy.fft
• Signal processing: scipy.signal

5
• Image manipulation: scipy.ndimage
• Summary exercises on scientific computing
• Full code examples for the SciPy chapter
CHAPTER

Warning: This tutorial is far from an introduction to numerical computing. As enumerating the
different submodules and functions in SciPy would be very boring, we concentrate instead on a few
examples to give a general idea of how to use scipy for scientific computing.

scipy is composed of task-specific sub-modules:

SciPy : high-level scientific computing scipy.cluster Vector quantization / Kmeans


scipy.constants Physical and mathematical constants
scipy.fft Fourier transform
scipy.integrate Integration routines
scipy.interpolate Interpolation
scipy.io Data input and output
scipy.linalg Linear algebra routines
Authors: Gaël Varoquaux, Adrien Chauve, Andre Espaze, Emmanuelle Gouillart, Ralf Gommers scipy.ndimage n-dimensional image package
scipy.odr Orthogonal distance regression
scipy.optimize Optimization
Scipy scipy.signal Signal processing
scipy.sparse Sparse matrices
The scipy package contains various toolboxes dedicated to common issues in scientific computing. scipy.spatial Spatial data structures and algorithms
Its different submodules correspond to different applications, such as interpolation, integration, opti- scipy.special Any special mathematical functions
mization, image processing, statistics, special functions, etc. scipy.stats Statistics

Tip: scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU Tip: They all depend on numpy, but are mostly independent of each other. The standard way of
Scientific Library for C and C++), or Matlab’s toolboxes. scipy is the core package for scientific routines importing NumPy and these SciPy modules is:
in Python; it is meant to operate efficiently on numpy arrays, so that NumPy and SciPy work hand in
hand. >>> import numpy as np
>>> import scipy as sp
Before implementing a routine, it is worth checking if the desired data processing is not already imple-
mented in SciPy. As non-professional programmers, scientists often tend to re-invent the wheel, which
leads to buggy, non-optimal, difficult-to-share and unmaintainable code. By contrast, SciPy’s routines
are optimized and tested, and should therefore be used when possible.
5.1 File input/output: scipy.io
Chapters contents scipy.io contains functions for loading and saving data in several common formats including Matlab,
IDL, Matrix Market, and Harwell-Boeing.
• File input/output: scipy.io
Matlab files: Loading and saving:
• Special functions: scipy.special
>>> import scipy as sp
• Linear algebra operations: scipy.linalg >>> a = np.ones((3, 3))
• Interpolation: scipy.interpolate >>> sp.io.savemat('file.mat', {'a': a}) # savemat expects a dictionary
(continues on next page)

210 5.1. File input/output: scipy.io 211


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> import scipy as sp
>>> data = sp.io.loadmat('file.mat') >>> x = np.asarray([1, 2])
>>> data['a'] >>> y = np.asarray([[3], [4], [5]])
array([[1., 1., 1.], >>> res = sp.special.xlog1py(x, y)
[1., 1., 1.], >>> res.shape
[1., 1., 1.]]) (3, 2)
>>> ref = x * np.log(1 + y)
>>> np.allclose(res, ref)
Warning: Python / Matlab mismatch: The Matlab file format does not support 1D arrays. True
>>> a = np.ones(3)
However, scipy.special.xlog1py() is numerically favorable for small 𝑦, when explicit addition of 1
>>> a
would lead to loss of precision due to floating point truncation error.
array([1., 1., 1.])
>>> a.shape >>> x = 2.5
(3,) >>> y = 1e-18
>>> sp.io.savemat('file.mat', {'a': a}) >>> x * np.log(1 + y)
>>> a2 = sp.io.loadmat('file.mat')['a'] 0.0
>>> a2 >>> sp.special.xlog1py(x, y)
array([[1., 1., 1.]]) 2.5e-18
>>> a2.shape
(1, 3) Many special functions also have “logarithmized” variants. For instance, the gamma function Γ(·) is
Notice that the original array was a one-dimensional array, whereas the saved and reloaded array is related to the factorial function by 𝑛! = Γ(𝑛 + 1), but it extends the domain from the positive integers
a two-dimensional array with a single row. to the complex plane.

For other formats, see the scipy.io documentation. >>> x = np.arange(10)


>>> np.allclose(sp.special.gamma(x + 1), sp.special.factorial(x))
True
See also: >>> sp.special.gamma(5) < sp.special.gamma(5.5) < sp.special.gamma(6)
• Load text files: numpy.loadtxt()/numpy.savetxt() True

• Clever loading of text/csv files: numpy.genfromtxt() The factorial function grows quickly, and so the gamma function overflows for moderate values of the
• Fast and efficient, but NumPy-specific, binary format: numpy.save()/numpy.load() argument. However, sometimes only the logarithm of the gamma function is needed. In such cases, we
can compute the logarithm of the gamma function directly using scipy.special.gammaln().
• Basic input/output of images in Matplotlib: matplotlib.pyplot.imread()/matplotlib.pyplot.
imsave() >>> x = [5, 50, 500]
>>> np.log(sp.special.gamma(x))
• More advanced input/output of images: imageio
array([ 3.17805383, 144.56574395, inf])
>>> sp.special.gammaln(x)
array([ 3.17805383, 144.56574395, 2605.11585036])
5.2 Special functions: scipy.special
Such functions can often be used when the intermediate components of a calculation would overflow
“Special” functions are functions commonly used in science and mathematics that are not considered to or underflow, but the final result would not. For example, suppose we wish to compute the ratio
be “elementary” functions. Examples include Γ(500)/Γ(499).
• the gamma function, scipy.special.gamma(), >>> a = sp.special.gamma(500)
• the error function, scipy.special.erf(), >>> b = sp.special.gamma(499)
>>> a, b
• Bessel functions, such as scipy.special.jv() (Bessel function of the first kind), and (inf, inf)
• elliptic functions, such as scipy.special.ellipj() (Jacobi elliptic functions).
Both the numerator and denominator overflow, so performing 𝑎/𝑏 will not return the result we seek.
Other special functions are combinations of familiar elementary functions, but they offer better accuracy However, the magnitude of the result should be moderate, so the use of logarithms comes to mind.
or robustness than their naive implementations would. Combining the identities log(𝑎/𝑏) = log(𝑎) − log(𝑏) and exp(log(𝑥)) = 𝑥, we get:
Most of these function are computed elementwise and follow standard NumPy broadcasting rules when
>>> log_a = sp.special.gammaln(500)
the input arrays have different shapes. For example, scipy.special.xlog1py() is mathematically
>>> log_b = sp.special.gammaln(499)
equivalent to 𝑥 log(1 + 𝑦).
>>> log_res = log_a - log_b
>>> res = np.exp(log_res)
(continues on next page)

5.2. Special functions: scipy.special 212 5.2. Special functions: scipy.special 213
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


>>> res >>> U, s, Vh = sp.linalg.svd(A)
499.0000000... >>> s # singular values
array([4.23606798, 0.23606798])
Similarly, suppose we wish to compute the difference log(Γ(500) − Γ(499)). For this, we use scipy.
special.logsumexp(), which computes log(exp(𝑥)+exp(𝑦)) using a numerical trick that avoids overflow. The original matrix can be recovered by matrix multiplication of the factors:

>>> res = sp.special.logsumexp([log_a, log_b], >>> S = np.diag(s) # convert to diagonal matrix before matrix multiplication
... b=[1, -1]) # weights the terms of the sum >>> A2 = U @ S @ Vh
>>> res >>> np.allclose(A2, A)
2605.113844343... True
>>> A3 = (U * s) @ Vh # more efficient: use array math broadcasting rules!
For more information about these and many other special functions, see the documentation of scipy. >>> np.allclose(A3, A)
special. True

Many other decompositions (e.g. LU, Cholesky, QR), solvers for structured linear systems (e.g. triangu-
5.3 Linear algebra operations: scipy.linalg lar, circulant), eigenvalue problem algorithms, matrix functions (e.g. matrix exponential), and routines
for special matrix creation (e.g. block diagonal, toeplitz) are available in scipy.linalg.
scipy.linalg provides a Python interface to efficient, compiled implementations of standard linear alge-
bra operations: the BLAS (Basic Linear Algebra Subroutines) and LAPACK (Linear Algebra PACKage)
libraries. 5.4 Interpolation: scipy.interpolate
For example, the scipy.linalg.det() function computes the determinant of a square matrix:
scipy.interpolate is used for fitting a function – an “interpolant” – to experimental or computed data.
>>> import scipy as sp Once fit, the interpolant can be used to approximate the underlying function at intermediate points; it
>>> arr = np.array([[1, 2], can also be used to compute the integral, derivative, or inverse of the function.
... [3, 4]]) Some kinds of interpolants, known as “smoothing splines”, are designed to generate smooth curves from
>>> sp.linalg.det(arr) noisy data. For example, suppose we have the following data:
-2.0
>>> rng = np.random.default_rng(27446968)
Mathematically, the solution of a linear system 𝐴𝑥 = 𝑏 is 𝑥 = 𝐴−1 𝑏, but explicit inversion of a matrix is >>> measured_time = np.linspace(0, 2*np.pi, 20)
numerically unstable and should be avoided. Instead, use scipy.linalg.solve(): >>> function = np.sin(measured_time)
>>> noise = rng.normal(loc=0, scale=0.1, size=20)
>>> A = np.array([[1, 2], >>> measurements = function + noise
... [2, 3]])
>>> b = np.array([14, 23]) scipy.interpolate.make_smoothing_spline() can be used to form a curve similar to the underlying
>>> x = sp.linalg.solve(A, b) sine function.
>>> x
array([4., 5.]) >>> smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time,␣
>>> np.allclose(A @ x, b) ˓→measurements)

True >>> interpolation_time = np.linspace(0, 2*np.pi, 200)


>>> smooth_results = smoothing_spline(interpolation_time)
Linear systems with special structure can often be solved more efficiently than more general systems. For
example, systems with triangular matrices can be solved using scipy.linalg.solve_triangular():

>>> A_upper = np.triu(A)


>>> A_upper
array([[1, 2],
[0, 3]])
>>> np.allclose(sp.linalg.solve_triangular(A_upper, b, lower=False),
... sp.linalg.solve(A_upper, b))
True

scipy.linalg also features matrix factorizations/decompositions such as the singular value decomposi-
tion.

>>> A = np.array([[1, 2],


... [2, 3]])
(continues on next page)

5.3. Linear algebra operations: scipy.linalg 214 5.4. Interpolation: scipy.interpolate 215
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

On the other hand, if the data are not noisy, it may be desirable to pass exactly through each point. 5.5 Optimization and fit: scipy.optimize
>>> interp_spline = sp.interpolate.make_interp_spline(measured_time, function)
>>> interp_results = interp_spline(interpolation_time) scipy.optimize provides algorithms for root finding, curve fitting, and more general optimization.

5.5.1 Root Finding

scipy.optimize.root_scalar() attempts to find a root of a specified scalar-valued function (i.e., an


argument at which the function value is zero). Like many scipy.optimize functions, the function needs
an initial guess of the solution, which the algorithm will refine until it converges or recognizes failure.
We also provide the derivative to improve the rate of convergence.

>>> def f(x):


... return (x-1)*(x-2)
>>> def df(x):
... return 2*x - 3
>>> x0 = 0 # guess
>>> res = sp.optimize.root_scalar(f, x0=x0, fprime=df)
>>> res
converged: True
The derivative and antiderivative methods of the result object can be used for differentiation and flag: converged
integration. For the latter, the constant of integration is assumed to be zero, but we can “wrap” the function_calls: 12
antiderivative to include a nonzero constant of integration. iterations: 6
>>> d_interp_spline = interp_spline.derivative() root: 1.0
>>> d_interp_results = d_interp_spline(interpolation_time) method: newton
>>> i_interp_spline = lambda t: interp_spline.antiderivative()(t) - 1
>>> i_interp_results = i_interp_spline(interpolation_time)
Warning: None of the functions in scipy.optimize that accept a guess are guaranteed to converge
for all possible guesses! (For example, try x0=1.5 in the example above, where the derivative of
the function is exactly zero.) If this occurs, try a different guess, adjust the options (like providing
a bracket as shown below), or consider whether SciPy offers a more appropriate method for the
problem.

Note that only one the root at 1.0 is found. By inspection, we can tell that there is a second root at
2.0. We can direct the function toward a particular root by changing the guess or by passing a bracket
that contains only the root we seek.

>>> res = sp.optimize.root_scalar(f, bracket=(1.5, 10))


>>> res.root
2.0

For multivariate problems, use scipy.optimize.root().

For functions that are monotonic on an interval (e.g. sin from 𝜋/2 to 3𝜋/2), we can reverse the arguments >>> def f(x):
of make_interp_spline to interpolate the inverse function. Because the first argument is expected to ... # intersection of unit circle and line from origin
be monotonically increasing, we also reverse the order of elements in the arrays with numpy.flip(). ... return [x[0]**2 + x[1]**2 - 1,
... x[1] - x[0]]
>>> i = (measured_time > np.pi/2) & (measured_time < 3*np.pi/2) >>> res = sp.optimize.root(f, x0=[0, 0])
>>> inverse_spline = sp.interpolate.make_interp_spline(np.flip(function[i]), >>> np.allclose(f(res.x), 0, atol=1e-10)
... np.flip(measured_time[i])) True
>>> inverse_spline(0) >>> np.allclose(res.x, np.sqrt(2)/2)
array(3.14159265) True

See the summary exercise on Maximum wind speed prediction at the Sprogø station for a more advanced Over-constrained problems can be solved in the least-squares sense using scipy.optimize.root() with
spline interpolation example, and read the SciPy interpolation tutorial and the scipy.interpolate method='lm' (Levenberg-Marquardt).
documentation for much more information.

5.4. Interpolation: scipy.interpolate 216 5.5. Optimization and fit: scipy.optimize 217
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> def f(x): >>> params, _ = sp.optimize.curve_fit(f, x, y, p0=[2, 1, 3])


... # intersection of unit circle, line from origin, and parabola >>> params
... return [x[0]**2 + x[1]**2 - 1, array([2.900026 , 1.50012043, 1.57079633])
... x[1] - x[0], >>> ref = [a, b, np.pi/2] # what we'd expect
... x[1] - x[0]**2] >>> np.allclose(params, ref, rtol=1e-3)
>>> res = sp.optimize.root(f, x0=[1, 1], method='lm') True
>>> res.success
True
>>> res.x Exercise: Curve fitting of temperature data
array([0.76096066, 0.66017736])
The temperature extremes in Alaska for each month, starting in January, are given by (in
See the documentation of scipy.optimize.root_scalar() and scipy.optimize.root() for a variety degrees Celsius):
of other solution algorithms and options.
max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18
min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58
5.5.2 Curve fitting 1. Plot these temperature extremes.
2. Define a function that can describe min and max temperatures. Hint: this function
has to have a period of 1 year. Hint: include a time offset.
3. Fit this function to the data with scipy.optimize.curve_fit().
4. Plot the result. Is the fit reasonable? If not, why?
5. Is the time offset for min and max temperatures the same within the fit accuracy?
solution

5.5.3 Optimization

Suppose we have data that is sinusoidal but noisy:

>>> x = np.linspace(-5, 5, num=50) # 50 values between -5 and 5


>>> noise = 0.01 * np.cos(100 * x)
>>> a, b = 2.9, 1.5
>>> y = a * np.cos(b * x) + noise

We can approximate the underlying amplitude, frequency, and phase from the data by least squares
curve fitting. To begin, we write a function that accepts the independent variable as the first argument
and all parameters to fit as separate arguments:

>>> def f(x, a, b, c):


... return a * np.sin(b * x + c)

Suppose we wish to minimize the scalar-valued function of a single variable 𝑓 (𝑥) = 𝑥2 + 10 sin(𝑥):

>>> def f(x):


... return x**2 + 10*np.sin(x)
>>> x = np.arange(-5, 5, 0.1)
>>> plt.plot(x, f(x))
[<matplotlib.lines.Line2D object at ...>]
>>> plt.show()

We can see that the function has a local minimizer near 𝑥 = 3.8 and a global minimizer near 𝑥 = −1.3,
but the precise values cannot be determined from the plot.
We then use scipy.optimize.curve_fit() to find 𝑎 and 𝑏: The most appropriate function for this purpose is scipy.optimize.minimize_scalar(). Since we know

5.5. Optimization and fit: scipy.optimize 218 5.5. Optimization and fit: scipy.optimize 219
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

the approximate locations of the minima, we will provide bounds that restrict the search to the vicinity This barely scratches the surface of SciPy’s optimization features, which include mixed integer linear
of the global minimum. programming, constrained nonlinear programming, and the solution of assignment problems. For much
more information, see the documentation of scipy.optimize and the advanced chapter Mathematical
>>> res = sp.optimize.minimize_scalar(f, bounds=(-2, -1)) optimization: finding minima of functions.
>>> res
message: Solution found.
success: True Exercise: 2-D minimization
status: 0
fun: -7.9458233756...
x: -1.306440997...
nit: 8
nfev: 8
>>> res.fun == f(res.x)
True

If we did not already know the approximate location of the global minimum, we could use one of
SciPy’s global minimizers, such as scipy.optimize.differential_evolution(). We are required to
pass bounds, but they do not need to be tight.

>>> bounds=[(-5, 5)] # list of lower, upper bound for each variable
>>> res = sp.optimize.differential_evolution(f, bounds=bounds)
>>> res
message: Optimization terminated successfully.
success: True The six-hump camelback function
fun: -7.9458233756...
x: [-1.306e+00] 𝑥4 2
𝑓 (𝑥, 𝑦) = (4 − 2.1𝑥2 + )𝑥 + 𝑥𝑦 + (4𝑦 2 − 4)𝑦 2
nit: 6 3
nfev: 111
has multiple local minima. Find a global minimum (there is more than one, each with the
jac: [ 9.948e-06]
same value of the objective function) and at least one other local minimum.
For multivariate optimization, a good choice for many problems is scipy.optimize.minimize(). Sup- Hints:
pose we wish to find the minimum of a quadratic function of two variables, 𝑓 (𝑥0 , 𝑥1 ) = (𝑥0 −1)2 +(𝑥1 −2)2 . • Variables can be restricted to −2 < 𝑥 < 2 and −1 < 𝑦 < 1.
>>> def f(x): • numpy.meshgrid() and matplotlib.pyplot.imshow() can help with visualization.
... return (x[0] - 1)**2 + (x[1] - 2)**2
• Try minimizing with scipy.optimize.minimize() with an initial guess of (𝑥, 𝑦) =
(0, 0). Does it find the global minimum, or converge to a local minimum? What about
Like scipy.optimize.root(), scipy.optimize.minimize() requires a guess x0. (Note that this is the
other initial guesses?
initial value of both variables rather than the value of the variable we happened to label 𝑥0 .)
• Try minimizing with scipy.optimize.differential_evolution().
>>> res = sp.optimize.minimize(f, x0=[0, 0])
>>> res solution
message: Optimization terminated successfully.
success: True See the summary exercise on Non linear least squares curve fitting: application to point extraction in
status: 0 topographical lidar data for another, more advanced example.
fun: 1.70578...e-16
x: [ 1.000e+00 2.000e+00]
nit: 2
jac: [ 3.219e-09 -8.462e-09]
hess_inv: [[ 9.000e-01 -2.000e-01]
[-2.000e-01 6.000e-01]]
nfev: 9
njev: 3

Maximization?

Is scipy.optimize.minimize() restricted to the solution of minimization problems? Nope! To solve


a maximization problem, simply minimize the negative of the original objective function.

5.5. Optimization and fit: scipy.optimize 220 5.5. Optimization and fit: scipy.optimize 221
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.6 Statistics and random numbers: scipy.stats (continued from previous page)
>>> scale
0.9973396878...
scipy.stats contains fundamental tools for statistics in Python.
Since we know the true parameters of the distribution from which the sample was drawn, we are not
5.6.1 Statistical Distributions surprised that these estimates are similar.

Consider a random variable distributed according to the standard normal. We draw a sample consisting Exercise: Probability distributions
of 100000 observations from the random variable. The normalized histogram of the sample is an estimator
of the random variable’s probability density function (PDF): Generate 1000 random variates from a gamma distribution with a shape parameter of 1. Hint: the
>>> dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution shape parameter is passed as the first argument when freezing the distribution. Plot the histogram of
>>> sample = dist.rvs(size=100000) # "random variate sample" the sample, and overlay the distribution’s PDF. Estimate the shape parameter from the sample using
>>> plt.hist(sample, bins=50, density=True, label='normalized histogram') the fit method.
>>> x = np.linspace(-5, 5) Extra: the distributions have many useful methods. Explore them using tab completion. Plot the
>>> plt.plot(x, dist.pdf(x), label='PDF') cumulative density function of the distribution, and compute the variance.
[<matplotlib.lines.Line2D object at ...>]
>>> plt.legend()
<matplotlib.legend.Legend object at ...>
5.6.2 Sample Statistics and Hypothesis Tests

The sample mean is an estimator of the mean of the distribution from which the sample was drawn:

>>> np.mean(sample)
0.001576700508...

NumPy includes some of the most fundamental sample statistics (e.g. numpy.mean(), numpy.var(),
numpy.percentile()); scipy.stats includes many more. For instance, the geometric mean is a common
measure of central tendency for data that tends to be distributed over many orders of magnitude.

>>> sp.stats.gmean(2**sample)
1.0010934829...

SciPy also includes a variety of hypothesis tests that produce a sample statistic and a p-value. For
instance, suppose we wish to test the null hypothesis that sample was drawn from a normal distribution:

>>> res = sp.stats.normaltest(sample)


>>> res.statistic
5.20841759...
>>> res.pvalue
0.07396163283...

Here, statistic is a sample statistic that tends to be high for samples that are drawn from non-normal
Distribution objects and frozen distributions
distributions. pvalue is the probability of observing such a high value of the statistic for a sample
that has been drawn from a normal distribution. If the p-value is unusually small, this may be taken
Each of the 100+ scipy.stats distribution families is represented by an object with a __call__
as evidence that sample was not drawn from the normal distribution. Our statistic and p-value are
method. Here, we call the scipy.stats.norm object to specify its location and scale, and it returns a
moderate, so the test is inconclusive.
frozen distribution: a particular element of a distribution family with all parameters fixed. The frozen
distribution object has methods to compute essential functions of the particular distribution. There are many other features of scipy.stats, including circular statistics, quasi-Monte Carlo methods,
and resampling methods. For much more information, see the documentation of scipy.stats and the
advanced chapter statistics.
Suppose we knew that the sample had been drawn from a distribution belonging to the family of normal
distributions, but we did not know the particular distribution’s location (mean) and scale (standard
deviation). We perform maximum likelihood estimation of the unknown parameters using the distribution
family’s fit method:

>>> loc, scale = sp.stats.norm.fit(sample)


>>> loc
0.0015767005...
(continues on next page)

5.6. Statistics and random numbers: scipy.stats 222 5.6. Statistics and random numbers: scipy.stats 223
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.7 Numerical integration: scipy.integrate

5.7.1 Quadrature
∫︀ 𝜋/2
Suppose we wish to compute the definite integral 0 sin(𝑡)𝑑𝑡 numerically. scipy.integrate.quad()
chooses one of several adaptive techniques depending on the parameters, and is therefore the recom-
mended first choice for integration of function of a single variable:

>>> integral, error_estimate = sp.integrate.quad(np.sin, 0, np.pi/2)


>>> np.allclose(integral, 1) # numerical result ~ analytical result
True
>>> abs(integral - 1) < error_estimate # actual error < estimated error
True Let us integrate a more complex ODE: a damped spring-mass oscillator. The position of√︀ a mass attached
to a spring obeys the 2nd order ODE 𝑦¨ + 2𝜁𝜔0 𝑦˙ + 𝜔02 𝑦 = 0 with natural frequency 𝜔0 = 𝑘/𝑚, damping
Other functions for numerical quadrature, including integration of multivariate functions and approxi- ratio 𝜁 = 𝑐/(2𝑚𝜔0 ), spring constant 𝑘, mass 𝑚, and damping coefficient 𝑐.
mating integrals from samples, are available in scipy.integrate.
Before using scipy.integrate.solve_ivp(), the 2nd order ODE needs to be transformed into a system
of first-order ODEs. Note that
5.7.2 Initial Value Problems 𝑑𝑦 𝑑𝑦˙
= 𝑦˙ = 𝑦¨ = −(2𝜁𝜔0 𝑦˙ + 𝜔02 𝑦)
𝑑𝑡 𝑑𝑡
scipy.integrate also features routines for integrating Ordinary Differential Equations (ODE). For
example, scipy.integrate.solve_ivp() integrates ODEs of the form: If we define 𝑧 = [𝑧0 , 𝑧1 ] where 𝑧0 = 𝑦 and 𝑧1 = 𝑦,˙ then the first order equation:
[︂ 𝑑𝑧0 ]︂ [︂ ]︂
𝑑𝑦 𝑑𝑧 𝑑𝑡 𝑧1
= 𝑓 (𝑡, 𝑦(𝑡)) = 𝑑𝑧 = 2
𝑑𝑡 𝑑𝑡 1
𝑑𝑡
−(2𝜁𝜔0 𝑧1 + 𝜔0 𝑧0 )

from an initial time 𝑡0 and initial state 𝑦(𝑡 = 𝑡0 ) = 𝑡0 to a final time 𝑡𝑓 or until an event occurs (e.g. a is equivalent to the original second order equation.
specified state is reached).
We set:
As an introduction, consider the initial value problem given by 𝑑𝑦 𝑑𝑡 = −2𝑦 and the initial condition
𝑦(𝑡 = 0) = 1 on the interval 𝑡 = 0 . . . 4. We begin by defining a callable that computes 𝑓 (𝑡, 𝑦(𝑡)) given >>> m = 0.5 # kg
the current time and state. >>> k = 4 # N/m
>>> c = 0.4 # N s/m
>>> def f(t, y): >>> zeta = c / (2 * m * np.sqrt(k/m))
... return -2 * y >>> omega = np.sqrt(k / m)

Then, to compute y as a function of time: and define the function that computes 𝑧˙ = 𝑓 (𝑡, 𝑧(𝑡)):

>>> t_span = (0, 4) # time interval >>> def f(t, z, zeta, omega):
>>> t_eval = np.linspace(*t_span) # times at which to evaluate `y` ... return (z[1], -2.0 * zeta * omega * z[1] - omega**2 * z[0])
>>> y0 = [1,] # initial state
>>> res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval)

and plot the result:

>>> plt.plot(res.t, res.y[0])


[<matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel('t')
Text(0.5, ..., 't')
>>> plt.ylabel('y')
Text(..., 0.5, 'y')
>>> plt.title('Solution of Initial Value Problem')
Text(0.5, 1.0, 'Solution of Initial Value Problem')

Integration of the system follows:

>>> t_span = (0, 10)


>>> t_eval = np.linspace(*t_span, 100)
(continues on next page)

5.7. Numerical integration: scipy.integrate 224 5.7. Numerical integration: scipy.integrate 225
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> z0 = [1, 0]
>>> res = sp.integrate.solve_ivp(f, t_span, z0, t_eval=t_eval,
... args=(zeta, omega), method='LSODA')

Tip: With the option method=’LSODA’, scipy.integrate.solve_ivp() uses the LSODA (Liver-
more Solver for Ordinary Differential equations with Automatic method switching for stiff and non-stiff
problems). See the ODEPACK Fortran library for more details.

See also:
Partial Differental Equations
There is no Partial Differential Equations (PDE) solver in SciPy. Some Python packages for solving
PDE’s are available, such as fipy or SfePy.

5.8 Fast Fourier transforms: scipy.fft


Setting the Fourier component above this frequency to zero and inverting the FFT with scipy.fft.
ifft(), gives a filtered signal.
The scipy.fft module computes fast Fourier transforms (FFTs) and offers utilities to handle them.
Some important functions are:
Note: The code of this example can be found here
• scipy.fft.fft() to compute the FFT
• scipy.fft.fftfreq() to generate the sampling frequencies
• scipy.fft.ifft() to compute the inverse FFT, from frequency space to signal space numpy.fft

NumPy also has an implementation of FFT (numpy.fft). However, the SciPy one should be preferred,
as it uses more efficient underlying implementations.

As an illustration, a (noisy) input signal (sig), and its FFT:

>>> sig_fft = sp.fft.fft(sig)


>>> freqs = sp.fft.fftfreq(sig.size, d=time_step)
Fully worked examples:

Crude periodicity finding (link) Gaussian image blur (link)

Signal FFT

As the signal comes from a real-valued function, the Fourier transform is symmetric.
The peak signal frequency can be found with freqs[power.argmax()]

5.8. Fast Fourier transforms: scipy.fft 226 5.8. Fast Fourier transforms: scipy.fft 227
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.9 Signal processing: scipy.signal


Exercise: Denoise moon landing image

Tip: scipy.signal is for typical signal processing: 1D, regularly-sampled signals.

Resampling scipy.signal.resample(): resample a signal to n points using FFT.

>>> t = np.linspace(0, 5, 100)


>>> x = np.sin(t)

>>> x_resampled = sp.signal.resample(x, 25)

>>> plt.plot(t, x)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(t[::4], x_resampled, 'ko')
1. Examine the provided image moonlanding.png, which is heavily contaminated with periodic
[<matplotlib.lines.Line2D object at ...>]
noise. In this exercise, we aim to clean up the noise using the Fast Fourier Transform.
2. Load the image using matplotlib.pyplot.imread().
3. Find and use the 2-D FFT function in scipy.fft, and plot the spectrum (Fourier transform of) Tip: Notice how on the side of the window the resampling is less accurate and has a rippling effect.
the image. Do you have any trouble visualising the spectrum? If so, why? This resampling is different from the interpolation provided by scipy.interpolate as it only applies to
4. The spectrum consists of high and low frequency components. The noise is contained in the regularly sampled data.
high-frequency part of the spectrum, so set some of those components to zero (use array slicing).
5. Apply the inverse Fourier transform to see the resulting image.
Solution

Detrending scipy.signal.detrend(): remove linear trend from signal:

5.8. Fast Fourier transforms: scipy.fft 228 5.9. Signal processing: scipy.signal 229
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> t = np.linspace(0, 5, 100) 5.10 Image manipulation: scipy.ndimage


>>> rng = np.random.default_rng()
>>> x = t + rng.normal(size=100) scipy.ndimage provides manipulation of n-dimensional arrays as images.

>>> x_detrended = sp.signal.detrend(x)


5.10.1 Geometrical transformations on images
>>> plt.plot(t, x)
[<matplotlib.lines.Line2D object at ...>] Changing orientation, resolution, ..
>>> plt.plot(t, x_detrended)
[<matplotlib.lines.Line2D object at ...>] >>> import scipy as sp

Filtering: For non-linear filtering, scipy.signal has filtering (median filter scipy.signal.medfilt(), >>> # Load an image
Wiener scipy.signal.wiener()), but we will discuss this in the image section. >>> face = sp.datasets.face(gray=True)

>>> # Shift, rotate and zoom it


Tip: scipy.signal also has a full-blown set of tools for the design of linear filter (finite and infinite >>> shifted_face = sp.ndimage.shift(face, (50, 50))
response filters), but this is out of the scope of this tutorial. >>> shifted_face2 = sp.ndimage.shift(face, (50, 50), mode='nearest')
>>> rotated_face = sp.ndimage.rotate(face, 30)
Spectral analysis: scipy.signal.spectrogram() compute a spectrogram –frequency spectrums over >>> cropped_face = face[50:-50, 50:-50]
consecutive time windows–, while scipy.signal.welch() comptes a power spectrum density (PSD). >>> zoomed_face = sp.ndimage.zoom(face, 2)
>>> zoomed_face.shape
(1536, 2048)

>>> plt.subplot(151)
<Axes: >

>>> plt.imshow(shifted_face, cmap=plt.cm.gray)


<matplotlib.image.AxesImage object at 0x...>

>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5)

>>> # etc.

5.10.2 Image filtering

Generate a noisy face:

>>> import scipy as sp


>>> face = sp.datasets.face(gray=True)
>>> face = face[:512, -512:] # crop out square on right
>>> import numpy as np
>>> noisy_face = np.copy(face).astype(float)
>>> rng = np.random.default_rng()
>>> noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape)

Apply a variety of filters on it:

5.9. Signal processing: scipy.signal 230 5.10. Image manipulation: scipy.ndimage 231
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Erosion scipy.ndimage.binary_erosion()
>>> blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)
>>> median_face = sp.ndimage.median_filter(noisy_face, size=5) >>> a = np.zeros((7, 7), dtype=int)
>>> wiener_face = sp.signal.wiener(noisy_face, (5, 5)) >>> a[1:6, 2:5] = 1
>>> a
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
>>> sp.ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
Other filters in scipy.ndimage.filters and scipy.signal can be applied to images.
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
Exercise [0, 0, 0, 0, 0, 0, 0]])
>>> # Erosion removes objects smaller than the structure
Compare histograms for the different filtered images. >>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
5.10.3 Mathematical morphology [0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
Tip: Mathematical morphology stems from set theory. It characterizes and transforms geometrical [0, 0, 0, 0, 0, 0, 0]])
structures. Binary (black and white) images, in particular, can be transformed using this theory: the
sets to be transformed are the sets of neighboring non-zero-valued pixels. The theory was also extended • Dilation scipy.ndimage.binary_dilation()
to gray-valued images.
>>> a = np.zeros((5, 5))
>>> a[2, 2] = 1
>>> a
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> sp.ndimage.binary_dilation(a).astype(a.dtype)
array([[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 1., 1., 1., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.]])
Mathematical-morphology operations use a structuring element in order to modify geometrical structures.
• Opening scipy.ndimage.binary_opening()
Let us first generate a structuring element:
>>> a = np.zeros((5, 5), dtype=int)
>>> el = sp.ndimage.generate_binary_structure(2, 1)
>>> a[1:4, 1:4] = 1
>>> el
>>> a[4, 4] = 1
array([[False, True, False],
>>> a
[...True, True, True],
array([[0, 0, 0, 0, 0],
[False, True, False]])
[0, 1, 1, 1, 0],
>>> el.astype(int)
[0, 1, 1, 1, 0],
array([[0, 1, 0],
[0, 1, 1, 1, 0],
[1, 1, 1],
[0, 0, 0, 0, 1]])
[0, 1, 0]])
(continues on next page)

5.10. Image manipulation: scipy.ndimage 232 5.10. Image manipulation: scipy.ndimage 233
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


>>> # Opening removes small objects >>> a[4, 4] = 2; a[2, 3] = 1
>>> sp.ndimage.binary_opening(a, structure=np.ones((3, 3))).astype(int) >>> a
array([[0, 0, 0, 0, 0], array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0], [0, 3, 3, 3, 3, 3, 0],
[0, 1, 1, 1, 0], [0, 3, 3, 1, 3, 3, 0],
[0, 1, 1, 1, 0], [0, 3, 3, 3, 3, 3, 0],
[0, 0, 0, 0, 0]]) [0, 3, 3, 3, 2, 3, 0],
>>> # Opening can also smooth corners [0, 3, 3, 3, 3, 3, 0],
>>> sp.ndimage.binary_opening(a).astype(int) [0, 0, 0, 0, 0, 0, 0]])
array([[0, 0, 0, 0, 0], >>> sp.ndimage.grey_erosion(a, size=(3, 3))
[0, 0, 1, 0, 0], array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0]]) [0, 0, 1, 1, 1, 0, 0],
[0, 0, 3, 2, 2, 0, 0],
• Closing: scipy.ndimage.binary_closing() [0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
Exercise

Check that opening amounts to eroding, then dilating. 5.10.4 Connected components and measurements on images

Let us first generate a nice synthetic binary image.


An opening operation removes small structures, while a closing operation fills small holes. Such opera-
tions can therefore be used to “clean” an image. >>> x, y = np.indices((100, 100))
>>> sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2
>>> a = np.zeros((50, 50)) >>> mask = sig > 1
>>> a[10:-10, 10:-10] = 1
>>> rng = np.random.default_rng()
>>> a += 0.25 * rng.standard_normal(a.shape)
>>> mask = a>=0.5
>>> opened_mask = sp.ndimage.binary_opening(mask)
>>> closed_mask = sp.ndimage.binary_closing(opened_mask)

Exercise

Check that the area of the reconstructed square is smaller than the area of the initial
square. (The opposite would occur if the closing step was performed before the opening).

For gray-valued images, eroding (resp. dilating) amounts to replacing a pixel by the minimal (resp.
maximal) value among pixels covered by the structuring element centered on the pixel of interest.

>>> a = np.zeros((7, 7), dtype=int) scipy.ndimage.label() assigns a different label to each connected component:
>>> a[1:6, 1:6] = 3
(continues on next page)

5.10. Image manipulation: scipy.ndimage 234 5.10. Image manipulation: scipy.ndimage 235
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> labels, nb = sp.ndimage.label(mask)


5.11.1 Maximum wind speed prediction at the Sprogø station
>>> nb
The exercise goal is to predict the maximum wind speed occurring every 50 years even if no measure
8
exists for such a period. The available data are only measured over 21 years at the Sprogø meteorological
station located in Denmark. First, the statistical steps will be given and then illustrated with functions
Now compute measurements on each connected component:
from the scipy.interpolate module. At the end the interested readers are invited to compute results from
>>> areas = sp.ndimage.sum(mask, labels, range(1, labels.max()+1)) raw data and in a slightly different approach.
>>> areas # The number of pixels in each connected component
array([190., 45., 424., 278., 459., 190., 549., 424.]) Statistical approach
>>> maxima = sp.ndimage.maximum(sig, labels, range(1, labels.max()+1))
>>> maxima # The maximum signal in each connected component
The annual maxima are supposed to fit a normal probability density function. However such function
array([ 1.80238238, 1.13527605, 5.51954079, 2.49611818, 6.71673619,
is not going to be estimated because it gives a probability from a wind speed maxima. Finding the
1.80238238, 16.76547217, 5.51954079])
maximum wind speed occurring every 50 years requires the opposite approach, the result needs to be
found from a defined probability. That is the quantile function role and the exercise goal will be to find
it. In the current model, it is supposed that the maximum wind speed occurring every 50 years is defined
as the upper 2% quantile.
By definition, the quantile function is the inverse of the cumulative distribution function. The latter
describes the probability distribution of an annual maxima. In the exercise, the cumulative probability
p_i for a given year i is defined as p_i = i/(N+1) with N = 21, the number of measured years. Thus
it will be possible to calculate the cumulative probability of every measured wind speed maxima. From
those experimental points, the scipy.interpolate module will be very useful for fitting the quantile function.
Finally the 50 years maxima is going to be evaluated from the cumulative probability of the 2% quantile.

Computing the cumulative probabilities

The annual wind speeds maxima have already been computed and saved in the NumPy format in the
Extract the 4th connected component, and crop the array around it: file examples/max-speeds.npy, thus they will be loaded by using NumPy:
>>> sp.ndimage.find_objects(labels)[3] >>> import numpy as np
(slice(30, 48, None), slice(30, 48, None)) >>> max_speeds = np.load('intro/scipy/summary-exercises/examples/max-speeds.npy')
>>> sl = sp.ndimage.find_objects(labels)[3] >>> years_nb = max_speeds.shape[0]
>>> import matplotlib.pyplot as plt
>>> plt.imshow(sig[sl]) Following the cumulative probability definition p_i from the previous section, the corresponding values
<matplotlib.image.AxesImage object at ...> will be:

See the summary exercise on Image processing application: counting bubbles and unmolten grains for a >>> cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1)
more advanced example.
and they are assumed to fit the given wind speeds:

5.11 Summary exercises on scientific computing >>> sorted_max_speeds = np.sort(max_speeds)

The summary exercises use mainly NumPy, SciPy and Matplotlib. They provide some real-life examples
Prediction with UnivariateSpline
of scientific computing with Python. Now that the basics of working with NumPy and SciPy have been
introduced, the interested user is invited to try these exercises.
In this section the quantile function will be estimated by using the UnivariateSpline class which can
represent a spline from points. The default behavior is to build a spline of degree 3 and points can
have different weights according to their reliability. Variants are InterpolatedUnivariateSpline and
LSQUnivariateSpline on which errors checking is going to change. In case a 2D spline is wanted, the
BivariateSpline class family is provided. All those classes for 1D and 2D splines use the FITPACK
Fortran subroutines, that’s why a lower library access is available through the splrep and splev functions
for respectively representing and evaluating a spline. Moreover interpolation functions without the use
of FITPACK parameters are also provided for simpler use.
For the Sprogø maxima wind speeds, the UnivariateSpline will be used because a spline of degree 3
seems to correctly fit the data:

5.11. Summary exercises on scientific computing 236 5.11. Summary exercises on scientific computing 237
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise with the Gumbell distribution


>>> import scipy as sp
>>> quantile_func = sp.interpolate.UnivariateSpline(cprob, sorted_max_speeds)
The interested readers are now invited to make an exercise by using the wind speeds measured over 21
years. The measurement period is around 90 minutes (the original period was around 10 minutes but the
The quantile function is now going to be evaluated from the full range of probabilities:
file size has been reduced for making the exercise setup easier). The data are stored in NumPy format
>>> nprob = np.linspace(0, 1, 100) inside the file examples/sprog-windspeeds.npy. Do not look at the source code for the plots until you
>>> fitted_max_speeds = quantile_func(nprob) have completed the exercise.
• The first step will be to find the annual maxima by using NumPy and plot them as a matplotlib
In the current model, the maximum wind speed occurring every 50 years is defined as the upper 2% bar figure.
quantile. As a result, the cumulative probability value will be:

>>> fifty_prob = 1. - 0.02

So the storm wind speed occurring every 50 years can be guessed by:

>>> fifty_wind = quantile_func(fifty_prob)


>>> fifty_wind
array(32.97989825...)

The results are now gathered on a Matplotlib figure:

Fig. 2: Solution: Python source file

• The second step will be to use the Gumbell distribution on cumulative probabilities p_i defined as
-log( -log(p_i) ) for fitting a linear quantile function (remember that you can define the degree
of the UnivariateSpline). Plotting the annual maxima versus the Gumbell distribution should
give you the following figure.
• The last step will be to find 34.23 m/s for the maximum wind speed occurring every 50 years.

Fig. 1: Solution: Python source file

5.11. Summary exercises on scientific computing 238 5.11. Summary exercises on scientific computing 239
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.11.2 Non linear least squares curve fitting: application to point extraction in
topographical lidar data

The goal of this exercise is to fit a model to some data. The data used in this tutorial are lidar data
and are described in details in the following introductory paragraph. If you’re impatient and want to
practice now, please skip it and go directly to Loading and visualization.

Introduction

Lidars systems are optical rangefinders that analyze property of scattered light to measure distances.
Most of them emit a short light impulsion towards a target and record the reflected signal. This signal
is then processed to extract the distance between the lidar system and the target.
Topographical lidar systems are such systems embedded in airborne platforms. They measure distances
between the platform and the Earth, so as to deliver information on the Earth’s topography (see1 for
more details).
In this tutorial, the goal is to analyze the waveform recorded by the lidar system2 . Such a signal
contains peaks whose center and amplitude permit to compute the position and some characteristics of
the hit target. When the footprint of the laser beam is around 1m on the Earth surface, the beam can
hit multiple targets during the two-way propagation (for example the ground and the top of a tree or
building). The sum of the contributions of each target hit by the laser beam then produces a complex
signal with multiple peaks, each one containing information about one target.
One state of the art method to extract information from these data is to decompose them in a sum of
Gaussian functions where each function represents the contribution of a target hit by the laser beam.
Therefore, we use the scipy.optimize module to fit a waveform to one or a sum of Gaussian functions.

Loading and visualization

Load the first waveform using:

>>> import numpy as np


>>> waveform_1 = np.load('intro/scipy/summary-exercises/examples/waveform_1.npy')

and visualize it:

>>> import matplotlib.pyplot as plt


>>> t = np.arange(len(waveform_1))
>>> plt.plot(t, waveform_1)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.show()

Fig. 3: Solution: Python source file As shown below, this waveform is a 80-bin-length signal with a single peak with an amplitude of ap-
proximately 30 in the 15 nanosecond bin. Additionally, the base level of noise is approximately 3. These
values can be used in the initial solution.
1 Mallet, C. and Bretar, F. Full-Waveform Topographic Lidar: State-of-the-Art. ISPRS Journal of Photogrammetry

and Remote Sensing 64(1), pp.1-16, January 2009 http://dx.doi.org/10.1016/j.isprsjprs.2008.09.007


2 The data used for this tutorial are part of the demonstration data available for the FullAnalyze software and were

kindly provided by the GIS DRAIX.

5.11. Summary exercises on scientific computing 240 5.11. Summary exercises on scientific computing 241
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• coeffs[3] is 𝜎 (width)

Initial solution

One possible initial solution that we determine by inspection is:

>>> x0 = np.array([3, 30, 15, 1], dtype=float)

Fit

scipy.optimize.leastsq minimizes the sum of squares of the function given as an argument. Basically,
the function to minimize is the residuals (the difference between the data and the model):

>>> def residuals(coeffs, y, t):


... return y - model(t, coeffs)

So let’s get our solution by calling scipy.optimize.leastsq() with the following arguments:
• the function to minimize
• an initial solution
• the additional arguments to pass to the function

>>> import scipy as sp


>>> t = np.arange(len(waveform_1))
>>> x, flag = sp.optimize.leastsq(residuals, x0, args=(waveform_1, t))
>>> x
array([ 2.70363, 27.82020, 15.47924, 3.05636])
Fitting a waveform with a simple Gaussian model
And visualize the solution:
The signal is very simple and can be modeled as a single Gaussian function and an offset corresponding fig, ax = plt.subplots(figsize=(8, 6))
to the background noise. To fit the signal with the function, we must: plt.plot(t, waveform_1, t, model(t, x))
• define the model plt.xlabel("Time [ns]")
plt.ylabel("Amplitude [bins]")
• propose an initial solution plt.legend(["Waveform", "Model"])
• call scipy.optimize.leastsq plt.show()

Remark: from scipy v0.8 and above, you should rather use scipy.optimize.curve_fit() which takes
Model the model and the data as arguments, so you don’t need to define the residuals any more.

A Gaussian function defined by Going further


{︃ (︂ )︂2 }︃
𝑡−𝜇
𝐵 + 𝐴 exp − • Try with a more complex waveform (for instance waveform_2.npy) that contains three significant
𝜎 peaks. You must adapt the model which is now a sum of Gaussian functions instead of only one
Gaussian peak.
can be defined in python by:
• In some cases, writing an explicit function to compute the Jacobian is faster than letting leastsq
>>> def model(t, coeffs): estimate it numerically. Create a function to compute the Jacobian of the residuals and use it as
... return coeffs[0] + coeffs[1] * np.exp( - ((t-coeffs[2])/coeffs[3])**2 ) an input for leastsq.
• When we want to detect very small peaks in the signal, or when the initial guess is too far from a
where
good solution, the result given by the algorithm is often not satisfying. Adding constraints to the
• coeffs[0] is 𝐵 (noise) parameters of the model enables to overcome such limitations. An example of a priori knowledge
we can add is the sign of our variables (which are all positive).
• coeffs[1] is 𝐴 (amplitude)
• See the solution.
• coeffs[2] is 𝜇 (center)

5.11. Summary exercises on scientific computing 242 5.11. Summary exercises on scientific computing 243
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Further exercise: compare the result of scipy.optimize.leastsq() and what you can get with
scipy.optimize.fmin_slsqp() when adding boundary constraints.

5.11.3 Image processing application: counting bubbles and unmolten grains

Statement of the problem

1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments
in the docstring of imshow to display the image with the “right” orientation (origin in the bottom
left corner, and not the upper left corner as for standard arrays).
This Scanning Element Microscopy image shows a glass sample (light gray matrix) with some
bubbles (on black) and unmolten sand grains (dark gray). We wish to determine the fraction
of the sample covered by these three phases, and to estimate the typical size of sand grains and
bubbles, their sizes, etc.
2. Crop the image to remove the lower panel with measure information.
3. Slightly filter the image with a median filter in order to refine its histogram. Check how the
histogram changes.

5.11. Summary exercises on scientific computing 244 5.11. Summary exercises on scientific computing 245
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand 2. Crop the image to remove the lower panel with measure information.
pixels, glass pixels and bubble pixels. Other option (homework): write a function that determines
automatically the thresholds from the minima of the histogram. >>> dat = dat[:-60]

5. Display an image in which the three phases are colored with three different colors. 3. Slightly filter the image with a median filter in order to refine its histogram. Check how the
6. Use mathematical morphology to clean the different phases. histogram changes.

7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are >>> filtdat = sp.ndimage.median_filter(dat, size=(7,7))
smaller than 10 pixels. To do so, use ndimage.sum or np.bincount to compute the grain sizes. >>> hi_dat = np.histogram(dat, bins=np.arange(256))
>>> hi_filtdat = np.histogram(filtdat, bins=np.arange(256))
8. Compute the mean size of bubbles.

5.11.4 Example of solution for the image processing exercise: unmolten grains in
glass

4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand
pixels, glass pixels and bubble pixels. Other option (homework): write a function that determines
automatically the thresholds from the minima of the histogram.

>>> void = filtdat <= 50


>>> sand = np.logical_and(filtdat > 50, filtdat <= 114)
>>> glass = filtdat > 114

5. Display an image in which the three phases are colored with three different colors.

>>> phases = void.astype(int) + 2*glass.astype(int) + 3*sand.astype(int)

1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments
in the docstring of imshow to display the image with the “right” orientation (origin in the bottom
left corner, and not the upper left corner as for standard arrays).

>>> dat = plt.imread('data/MV_HFV_012.jpg')

5.11. Summary exercises on scientific computing 246 5.11. Summary exercises on scientific computing 247
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> mean_bubble_size, median_bubble_size
(1699.875, 65.0)

5.12 Full code examples for the SciPy chapter

5.12.1 Finding the minimum of a smooth function

Demos various methods to find the minimum of a function.

import numpy as np
import matplotlib.pyplot as plt

def f(x):
return x**2 + 10 * np.sin(x)

x = np.arange(-5, 5, 0.1)
plt.plot(x, f(x))

6. Use mathematical morphology to clean the different phases.

>>> sand_op = sp.ndimage.binary_opening(sand, iterations=2)

7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are
smaller than 10 pixels. To do so, use sp.ndimage.sum or np.bincount to compute the grain sizes.

>>> sand_labels, sand_nb = sp.ndimage.label(sand_op)


>>> sand_areas = np.array(sp.ndimage.sum(sand_op, sand_labels, np.arange(sand_
˓→labels.max()+1)))

>>> mask = sand_areas > 100


>>> remove_small_sand = mask[sand_labels.ravel()].reshape(sand_labels.shape)

8. Compute the mean size of bubbles.

>>> bubbles_labels, bubbles_nb = sp.ndimage.label(void)


>>> bubbles_areas = np.bincount(bubbles_labels.ravel())[1:] [<matplotlib.lines.Line2D object at 0x7f49548eef90>]
>>> mean_bubble_size = bubbles_areas.mean()
>>> median_bubble_size = np.median(bubbles_areas) Now find the minimum with a few methods
(continues on next page)

5.11. Summary exercises on scientific computing 248 5.12. Full code examples for the SciPy chapter 249
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

import scipy as sp

# The default (Nelder Mead)


print(sp.optimize.minimize(f, x0=0))

message: Optimization terminated successfully.


success: True
status: 0
fun: -7.945823375615215
x: [-1.306e+00]
nit: 5
jac: [-1.192e-06]
hess_inv: [[ 8.589e-02]]
nfev: 12
njev: 6

plt.show()

Total running time of the script: (0 minutes 0.043 seconds)

5.12.2 Resample a signal with scipy.signal.resample


Total running time of the script: (0 minutes 0.219 seconds)
scipy.signal.resample() uses FFT to resample a 1D signal.
Generate a signal with 100 data point

import numpy as np 5.12.3 Detrending a signal


t = np.linspace(0, 5, 100) scipy.signal.detrend() removes a linear trend.
x = np.sin(t)
Generate a random signal with a trend
Downsample it by a factor of 4
import numpy as np
import scipy as sp
t = np.linspace(0, 5, 100)
x_resampled = sp.signal.resample(x, 25) rng = np.random.default_rng()
x = t + rng.normal(size=100)
Plot
Detrend
import matplotlib.pyplot as plt
import scipy as sp
plt.figure(figsize=(5, 4))
plt.plot(t, x, label="Original signal") x_detrended = sp.signal.detrend(x)
plt.plot(t[::4], x_resampled, "ko", label="Resampled signal")
Plot
plt.legend(loc="best")
import matplotlib.pyplot as plt
plt.show()
plt.figure(figsize=(5, 4))
plt.plot(t, x, label="x")
plt.plot(t, x_detrended, label="x_detrended")
plt.legend(loc="best")
plt.show()

5.12. Full code examples for the SciPy chapter 250 5.12. Full code examples for the SciPy chapter 251
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


def f(t, y):
return -2 * y

t_span = (0, 4) # time interval


t_eval = np.linspace(*t_span) # times at which to evaluate `y`
y0 = [
1,
] # initial state
res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval)

plt.figure(figsize=(4, 3))
plt.plot(res.t, res.y[0])
plt.xlabel("t")
plt.ylabel("y")
plt.title("Solution of Initial Value Problem")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.088 seconds)

Total running time of the script: (0 minutes 0.049 seconds) 5.12.5 Normal distribution: histogram and PDF

Explore the normal distribution: a histogram built from samples and the PDF (probability density
function).
5.12.4 Integrating a simple ODE

Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition y(t=0) = 1.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

(continues on next page)

5.12. Full code examples for the SciPy chapter 252 5.12. Full code examples for the SciPy chapter 253
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


import numpy as np
import scipy as sp return (z[1], -zeta * omega * z[1] - omega**2 * z[0])
import matplotlib.pyplot as plt

dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution t_span = (0, 10)


sample = dist.rvs(size=100000) # "random variate sample" t_eval = np.linspace(*t_span, 100)
plt.hist( z0 = [1, 0]
sample, res = sp.integrate.solve_ivp(
bins=51, # group the observations into 50 bins f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA"
density=True, # normalize the frequencies )
label="normalized histogram",
) plt.figure(figsize=(4, 3))
plt.plot(res.t, res.y[0], label="y")
x = np.linspace(-5, 5) # possible values of the random variable plt.plot(res.t, res.y[1], label="dy/dt")
plt.plot(x, dist.pdf(x), label="PDF") plt.legend(loc="best")
plt.legend() plt.show()
plt.show()
Total running time of the script: (0 minutes 0.056 seconds)
Total running time of the script: (0 minutes 0.107 seconds)

5.12.7 Comparing 2 sets of samples from Gaussians


5.12.6 Integrate the Damped spring-mass oscillator

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

m = 0.5 # kg
k = 4 # N/m import numpy as np
c = 0.4 # N s/m import matplotlib.pyplot as plt

zeta = c / (2 * m * np.sqrt(k / m)) # Generates 2 sets of observations


omega = np.sqrt(k / m) rng = np.random.default_rng(27446968)
samples1 = rng.normal(0, size=1000)
samples2 = rng.normal(1, size=1000)
def f(t, z, zeta, omega):
(continues on next page) (continues on next page)

5.12. Full code examples for the SciPy chapter 254 5.12. Full code examples for the SciPy chapter 255
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Compute a histogram of the sample
bins = np.linspace(-4, 4, 30)
histogram1, bins = np.histogram(samples1, bins=bins, density=True)
histogram2, bins = np.histogram(samples2, bins=bins, density=True)

plt.figure(figsize=(6, 4))
plt.hist(samples1, bins=bins, density=True, label="Samples 1")
plt.hist(samples2, bins=bins, density=True, label="Samples 2")
plt.legend(loc="best")
plt.show()

Total running time of the script: (0 minutes 0.106 seconds)

5.12.8 Curve fitting

Demos a simple curve fitting


First generate some data

import numpy as np

# Seed the random number generator for reproducibility


rng = np.random.default_rng(27446968) <matplotlib.collections.PathCollection object at 0x7f4954cc1850>

x_data = np.linspace(-5, 5, num=50) Now fit a simple sine function to the data
noise = 0.01 * np.cos(100 * x_data)
a, b = 2.9, 1.5 import scipy as sp
y_data = a * np.cos(b * x_data) + noise

# And plot it def test_func(x, a, b, c):


import matplotlib.pyplot as plt return a * np.sin(b * x + c)

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data) params, params_covariance = sp.optimize.curve_fit(
test_func, x_data, y_data, p0=[2, 1, 3]
)

print(params)

[2.900026 1.50012043 1.57079633]

And plot the resulting curve on the data

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label="Data")
plt.plot(x_data, test_func(x_data, *params), label="Fitted function")

plt.legend(loc="best")

plt.show()

5.12. Full code examples for the SciPy chapter 256 5.12. Full code examples for the SciPy chapter 257
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.132 seconds) [<matplotlib.lines.Line2D object at 0x7f4987c9d910>]

Compute and plot the spectrogram


5.12.9 Spectrogram, power spectral density
The spectrum of the signal on consecutive time windows
Demo spectrogram and power spectral density on a frequency chirp. import scipy as sp
import numpy as np
import matplotlib.pyplot as plt freqs, times, spectrogram = sp.signal.spectrogram(sig)

plt.figure(figsize=(5, 4))
plt.imshow(spectrogram, aspect="auto", cmap="hot_r", origin="lower")
Generate a chirp signal plt.title("Spectrogram")
plt.ylabel("Frequency band")
# Seed the random number generator plt.xlabel("Time window")
np.random.seed(0) plt.tight_layout()

time_step = 0.01
time_vec = np.arange(0, 70, time_step)

# A signal with a small frequency chirp


sig = np.sin(0.5 * np.pi * time_vec * (1 + 0.1 * time_vec))

plt.figure(figsize=(8, 5))
plt.plot(time_vec, sig)

5.12. Full code examples for the SciPy chapter 258 5.12. Full code examples for the SciPy chapter 259
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

plt.show()
Compute and plot the power spectral density (PSD)
Total running time of the script: (0 minutes 0.386 seconds)
The power of the signal per frequency band

freqs, psd = sp.signal.welch(sig)

plt.figure(figsize=(5, 4)) 5.12.10 Demo mathematical morphology


plt.semilogx(freqs, psd)
plt.title("PSD: power spectral density") A basic demo of binary opening and closing.
plt.xlabel("Frequency")
plt.ylabel("Power")
plt.tight_layout()

# Generate some binary data


import numpy as np

np.random.seed(0)
a = np.zeros((50, 50))
a[10:-10, 10:-10] = 1
a += 0.25 * np.random.standard_normal(a.shape)
mask = a >= 0.5

# Apply mathematical morphology


(continues on next page)

5.12. Full code examples for the SciPy chapter 260 5.12. Full code examples for the SciPy chapter 261
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Load some data
import scipy as sp import scipy as sp

opened_mask = sp.ndimage.binary_opening(mask) face = sp.datasets.face(gray=True)


closed_mask = sp.ndimage.binary_closing(opened_mask)
# Apply a variety of transformations
# Plot import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
shifted_face = sp.ndimage.shift(face, (50, 50))
plt.figure(figsize=(12, 3.5)) shifted_face2 = sp.ndimage.shift(face, (50, 50), mode="nearest")
plt.subplot(141) rotated_face = sp.ndimage.rotate(face, 30)
plt.imshow(a, cmap=plt.cm.gray) cropped_face = face[50:-50, 50:-50]
plt.axis("off") zoomed_face = sp.ndimage.zoom(face, 2)
plt.title("a") zoomed_face.shape

plt.subplot(142) plt.figure(figsize=(15, 3))


plt.imshow(mask, cmap=plt.cm.gray) plt.subplot(151)
plt.axis("off") plt.imshow(shifted_face, cmap=plt.cm.gray)
plt.title("mask") plt.axis("off")

plt.subplot(143) plt.subplot(152)
plt.imshow(opened_mask, cmap=plt.cm.gray) plt.imshow(shifted_face2, cmap=plt.cm.gray)
plt.axis("off") plt.axis("off")
plt.title("opened_mask")
plt.subplot(153)
plt.subplot(144) plt.imshow(rotated_face, cmap=plt.cm.gray)
plt.imshow(closed_mask, cmap=plt.cm.gray) plt.axis("off")
plt.title("closed_mask")
plt.axis("off") plt.subplot(154)
plt.imshow(cropped_face, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) plt.axis("off")

plt.show() plt.subplot(155)
plt.imshow(zoomed_face, cmap=plt.cm.gray)
Total running time of the script: (0 minutes 0.104 seconds) plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)

5.12.11 Plot geometrical transformations on images plt.show()

Demo geometrical transformations of images. Total running time of the script: (0 minutes 0.915 seconds)

5.12.12 Demo connected components

Extracting and labeling connected components in a 2D array

import numpy as np
import matplotlib.pyplot as plt
Downloading file 'face.dat' from 'https://raw.githubusercontent.com/scipy/dataset-
˓→face/main/face.dat' to '/home/runner/.cache/scipy-data'. Generate some binary data

x, y = np.indices((100, 100))
sig = (
np.sin(2 * np.pi * x / 50.0)
* np.sin(2 * np.pi * y / 50.0)
(continues on next page)

5.12. Full code examples for the SciPy chapter 262 5.12. Full code examples for the SciPy chapter 263
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


* (1 + x * y / 50.0**2) ** 2
)
mask = sig > 1

plt.figure(figsize=(7, 3.5))
plt.subplot(1, 2, 1)
plt.imshow(sig)
plt.axis("off")
plt.title("sig")

plt.subplot(1, 2, 2)
plt.imshow(mask, cmap=plt.cm.gray)
plt.axis("off")
plt.title("mask")
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)

Extract the 4th connected component, and crop the array around it

sl = sp.ndimage.find_objects(labels == 4)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(sig[sl[0]])
plt.title("Cropped connected component")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)

plt.show()

Label connected components

import scipy as sp

labels, nb = sp.ndimage.label(mask)

plt.figure(figsize=(3.5, 3.5))
plt.imshow(labels)
plt.title("label")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)

Total running time of the script: (0 minutes 0.129 seconds)

5.12. Full code examples for the SciPy chapter 264 5.12. Full code examples for the SciPy chapter 265
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.12.13 Minima and roots of a function (continued from previous page)


xmins = np.array([xmin_global[0], xmin_local])
Demos finding minima and roots of a function. ax.plot(xmins, f(xmins), "go", label="Minima")

# Plot the roots


Define the function
roots = np.array([root.x, root2.x])
ax.plot(roots, f(roots), "kv", label="Roots")
import numpy as np
# Decorate the figure
x = np.arange(-10, 10, 0.1) ax.legend(loc="best")
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
def f(x): ax.axhline(0, color="gray")
return x**2 + 10 * np.sin(x) plt.show()

Find minima

import scipy as sp

# Global optimization
grid = (-10, 10, 0.1)
xmin_global = sp.optimize.brute(f, (grid,))
print(f"Global minima found { xmin_global} ")

# Constrain optimization
xmin_local = sp.optimize.fminbound(f, 0, 10)
print(f"Local minimum found { xmin_local} ")

Global minima found [-1.30641113]


Local minimum found 3.8374671194983834

Root finding

root = sp.optimize.root(f, 1) # our initial guess is 1


print(f"First root found { root.x} ")
root2 = sp.optimize.root(f, -2.5)
print(f"Second root found { root2.x} ")
Total running time of the script: (0 minutes 0.079 seconds)

First root found [0.]


Second root found [-2.47948183]

Plot function, minima, and roots

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6, 4))


ax = fig.add_subplot(111)

# Plot the function


ax.plot(x, f(x), "b-", label="f(x)")

# Plot the minima


(continues on next page)

5.12. Full code examples for the SciPy chapter 266 5.12. Full code examples for the SciPy chapter 267
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.12.14 Plot filtering on images Total running time of the script: (0 minutes 0.478 seconds)

Demo filtering for denoising of images.

5.12.15 Optimization of a two-parameter function

import numpy as np

# Define the function that we are interested in


def sixhump(x):
return (
(4 - 2.1 * x[0] ** 2 + x[0] ** 4 / 3) * x[0] ** 2
+ x[0] * x[1]
+ (-4 + 4 * x[1] ** 2) * x[1] ** 2
# Load some data )
import scipy as sp

face = sp.datasets.face(gray=True) # Make a grid to evaluate the function (for plotting)


face = face[:512, -512:] # crop out square on right xlim = [-2, 2]
ylim = [-1, 1]
# Apply a variety of filters x = np.linspace(*xlim)
import matplotlib.pyplot as plt y = np.linspace(*ylim)
xg, yg = np.meshgrid(x, y)
import numpy as np

noisy_face = np.copy(face).astype(float) A 2D image plot of the function


rng = np.random.default_rng()
noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape) Simple visualization in 2D
blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)
median_face = sp.ndimage.median_filter(noisy_face, size=5) import matplotlib.pyplot as plt
wiener_face = sp.signal.wiener(noisy_face, (5, 5))
plt.figure()
plt.figure(figsize=(12, 3.5)) plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower")
plt.subplot(141) plt.colorbar()
plt.imshow(noisy_face, cmap=plt.cm.gray)
plt.axis("off")
plt.title("noisy")

plt.subplot(142)
plt.imshow(blurred_face, cmap=plt.cm.gray)
plt.axis("off")
plt.title("Gaussian filter")

plt.subplot(143)
plt.imshow(median_face, cmap=plt.cm.gray)
plt.axis("off")
plt.title("median filter")

plt.subplot(144)
plt.imshow(wiener_face, cmap=plt.cm.gray)
plt.title("Wiener filter")
plt.axis("off")

plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)

plt.show()

5.12. Full code examples for the SciPy chapter 268 5.12. Full code examples for the SciPy chapter 269
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.colorbar.Colorbar object at 0x7f4955d7e150> Text(0.5, 1.0, 'Six-hump Camelback function')

A 3D surface plot of the function Find minima

from mpl_toolkits.mplot3d import Axes3D import scipy as sp

fig = plt.figure() # local minimization


ax = fig.add_subplot(111, projection="3d") res_local = sp.optimize.minimize(sixhump, x0=[0, 0])
surf = ax.plot_surface(
xg, # global minimization
yg, res_global = sp.optimize.differential_evolution(sixhump, bounds=[xlim, ylim])
sixhump([xg, yg]),
rstride=1, plt.figure()
cstride=1, # Show the function in 2D
cmap=plt.cm.viridis, plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower")
linewidth=0, plt.colorbar()
antialiased=False, # Mark the minima
) plt.scatter(res_local.x[0], res_local.x[1], label="local minimizer")
plt.scatter(res_global.x[0], res_global.x[1], label="global minimizer")
ax.set_xlabel("x") plt.legend()
ax.set_ylabel("y") plt.show()
ax.set_zlabel("f(x, y)")
ax.set_title("Six-hump Camelback function")

5.12. Full code examples for the SciPy chapter 270 5.12. Full code examples for the SciPy chapter 271
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.386 seconds)

[<matplotlib.lines.Line2D object at 0x7f495545e850>]

5.12.16 Plotting and manipulating FFTs for filtering


Compute and plot the power
Plot the power of the FFT of a signal and inverse FFT back to reconstruct a signal.
# The FFT of the signal
This example demonstrate scipy.fft.fft(), scipy.fft.fftfreq() and scipy.fft.ifft(). It imple-
sig_fft = sp.fft.fft(sig)
ments a basic filter that is very suboptimal, and should not be used.

import numpy as np # And the power (sig_fft is of complex dtype)


import scipy as sp power = np.abs(sig_fft) ** 2
import matplotlib.pyplot as plt
# The corresponding frequencies
sample_freq = sp.fft.fftfreq(sig.size, d=time_step)
Generate the signal
# Plot the FFT power
plt.figure(figsize=(6, 5))
# Seed the random number generator plt.plot(sample_freq, power)
rng = np.random.default_rng(27446968) plt.xlabel("Frequency [Hz]")
plt.ylabel("plower")
time_step = 0.02
period = 5.0 # Find the peak frequency: we can focus on only the positive frequencies
pos_mask = np.where(sample_freq > 0)
time_vec = np.arange(0, 20, time_step) freqs = sample_freq[pos_mask]
sig = np.sin(2 * np.pi / period * time_vec) + 0.5 * rng.normal(size=time_vec.size) peak_freq = freqs[power[pos_mask].argmax()]
plt.figure(figsize=(6, 5)) # Check that it does indeed correspond to the frequency that we generate
plt.plot(time_vec, sig, label="Original signal")
(continues on next page)

5.12. Full code examples for the SciPy chapter 272 5.12. Full code examples for the SciPy chapter 273
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


# the signal with plt.plot(time_vec, filtered_sig, linewidth=3, label="Filtered signal")
np.allclose(peak_freq, 1.0 / period) plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
# An inner plot to show the peak frequency
axes = plt.axes([0.55, 0.3, 0.3, 0.5]) plt.legend(loc="best")
plt.title("Peak frequency")
plt.plot(freqs[:8], power[pos_mask][:8])
plt.setp(axes, yticks=[])

# scipy.signal.find_peaks_cwt can also be used for more advanced


# peak detection

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/matplotlib/cbook.
˓→py:1762: ComplexWarning: Casting complex values to real discards the imaginary part

return math.isfinite(val)
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/matplotlib/cbook.
˓→py:1398: ComplexWarning: Casting complex values to real discards the imaginary part

return np.asarray(x, float)


[]
<matplotlib.legend.Legend object at 0x7f4955411bd0>

Remove all the high frequencies Note This is actually a bad way of creating a filter: such brutal cut-off in frequency space does not
control distortion on the signal.
We now remove all the high frequencies and transform back from frequencies to signal. Filters should be created using the SciPy filter design code
high_freq_fft = sig_fft.copy() plt.show()
high_freq_fft[np.abs(sample_freq) > peak_freq] = 0
filtered_sig = sp.fft.ifft(high_freq_fft) Total running time of the script: (0 minutes 0.243 seconds)
plt.figure(figsize=(6, 5))
plt.plot(time_vec, sig, label="Original signal")
(continues on next page)

5.12. Full code examples for the SciPy chapter 274 5.12. Full code examples for the SciPy chapter 275
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

5.12.17 A demo of 1D interpolation


# Generate data
• import numpy as np

rng = np.random.default_rng(27446968)
measured_time = np.linspace(0, 2 * np.pi, 20)
function = np.sin(measured_time)
noise = rng.normal(loc=0, scale=0.1, size=20)
measurements = function + noise

# Smooth the curve and interpolate at new times


import scipy as sp

smoothing_spline = sp.interpolate.make_smoothing_spline(measured_time, measurements)


interpolation_time = np.linspace(0, 2 * np.pi, 200)
smooth_results = smoothing_spline(interpolation_time)

# Plot the data, the interpolant, and the original function


import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.plot(measured_time, measurements, ".", ms=6, label="measurements")
plt.plot(interpolation_time, smooth_results, label="smoothing spline")
plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve
˓→")

plt.legend()
• plt.show()

# Fit the data exactly


interp_spline = sp.interpolate.make_interp_spline(measured_time, function)
interp_results = interp_spline(interpolation_time)

# Plot the data, the interpolant, and the original function


plt.figure(figsize=(6, 4))
(continues on next page)

5.12. Full code examples for the SciPy chapter 276 5.12. Full code examples for the SciPy chapter 277
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.plot(measured_time, function, ".", ms=6, label="measurements")
plt.plot(interpolation_time, interp_results, label="interpolating spline")
plt.plot(interpolation_time, np.sin(interpolation_time), "--", label="underlying curve
˓→")

plt.legend()
plt.show()

# Plot interpolant, its derivative, and its antiderivative


plt.figure(figsize=(6, 4))
t = interpolation_time
plt.plot(t, interp_spline(t), label="spline")
plt.plot(t, interp_spline.derivative()(t), label="derivative")
plt.plot(t, interp_spline.antiderivative()(t) - 1, label="antiderivative")

plt.legend()
plt.show()

Total running time of the script: (0 minutes 0.204 seconds)

5.12.18 Solutions of the exercises for SciPy

Solutions of the exercises for SciPy

Crude periodicity finding

Discover the periods in evolution of animal populations (../../../../data/populations.txt) <matplotlib.legend.Legend object at 0x7f495497bf10>

Load the data


Plot its periods

import numpy as np
import scipy as sp
data = np.loadtxt("../../../../data/populations.txt")
years = data[:, 0] ft_populations = sp.fft.fft(populations, axis=0)
populations = data[:, 1:] frequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0])
periods = 1 / frequencies

plt.figure()
Plot the data plt.plot(periods, abs(ft_populations) * 1e-3, "o")
plt.xlim(0, 22)
import matplotlib.pyplot as plt plt.xlabel("Period")
plt.ylabel(r"Power ($\cdot10^3$)")
plt.figure()
plt.plot(years, populations * 1e-3) plt.show()
plt.xlabel("Year")
plt.ylabel(r"Population number ($\cdot10^3$)")
plt.legend(["hare", "lynx", "carrot"], loc=1)

5.12. Full code examples for the SciPy chapter 278 5.12. Full code examples for the SciPy chapter 279
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

The data

import numpy as np

temp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])
temp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])

import matplotlib.pyplot as plt

months = np.arange(12)
plt.plot(months, temp_max, "ro")
plt.plot(months, temp_min, "bo")
plt.xlabel("Month")
plt.ylabel("Min and max temperature")

/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/scipy/
˓→examples/solutions/plot_periodicity_finder.py:39: RuntimeWarning: divide by zero␣

˓→encountered in divide

periods = 1 / frequencies

There’s probably a period of around 10 years (obvious from the plot), but for this crude a method,
there’s not enough data to say much more.
Total running time of the script: (0 minutes 0.121 seconds)

Curve fitting: temperature as a function of month of the year

We have the min and max temperatures in Alaska for each months of the year. We would like to find a
function to describe this yearly evolution.
Text(35.472222222222214, 0.5, 'Min and max temperature')
For this, we will fit a periodic function.

5.12. Full code examples for the SciPy chapter 280 5.12. Full code examples for the SciPy chapter 281
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Fitting it to a periodic function

import scipy as sp Simple image blur by convolution with a Gaussian kernel

Blur an an image (../../../../data/elephant.png) using a Gaussian kernel.


def yearly_temps(times, avg, ampl, time_offset):
return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()) Convolution is easy to perform with FFT: convolving two signals boils down to multiplying their FFTs
(and performing an inverse FFT).

res_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0]) import numpy as np
res_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0]) import scipy as sp
import matplotlib.pyplot as plt

Plotting the fit


The original image

days = np.linspace(0, 12, num=365)


# read image
plt.figure() img = plt.imread("../../../../data/elephant.png")
plt.plot(months, temp_max, "ro") plt.figure()
plt.plot(days, yearly_temps(days, *res_max), "r-") plt.imshow(img)
plt.plot(months, temp_min, "bo")
plt.plot(days, yearly_temps(days, *res_min), "b-")
plt.xlabel("Month")
plt.ylabel(r"Temperature ($^\circ$C)")

plt.show()

<matplotlib.image.AxesImage object at 0x7f4954a3a0d0>

Total running time of the script: (0 minutes 0.132 seconds)

5.12. Full code examples for the SciPy chapter 282 5.12. Full code examples for the SciPy chapter 283
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Prepare an Gaussian convolution kernel

# First a 1-D Gaussian


t = np.linspace(-10, 10, 30)
bump = np.exp(-0.1 * t**2)
bump /= np.trapz(bump) # normalize the integral to 1

# make a 2-D kernel out of it


kernel = bump[:, np.newaxis] * bump[np.newaxis, :]

Implement convolution via FFT

# Padded fourier transform, with the same shape as the image


# We use :func:`scipy.fft.fft2` to have a 2D FFT
kernel_ft = sp.fft.fft2(kernel, s=img.shape[:2], axes=(0, 1))

# convolve
img_ft = sp.fft.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
img2_ft = kernel_ft[:, :, np.newaxis] * img_ft
img2 = sp.fft.ifft2(img2_ft, axes=(0, 1)).real

# clip values to range


img2 = np.clip(img2, 0, 1)

# plot output
plt.figure()
plt.imshow(img2) <matplotlib.image.AxesImage object at 0x7f4955a67810>

Further exercise (only if you are familiar with this stuff):


A “wrapped border” appears in the upper left and top edges of the image. This is because the padding
is not done correctly, and does not take the kernel size into account (so the convolution “flows out of
bounds of the image”). Try to remove this artifact.

A function to do it: scipy.signal.fftconvolve()

The above exercise was only for didactic reasons: there exists a function in scipy that will do
this for us, and probably do a better job: scipy.signal.fftconvolve()

# mode='same' is there to enforce the same output shape as input arrays


# (ie avoid border effects)
img3 = sp.signal.fftconvolve(img, kernel[:, :, np.newaxis], mode="same")
plt.figure()
plt.imshow(img3)

5.12. Full code examples for the SciPy chapter 284 5.12. Full code examples for the SciPy chapter 285
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Read and plot the image

import numpy as np
import matplotlib.pyplot as plt

im = plt.imread("../../../../data/moonlanding.png").astype(float)

plt.figure()
plt.imshow(im, plt.cm.gray)
plt.title("Original image")

<matplotlib.image.AxesImage object at 0x7f49601653d0>

Note that we still have a decay to zero at the border of the image. Using scipy.ndimage.
gaussian_filter() would get rid of this artifact

plt.show()

Total running time of the script: (0 minutes 0.377 seconds)

Image denoising by FFT Text(0.5, 1.0, 'Original image')

Denoise an image (../../../../data/moonlanding.png) by implementing a blur with an FFT.


Implements, via FFT, the following convolution: Compute the 2d FFT of the input image
∫︁
𝑓1 (𝑡) = 𝑑𝑡′ 𝐾(𝑡 − 𝑡′ )𝑓0 (𝑡′ ) import scipy as sp

𝑓˜1 (𝜔) = 𝐾(𝜔)


˜ 𝑓˜0 (𝜔) im_fft = sp.fft.fft2(im)

# Show the results

def plot_spectrum(im_fft):
from matplotlib.colors import LogNorm

# A logarithmic colormap
(continues on next page)

5.12. Full code examples for the SciPy chapter 286 5.12. Full code examples for the SciPy chapter 287
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5)) # Set to zero all rows with indices between r*keep_fraction and
plt.colorbar() # r*(1-keep_fraction):
im_fft2[int(r * keep_fraction) : int(r * (1 - keep_fraction))] = 0

plt.figure() # Similarly with the columns:


plot_spectrum(im_fft) im_fft2[:, int(c * keep_fraction) : int(c * (1 - keep_fraction))] = 0
plt.title("Fourier transform")
plt.figure()
plot_spectrum(im_fft2)
plt.title("Filtered Spectrum")

Text(0.5, 1.0, 'Fourier transform')

Filter in FFT Text(0.5, 1.0, 'Filtered Spectrum')

# In the lines following, we'll make a copy of the original spectrum and
Reconstruct the final image
# truncate coefficients.

# Define the fraction of coefficients (in each direction) we keep # Reconstruct the denoised image from the filtered spectrum, keep only the
keep_fraction = 0.1 # real part for display.
im_new = sp.fft.ifft2(im_fft2).real
# Call ff a copy of the original transform. NumPy arrays have a copy
# method for this purpose. plt.figure()
im_fft2 = im_fft.copy() plt.imshow(im_new, plt.cm.gray)
plt.title("Reconstructed Image")
# Set r and c to be the number of rows and columns of the array.
r, c = im_fft2.shape

(continues on next page)

5.12. Full code examples for the SciPy chapter 288 5.12. Full code examples for the SciPy chapter 289
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 1.0, 'Reconstructed Image') Total running time of the script: (0 minutes 0.865 seconds)

Easier and better: scipy.ndimage.gaussian_filter()


See also:
Implementing filtering directly with FFTs is tricky and time consuming. We can use the References to go further
Gaussian filter from scipy.ndimage
• Some chapters of the advanced and the packages and applications parts of the SciPy lectures
im_blur = sp.ndimage.gaussian_filter(im, 4)
• The SciPy cookbook
plt.figure()
plt.imshow(im_blur, plt.cm.gray)
plt.title("Blurred image")

plt.show()

5.12. Full code examples for the SciPy chapter 290 5.12. Full code examples for the SciPy chapter 291
Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


increasing : bool, optional
Order of the powers of the columns. If True, the powers increase
from left to right, if False (the default) they are reversed.

.. versionadded:: 1.9.0

Returns

CHAPTER 6 -------
out : ndarray
Vandermonde matrix. If `increasing` is False, the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
True, the columns are ``x^0, x^1, ..., x^(N-1)``.

See Also
--------
polynomial.polynomial.polyvander

Examples
--------
>>> x = np.array([1, 2, 3, 5])
Getting help and finding documentation >>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])

>>> np.column_stack([x**(N-1-i) for i in range(N)])


Author: Emmanuelle Gouillart array([[ 1, 1, 1],
Rather than knowing all functions in NumPy and SciPy, it is important to find rapidly information [ 4, 2, 1],
throughout the documentation and the available help. Here are some ways to get information: [ 9, 3, 1],
[25, 5, 1]])
• In Ipython, help function opens the docstring of the function. Only type the beginning of the
function’s name and use tab completion to display the matching functions. >>> x = np.array([1, 2, 3, 5])
In [1]: help(np.van<TAB> >>> np.vander(x)
array([[ 1, 1, 1, 1],
In [2]: help(np.vander) [ 8, 4, 2, 1],
Help on _ArrayFunctionDispatcher in module numpy: [ 27, 9, 3, 1],
[125, 25, 5, 1]])
vander(x, N=None, increasing=False) >>> np.vander(x, increasing=True)
Generate a Vandermonde matrix. array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
The columns of the output matrix are powers of the input vector. The [ 1, 3, 9, 27],
order of the powers is determined by the `increasing` boolean argument. [ 1, 5, 25, 125]])
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such The determinant of a square Vandermonde matrix is the product
a matrix with a geometric progression in each row is named for Alexandre- of the differences between the values of the input vector:
Theophile Vandermonde.
>>> np.linalg.det(np.vander(x))
Parameters 48.000000000000043 # may vary
---------- >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
x : array_like 48
1-D input array.
N : int, optional In Ipython it is not possible to open a separated window for help and documentation; however one can
Number of columns in the output. If `N` is not specified, a square always open a second Ipython shell just to display help and docstrings. . .
array is returned (``N = len(x)``). • Numpy’s and Scipy’s documentations can be browsed online on https://scipy.org and https://
(continues on next page)

292 293
Scientific Python Lectures, Edition 2024.2rc0.dev0

numpy.org. The search button is quite useful inside the reference documentation of the two
packages.
Tutorials on various topics as well as the complete API with all docstrings are found on this website.
• Numpy’s and Scipy’s documentation is enriched and updated on a regular basis by users on a wiki
https://numpy.org/doc/stable/. As a result, some docstrings are clearer or more detailed on the
wiki, and you may want to read directly the documentation on the wiki instead of the official
documentation website. Note that anyone can create an account on the wiki and write better
documentation; this is an easy way to contribute to an open-source project and improve the tools
you are using!
• The SciPy Cookbook https://scipy-cookbook.readthedocs.io gives recipes on many common prob-
lems frequently encountered, such as fitting data points, solving ODE, etc.
• Matplotlib’s website https://matplotlib.org/ features a very nice gallery with a large number of
plots, each of them shows both the source code and the resulting plot. This is very useful for
learning by example. More standard documentation is also available.
Finally, two more “technical” possibilities are useful as well:
• In Ipython, the magical function %psearch search for objects matching patterns. This is useful if,
for example, one does not know the exact name of a function. Part II
In [3]: import numpy as np

• numpy.lookfor looks for keywords inside the docstrings of specified modules.

In [4]: np.lookfor('convolution')
Advanced topics
Search results for 'convolution'
--------------------------------
numpy.convolve
Returns the discrete, linear convolution of two one-dimensional sequences.
numpy.ma.convolve
Returns the discrete, linear convolution of two one-dimensional sequences.
numpy.polymul
Find the product of two polynomials.
numpy.bartlett
Return the Bartlett window.
numpy.correlate
Cross-correlation of two 1-dimensional sequences.
numpy.vectorize
vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None,

• If everything listed above fails (and Google doesn’t have the answer). . . don’t despair! There is
a vibrant Scientific Python community. Scientific Python is present on various platform. https:
//scientific-python.org/community/
Packages like SciPy and NumPy also have their own channels. Have a look at their respective
websites to find out how to engage with users and maintainers.

294 295
Scientific Python Lectures, Edition 2024.2rc0.dev0

This part of the Scientific Python Lectures is dedicated to advanced usage. It strives to educate the
proficient Python coder to be an expert and tackles various specific topics.

CHAPTER 7
Advanced Python Constructs

Author Zbigniew Jędrzejewski-Szmek


This section covers some features of the Python language which can be considered advanced — in
the sense that not every language has them, and also in the sense that they are more useful in more
complicated programs or libraries, but not in the sense of being particularly specialized, or particularly
complicated.
It is important to underline that this chapter is purely about the language itself — about features
supported through special syntax complemented by functionality of the Python stdlib, which could not
be implemented through clever external modules.
The process of developing the Python programming language, its syntax, is very transparent; proposed
changes are evaluated from various angles and discussed via Python Enhancement Proposals — PEPs.
As a result, features described in this chapter were added after it was shown that they indeed solve real
problems and that their use is as simple as possible.

Chapter contents

• Iterators, generator expressions and generators


– Iterators
– Generator expressions
– Generators
– Bidirectional communication
– Chaining generators
• Decorators
– Replacing or tweaking the original object

296 297
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

– Decorators implemented as classes and as functions (continued from previous page)


File "<stdin>", line 1, in <module>
– Copying the docstring and other attributes of the original function
StopIteration
– Examples in the standard library
– Deprecation of functions When used in a loop, StopIteration is swallowed and causes the loop to finish. But with explicit
invocation, we can see that once the iterator is exhausted, accessing it raises an exception.
– A while-loop removing decorator
Using the for..in loop also uses the __iter__ method. This allows us to transparently start the iteration
– A plugin registration system over a sequence. But if we already have the iterator, we want to be able to use it in an for loop in
• Context managers the same way. In order to achieve this, iterators in addition to next are also required to have a method
called __iter__ which returns the iterator (self).
– Catching exceptions
Support for iteration is pervasive in Python: all sequences and unordered containers in the standard
– Using generators to define context managers library allow this. The concept is also stretched to other things: e.g. file objects support iteration over
lines.

>>> with open("/etc/fstab") as f:


7.1 Iterators, generator expressions and generators ... f is f.__iter__()
...
True
7.1.1 Iterators
The file is an iterator itself and it’s __iter__ method doesn’t create a separate object: only a single
thread of sequential access is allowed.
Simplicity

Duplication of effort is wasteful, and replacing the various home-grown approaches with a standard 7.1.2 Generator expressions
feature usually ends up making things more readable, and interoperable as well.
A second way in which iterator objects are created is through generator expressions, the basis for list
Guido van Rossum — Adding Optional Static Typing to Python comprehensions. To increase clarity, a generator expression must always be enclosed in parentheses
or an expression. If round parentheses are used, then a generator iterator is created. If rectangular
An iterator is an object adhering to the iterator protocol — basically this means that it has a next parentheses are used, the process is short-circuited and we get a list.
method, which, when called, returns the next item in the sequence, and when there’s nothing to return,
raises the StopIteration exception. >>> (i for i in nums)
<generator object <genexpr> at 0x...>
An iterator object allows to loop just once. It holds the state (position) of a single iteration, or from the >>> [i for i in nums]
other side, each loop over a sequence requires a single iterator object. This means that we can iterate [1, 2, 3]
over the same sequence more than once concurrently. Separating the iteration logic from the sequence >>> list(i for i in nums)
allows us to have more than one way of iteration. [1, 2, 3]
Calling the __iter__ method on a container to create an iterator object is the most straightforward way
to get hold of an iterator. The iter function does that for us, saving a few keystrokes. The list comprehension syntax also extends to dictionary and set comprehensions. A set is cre-
ated when the generator expression is enclosed in curly braces. A dict is created when the generator
>>> nums = [1, 2, 3] # note that ... varies: these are different objects expression contains “pairs” of the form key:value:
>>> iter(nums)
<...iterator object at ...> >>> {i for i in range(3)}
>>> nums.__iter__() {0, 1, 2}
<...iterator object at ...> >>> {i:i**2 for i in range(3)}
>>> nums.__reversed__() {0: 0, 1: 1, 2: 4}
<...reverseiterator object at ...>
One gotcha should be mentioned: in old Pythons the index variable (i) would leak, and in versions >=
>>> it = iter(nums) 3 this is fixed.
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
(continues on next page)

7.1. Iterators, generator expressions and generators 298 7.1. Iterators, generator expressions and generators 299
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

7.1.3 Generators function. Since no yield was reached, an exception is raised.


What happens with the function after a yield, when the control passes to the caller? The state of
each generator is stored in the generator object. From the point of view of the generator function, is
Generators
looks almost as if it was running in a separate thread, but this is just an illusion: execution is strictly
single-threaded, but the interpreter keeps and restores the state in between the requests for the next
A generator is a function that produces a sequence of results instead of a single value.
value.
David Beazley — A Curious Course on Coroutines and Concurrency
Why are generators useful? As noted in the parts about iterators, a generator function is just a different
way to create an iterator object. Everything that can be done with yield statements, could also be
A third way to create iterator objects is to call a generator function. A generator is a function containing done with next methods. Nevertheless, using a function and having the interpreter perform its magic
the keyword yield. It must be noted that the mere presence of this keyword completely changes the to create an iterator has advantages. A function can be much shorter than the definition of a class with
nature of the function: this yield statement doesn’t have to be invoked, or even reachable, but causes the required next and __iter__ methods. What is more important, it is easier for the author of the
the function to be marked as a generator. When a normal function is called, the instructions contained in generator to understand the state which is kept in local variables, as opposed to instance attributes,
the body start to be executed. When a generator is called, the execution stops before the first instruction which have to be used to pass data between consecutive invocations of next on an iterator object.
in the body. An invocation of a generator function creates a generator object, adhering to the iterator
A broader question is why are iterators useful? When an iterator is used to power a loop, the loop
protocol. As with normal function invocations, concurrent and recursive invocations are allowed.
becomes very simple. The code to initialise the state, to decide if the loop is finished, and to find the
When next is called, the function is executed until the first yield. Each encountered yield statement next value is extracted into a separate place. This highlights the body of the loop — the interesting
gives a value becomes the return value of next. After executing the yield statement, the execution of part. In addition, it is possible to reuse the iterator code in other places.
this function is suspended.

>>> def f(): 7.1.4 Bidirectional communication


... yield 1
... yield 2 Each yield statement causes a value to be passed to the caller. This is the reason for the introduction
>>> f() of generators by PEP 255. But communication in the reverse direction is also useful. One obvious way
<generator object f at 0x...> would be some external state, either a global variable or a shared mutable object. Direct communication
>>> gen = f() is possible thanks to PEP 342. It is achieved by turning the previously boring yield statement into an
>>> next(gen) expression. When the generator resumes execution after a yield statement, the caller can call a method
1 on the generator object to either pass a value into the generator, which then is returned by the yield
>>> next(gen) statement, or a different method to inject an exception into the generator.
2
>>> next(gen) The first of the new methods is send(value), which is similar to next(), but passes value into the
Traceback (most recent call last): generator to be used for the value of the yield expression. In fact, g.next() and g.send(None) are
File "<stdin>", line 1, in <module> equivalent.
StopIteration The second of the new methods is throw(type, value=None, traceback=None) which is equivalent to:

Let’s go over the life of the single invocation of the generator function. raise type, value, traceback

>>> def f(): at the point of the yield statement.


... print("-- start --")
Unlike raise (which immediately raises an exception from the current execution point), throw() first
... yield 3
resumes the generator, and only then raises the exception. The word throw was picked because it
... print("-- finish --")
is suggestive of putting the exception in another location, and is associated with exceptions in other
... yield 4
languages.
>>> gen = f()
>>> next(gen) What happens when an exception is raised inside the generator? It can be either raised explicitly or
-- start -- when executing some statements or it can be injected at the point of a yield statement by means of
3 the throw() method. In either case, such an exception propagates in the standard manner: it can
>>> next(gen) be intercepted by an except or finally clause, or otherwise it causes the execution of the generator
-- finish -- function to be aborted and propagates in the caller.
4
For completeness’ sake, it’s worth mentioning that generator iterators also have a close() method,
>>> next(gen)
which can be used to force a generator that would otherwise be able to provide more values to finish
Traceback (most recent call last):
immediately. It allows the generator __del__ method to destroy objects holding the state of generator.
...
Let’s define a generator which just prints what is passed in through send and throw.
StopIteration
>>> import itertools
Contrary to a normal function, where executing f() would immediately cause the first print to be >>> def g():
executed, gen is assigned without executing any statements in the function body. Only when gen. ... print('--start--')
__next__() is invoked by next, the statements up to the first yield are executed. The second next ... for i in itertools.count():
prints -- finish -- and execution halts on the second yield. The third next falls of the end of the (continues on next page)

7.1. Iterators, generator expressions and generators 300 7.1. Iterators, generator expressions and generators 301
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 7.2 Decorators


... print('--yielding %i --' % i)
... try:
... ans = yield i Summary
... except GeneratorExit:
... print('--closing--') This amazing feature appeared in the language almost apologetically and with concern that it might
... raise not be that useful.
... except Exception as e:
... print('--yield raised %r --' % e) Bruce Eckel — An Introduction to Python Decorators
... else:
... print('--yield returned %s --' % ans) Since functions and classes are objects, they can be passed around. Since they are mutable objects, they
can be modified. The act of altering a function or class object after it has been constructed but before
>>> it = g() is is bound to its name is called decorating.
>>> next(it)
--start-- There are two things hiding behind the name “decorator” — one is the function which does the work of
--yielding 0-- decorating, i.e. performs the real work, and the other one is the expression adhering to the decorator
0 syntax, i.e. an at-symbol and the name of the decorating function.
>>> it.send(11) Function can be decorated by using the decorator syntax for functions:
--yield returned 11--
--yielding 1-- @decorator # ❷
1 def function(): # ❶
>>> it.throw(IndexError) pass
--yield raised IndexError()--
--yielding 2-- • A function is defined in the standard way. ❶
2
>>> it.close() • An expression starting with @ placed before the function definition is the decorator ❷. The part
--closing-- after @ must be a simple expression, usually this is just the name of a function or class. This part is
evaluated first, and after the function defined below is ready, the decorator is called with the newly
defined function object as the single argument. The value returned by the decorator is attached to
the original name of the function.
7.1.5 Chaining generators
Decorators can be applied to functions and to classes. For classes the semantics are identical — the
original class definition is used as an argument to call the decorator and whatever is returned is assigned
Note: This is a preview of PEP 380 (not yet implemented, but accepted for Python 3.3). under the original name.
Before the decorator syntax was implemented (PEP 318), it was possible to achieve the same effect by
Let’s say we are writing a generator and we want to yield a number of values generated by a second assigning the function or class object to a temporary variable and then invoking the decorator explicitly
generator, a subgenerator. If yielding of values is the only concern, this can be performed without and then assigning the return value to the name of the function. This sounds like more typing, and it
much difficulty using a loop such as is, and also the name of the decorated function doubling as a temporary variable must be used at least
three times, which is prone to errors. Nevertheless, the example above is equivalent to:
subgen = some_other_generator()
for v in subgen: def function(): # ❶
yield v pass
function = decorator(function) # ❷
However, if the subgenerator is to interact properly with the caller in the case of calls to send(), throw()
and close(), things become considerably more difficult. The yield statement has to be guarded by a Decorators can be stacked — the order of application is bottom-to-top, or inside-out. The semantics
try..except..finally structure similar to the one defined in the previous section to “debug” the generator are such that the originally defined function is used as an argument for the first decorator, whatever is
function. Such code is provided in PEP 380#id13, here it suffices to say that new syntax to properly returned by the first decorator is used as an argument for the second decorator, . . . , and whatever is
yield from a subgenerator is being introduced in Python 3.3: returned by the last decorator is attached under the name of the original function.
The decorator syntax was chosen for its readability. Since the decorator is specified before the header
yield from some_other_generator()
of the function, it is obvious that its is not a part of the function body and its clear that it can only
operate on the whole function. Because the expression is prefixed with @ is stands out and is hard to
This behaves like the explicit loop above, repeatedly yielding values from some_other_generator until miss (“in your face”, according to the PEP :) ). When more than one decorator is applied, each one is
it is exhausted, but also forwards send, throw and close to the subgenerator. placed on a separate line in an easy to read way.

7.1. Iterators, generator expressions and generators 302 7.2. Decorators 303
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

7.2.1 Replacing or tweaking the original object >>> def replacing_decorator_with_args(arg):


... print("defining the decorator")
Decorators can either return the same function or class object or they can return a completely different
... def _decorator(function):
object. In the first case, the decorator can exploit the fact that function and class objects are mutable
... # in this inner function, arg is available too
and add attributes, e.g. add a docstring to a class. A decorator might do something useful even without
... print("doing decoration, %r " % arg)
modifying the object, for example register the decorated class in a global registry. In the second case,
... def _wrapper(*args, **kwargs):
virtually anything is possible: when something different is substituted for the original function or class,
... print("inside wrapper, %r %r " % (args, kwargs))
the new object can be completely different. Nevertheless, such behaviour is not the purpose of decorators:
... return function(*args, **kwargs)
they are intended to tweak the decorated object, not do something unpredictable. Therefore, when a
... return _wrapper
function is “decorated” by replacing it with a different function, the new function usually calls the original
... return _decorator
function, after doing some preparatory work. Likewise, when a class is “decorated” by replacing if with
>>> @replacing_decorator_with_args("abc")
a new class, the new class is usually derived from the original class. When the purpose of the decorator
... def function(*args, **kwargs):
is to do something “every time”, like to log every call to a decorated function, only the second type of
... print("inside function, %r %r " % (args, kwargs))
decorators can be used. On the other hand, if the first type is sufficient, it is better to use it, because it
... return 14
is simpler.
defining the decorator
doing decoration, 'abc'
7.2.2 Decorators implemented as classes and as functions >>> function(11, 12)
inside wrapper, (11, 12) {}
inside function, (11, 12) {}
The only requirement on decorators is that they can be called with a single argument. This means that
14
decorators can be implemented as normal functions, or as classes with a __call__ method, or in theory,
even as lambda functions.
The _wrapper function is defined to accept all positional and keyword arguments. In general we cannot
Let’s compare the function and class approaches. The decorator expression (the part after @) can be know what arguments the decorated function is supposed to accept, so the wrapper function just passes
either just a name, or a call. The bare-name approach is nice (less to type, looks cleaner, etc.), but is everything to the wrapped function. One unfortunate consequence is that the apparent argument list is
only possible when no arguments are needed to customise the decorator. Decorators written as functions misleading.
can be used in those two cases:
Compared to decorators defined as functions, complex decorators defined as classes are simpler. When
>>> def simple_decorator(function): an object is created, the __init__ method is only allowed to return None, and the type of the created
... print("doing decoration") object cannot be changed. This means that when a decorator is defined as a class, it doesn’t make
... return function much sense to use the argument-less form: the final decorated object would just be an instance of the
>>> @simple_decorator decorating class, returned by the constructor call, which is not very useful. Therefore it’s enough to
... def function(): discuss class-based decorators where arguments are given in the decorator expression and the decorator
... print("inside function") __init__ method is used for decorator construction.
doing decoration
>>> function() >>> class decorator_class(object):
inside function ... def __init__(self, arg):
... # this method is called in the decorator expression
>>> def decorator_with_arguments(arg): ... print("in decorator init, %s " % arg)
... print("defining the decorator") ... self.arg = arg
... def _decorator(function): ... def __call__(self, function):
... # in this inner function, arg is available too ... # this method is called to do the job
... print("doing decoration, %r " % arg) ... print("in decorator call, %s " % self.arg)
... return function ... return function
... return _decorator >>> deco_instance = decorator_class('foo')
>>> @decorator_with_arguments("abc") in decorator init, foo
... def function(): >>> @deco_instance
... print("inside function") ... def function(*args, **kwargs):
defining the decorator ... print("in function, %s %s " % (args, kwargs))
doing decoration, 'abc' in decorator call, foo
>>> function() >>> function()
inside function in function, () {}

The two trivial decorators above fall into the category of decorators which return the original function. Contrary to normal rules (PEP 8) decorators written as classes behave more like functions and therefore
If they were to return a new function, an extra level of nestedness would be required. In the worst case, their name often starts with a lowercase letter.
three levels of nested functions. In reality, it doesn’t make much sense to create a new class just to have a decorator which returns the
original function. Objects are supposed to hold state, and such decorators are more useful when the
decorator returns a new object.

7.2. Decorators 304 7.2. Decorators 305


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> class replacing_decorator_class(object): >>> function


... def __init__(self, arg): <function function at 0x...>
... # this method is called in the decorator expression >>> print(function.__doc__)
... print("in decorator init, %s " % arg) extensive documentation
... self.arg = arg
... def __call__(self, function): One important thing is missing from the list of attributes which can be copied to the replacement
... # this method is called to do the job
function: the argument list. The default values for arguments can be modified through the __defaults__,
... print("in decorator call, %s " % self.arg)
__kwdefaults__ attributes, but unfortunately the argument list itself cannot be set as an attribute. This
... self.function = function means that help(function) will display a useless argument list which will be confusing for the user of
... return self._wrapper the function. An effective but ugly way around this problem is to create the wrapper dynamically, using
... def _wrapper(self, *args, **kwargs): eval. This can be automated by using the external decorator module. It provides support for the
... print("in the wrapper, %s %s " % (args, kwargs)) decorator decorator, which takes a wrapper and turns it into a decorator which preserves the function
... return self.function(*args, **kwargs)
signature.
>>> deco_instance = replacing_decorator_class('foo')
in decorator init, foo To sum things up, decorators should always use functools.update_wrapper or some other means of
>>> @deco_instance copying function attributes.
... def function(*args, **kwargs):
... print("in function, %s %s " % (args, kwargs))
in decorator call, foo 7.2.4 Examples in the standard library
>>> function(11, 12)
in the wrapper, (11, 12) {} First, it should be mentioned that there’s a number of useful decorators available in the standard library.
in function, (11, 12) {} There are three decorators which really form a part of the language:
• classmethod causes a method to become a “class method”, which means that it can be invoked
A decorator like this can do pretty much anything, since it can modify the original function object and without creating an instance of the class. When a normal method is invoked, the interpreter inserts
mangle the arguments, call the original function or not, and afterwards mangle the return value. the instance object as the first positional parameter, self. When a class method is invoked, the
class itself is given as the first parameter, often called cls.
7.2.3 Copying the docstring and other attributes of the original function Class methods are still accessible through the class’ namespace, so they don’t pollute the module’s
namespace. Class methods can be used to provide alternative constructors:
When a new function is returned by the decorator to replace the original function, an unfortunate
class Array(object):
consequence is that the original function name, the original docstring, the original argument list are
def __init__(self, data):
lost. Those attributes of the original function can partially be “transplanted” to the new function
self.data = data
by setting __doc__ (the docstring), __module__ and __name__ (the full name of the function), and
__annotations__ (extra information about arguments and the return value of the function available in
@classmethod
Python 3). This can be done automatically by using functools.update_wrapper.
def fromfile(cls, file):
data = numpy.load(file)
functools.update_wrapper(wrapper, wrapped) return cls(data)

“Update a wrapper function to look like the wrapped function.” This is cleaner than using a multitude of flags to __init__.
>>> import functools
• staticmethod is applied to methods to make them “static”, i.e. basically a normal function, but
>>> def replacing_decorator_with_args(arg):
accessible through the class namespace. This can be useful when the function is only needed inside
... print("defining the decorator")
this class (its name would then be prefixed with _), or when we want the user to think of the
... def _decorator(function):
method as connected to the class, despite an implementation which doesn’t require this.
... print("doing decoration, %r " % arg)
... def _wrapper(*args, **kwargs): • property is the pythonic answer to the problem of getters and setters. A method decorated with
... print("inside wrapper, %r %r " % (args, kwargs)) property becomes a getter which is automatically called on attribute access.
... return function(*args, **kwargs)
... return functools.update_wrapper(_wrapper, function) >>> class A(object):
... return _decorator ... @property
>>> @replacing_decorator_with_args("abc") ... def a(self):
... def function(): ... "an important attribute"
... "extensive documentation" ... return "a value"
... print("inside function") >>> A.a
... return 14 <property object at 0x...>
defining the decorator >>> A().a
doing decoration, 'abc' 'a value'

7.2. Decorators 306 7.2. Decorators 307


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

In this example, A.a is an read-only attribute. It is also documented: help(A) includes the (continued from previous page)
docstring for attribute a taken from the getter method. Defining a as a property allows it to be a setting 2
calculated on the fly, and has the side effect of making it read-only, because no setter is defined. >>> del d.a
To have a setter and a getter, two methods are required, obviously: deleting
>>> d.a
class Rectangle(object): getting 1
def __init__(self, edge): 1
self.edge = edge
Properties are a bit of a stretch for the decorator syntax. One of the premises of the decorator
@property syntax — that the name is not duplicated — is violated, but nothing better has been invented so
def area(self): far. It is just good style to use the same name for the getter, setter, and deleter methods.
"""Computed area.
Some newer examples include:
Setting this updates the edge length to the proper value. • functools.lru_cache memoizes an arbitrary function maintaining a limited cache of argu-
""" ments:answer pairs (Python 3.2)
return self.edge**2
• functools.total_ordering is a class decorator which fills in missing ordering methods (__lt__,
__gt__, __le__, . . . ) based on a single available one.
@area.setter
def area(self, area):
self.edge = area ** 0.5 7.2.5 Deprecation of functions
The way that this works, is that the property decorator replaces the getter method with a property Let’s say we want to print a deprecation warning on stderr on the first invocation of a function we don’t
object. This object in turn has three methods, getter, setter, and deleter, which can be used like anymore. If we don’t want to modify the function, we can use a decorator:
as decorators. Their job is to set the getter, setter and deleter of the property object (stored as
attributes fget, fset, and fdel). The getter can be set like in the example above, when creating class deprecated(object):
the object. When defining the setter, we already have the property object under area, and we add """Print a deprecation warning once on first use of the function.
the setter to it by using the setter method. All this happens when we are creating the class.
>>> @deprecated() # doctest: +SKIP
Afterwards, when an instance of the class has been created, the property object is special. When the
... def f():
interpreter executes attribute access, assignment, or deletion, the job is delegated to the methods
... pass
of the property object.
>>> f() # doctest: +SKIP
To make everything crystal clear, let’s define a “debug” example: f is deprecated
"""
>>> class D(object): def __call__(self, func):
... @property self.func = func
... def a(self): self.count = 0
... print("getting 1") return self._wrapper
... return 1 def _wrapper(self, *args, **kwargs):
... @a.setter self.count += 1
... def a(self, value): if self.count == 1:
... print("setting %r " % value) print(self.func.__name__, 'is deprecated')
... @a.deleter return self.func(*args, **kwargs)
... def a(self):
... print("deleting")
It can also be implemented as a function:
>>> D.a
<property object at 0x...> def deprecated(func):
>>> D.a.fget """Print a deprecation warning once on first use of the function.
<function ...>
>>> D.a.fset >>> @deprecated # doctest: +SKIP
<function ...> ... def f():
>>> D.a.fdel ... pass
<function ...> >>> f() # doctest: +SKIP
>>> d = D() # ... varies, this is not the same `a` function f is deprecated
>>> d.a """
getting 1 count = [0]
1 def wrapper(*args, **kwargs):
>>> d.a = 2 count[0] += 1
(continues on next page) (continues on next page)

7.2. Decorators 308 7.2. Decorators 309


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


if count[0] == 1:
print(func.__name__, 'is deprecated') @WordProcessor.plugin
return func(*args, **kwargs) class CleanMdashesExtension(object):
return wrapper def cleanup(self, text):
return text.replace('&mdash;', u'\N{em dash}')

7.2.6 A while-loop removing decorator Here we use a decorator to decentralise the registration of plugins. We call our decorator with a noun,
instead of a verb, because we use it to declare that our class is a plugin for WordProcessor. Method
Let’s say we have function which returns a lists of things, and this list created by running a loop. If we plugin simply appends the class to the list of plugins.
don’t know how many objects will be needed, the standard way to do this is something like: A word about the plugin itself: it replaces HTML entity for em-dash with a real Unicode em-dash
character. It exploits the unicode literal notation to insert a character by using its name in the unicode
def find_answers():
database (“EM DASH”). If the Unicode character was inserted directly, it would be impossible to
answers = []
distinguish it from an en-dash in the source of a program.
while True:
ans = look_for_next_answer() See also:
if ans is None:
More examples and reading
break
answers.append(ans) • PEP 318 (function and method decorator syntax)
return answers
• PEP 3129 (class decorator syntax)
This is fine, as long as the body of the loop is fairly compact. Once it becomes more complicated, as • https://wiki.python.org/moin/PythonDecoratorLibrary
often happens in real code, this becomes pretty unreadable. We could simplify this by using yield
• https://docs.python.org/dev/library/functools.html
statements, but then the user would have to explicitly call list(find_answers()).
• https://pypi.org/project/decorator
We can define a decorator which constructs the list for us:
• Bruce Eckel
def vectorized(generator_func):
def wrapper(*args, **kwargs): – Decorators I: Introduction to Python Decorators
return list(generator_func(*args, **kwargs)) – Python Decorators II: Decorator Arguments
return functools.update_wrapper(wrapper, generator_func)
– Python Decorators III: A Decorator-Based Build System
Our function then becomes:
@vectorized 7.3 Context managers
def find_answers():
while True:
ans = look_for_next_answer() A context manager is an object with __enter__ and __exit__ methods which can be used in the with
if ans is None: statement:
break
with manager as var:
yield ans
do_something(var)

is in the simplest case equivalent to


7.2.7 A plugin registration system
var = manager.__enter__()
This is a class decorator which doesn’t modify the class, but just puts it in a global registry. It falls into try:
the category of decorators returning the original object: do_something(var)
finally:
class WordProcessor(object): manager.__exit__()
PLUGINS = []
def process(self, text): In other words, the context manager protocol defined in PEP 343 permits the extraction of the boring
for plugin in self.PLUGINS: part of a try..except..finally structure into a separate class leaving only the interesting do_something
text = plugin().cleanup(text) block.
return text
1. The __enter__ method is called first. It can return a value which will be assigned to var. The
@classmethod as-part is optional: if it isn’t present, the value returned by __enter__ is simply ignored.
def plugin(cls, plugin): 2. The block of code underneath with is executed. Just like with try clauses, it can either execute
cls.PLUGINS.append(plugin) successfully to the end, or it can break, continue or return, or it can throw an exception. Either
(continues on next page)

7.2. Decorators 310 7.3. Context managers 311


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

way, after the block is finished, the __exit__ method is called. If an exception was thrown, 7.3.1 Catching exceptions
the information about the exception is passed to __exit__, which is described below in the next
subsection. In the normal case, exceptions can be ignored, just like in a finally clause, and will When an exception is thrown in the with-block, it is passed as arguments to __exit__. Three arguments
be rethrown after __exit__ is finished. are used, the same as returned by sys.exc_info(): type, value, traceback. When no exception is thrown,
None is used for all three arguments. The context manager can “swallow” the exception by returning a
Let’s say we want to make sure that a file is closed immediately after we are done writing to it:
true value from __exit__. Exceptions can be easily ignored, because if __exit__ doesn’t use return
>>> class closing(object): and just falls of the end, None is returned, a false value, and therefore the exception is rethrown after
... def __init__(self, obj): __exit__ is finished.
... self.obj = obj The ability to catch exceptions opens interesting possibilities. A classic example comes from unit-tests
... def __enter__(self): — we want to make sure that some code throws the right kind of exception:
... return self.obj
... def __exit__(self, *args): class assert_raises(object):
... self.obj.close() # based on pytest and unittest.TestCase
>>> with closing(open('/tmp/file', 'w')) as f: def __init__(self, type):
... f.write('the contents\n') self.type = type
def __enter__(self):
Here we have made sure that the f.close() is called when the with block is exited. Since closing files is pass
such a common operation, the support for this is already present in the file class. It has an __exit__ def __exit__(self, type, value, traceback):
method which calls close and can be used as a context manager itself: if type is None:
raise AssertionError('exception expected')
>>> with open('/tmp/file', 'a') as f: if issubclass(type, self.type):
... f.write('more contents\n') return True # swallow the expected exception
raise AssertionError('wrong exception type')
The common use for try..finally is releasing resources. Various different cases are implemented
similarly: in the __enter__ phase the resource is acquired, in the __exit__ phase it is released, and the with assert_raises(KeyError):
exception, if thrown, is propagated. As with files, there’s often a natural operation to perform after the {}['foo']
object has been used and it is most convenient to have the support built in. With each release, Python
provides support in more places:
• all file-like objects: 7.3.2 Using generators to define context managers
– file ➥ automatically closed
When discussing generators, it was said that we prefer generators to iterators implemented as classes
– fileinput, tempfile because they are shorter, sweeter, and the state is stored as local, not instance, variables. On the other
– bz2.BZ2File, gzip.GzipFile, tarfile.TarFile, zipfile.ZipFile hand, as described in Bidirectional communication, the flow of data between the generator and its caller
can be bidirectional. This includes exceptions, which can be thrown into the generator. We would like to
– ftplib, nntplib ➥ close connection implement context managers as special generator functions. In fact, the generator protocol was designed
• locks to support this use case.

– multiprocessing.RLock ➥ lock and unlock @contextlib.contextmanager


def some_generator(<arguments>):
– multiprocessing.Semaphore <setup>
– memoryview ➥ automatically release try:
yield <value>
• decimal.localcontext ➥ modify precision of computations temporarily finally:
• _winreg.PyHKEY ➥ open and close hive key <cleanup>

• warnings.catch_warnings ➥ kill warnings temporarily The contextlib.contextmanager helper takes a generator and turns it into a context manager. The
• contextlib.closing ➥ the same as the example above, call close generator has to obey some rules which are enforced by the wrapper function — most importantly it
must yield exactly once. The part before the yield is executed from __enter__, the block of code
• parallel programming protected by the context manager is executed when the generator is suspended in yield, and the rest
– concurrent.futures.ThreadPoolExecutor ➥ invoke in parallel then kill thread pool is executed in __exit__. If an exception is thrown, the interpreter hands it to the wrapper through
__exit__ arguments, and the wrapper function then throws it at the point of the yield statement.
– concurrent.futures.ProcessPoolExecutor ➥ invoke in parallel then kill process pool Through the use of generators, the context manager is shorter and simpler.
– nogil ➥ solve the GIL problem temporarily (cython only :( ) Let’s rewrite the closing example as a generator:

@contextlib.contextmanager
def closing(obj):
(continues on next page)

7.3. Context managers 312 7.3. Context managers 313


Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


try:
yield obj
finally:
obj.close()

Let’s rewrite the assert_raises example as a generator:

8
@contextlib.contextmanager
def assert_raises(type):
try:
yield CHAPTER
except type:
return
except Exception as value:
raise AssertionError('wrong exception type')
else:
raise AssertionError('exception expected')

Here we use a decorator to turn generator functions into context managers!

Advanced NumPy

Author: Pauli Virtanen


NumPy is at the base of Python’s scientific stack of tools. Its purpose to implement efficient operations
on many items in a block of memory. Understanding how it works in detail helps in making efficient use
of its flexibility, taking useful shortcuts.
This section covers:
• Anatomy of NumPy arrays, and its consequences. Tips and tricks.
• Universal functions: what, why, and what to do if you want a new one.
• Integration with other tools: NumPy offers several ways to wrap any data in an ndarray, without
unnecessary copies.
• Recently added features, and what’s in them: PEP 3118 buffers, generalized ufuncs, . . .

Prerequisites

• NumPy
• Cython
• Pillow (Python imaging library, used in a couple of examples)

Chapter contents

• Life of ndarray
– It’s. . .

7.3. Context managers 314 315


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

– Block of memory
– Data types
– Indexing scheme: strides
– Findings in dissection
• Universal functions
– What they are?
– Exercise: building an ufunc from scratch
– Solution: building an ufunc from scratch typedef struct PyArrayObject {
– Generalized ufuncs PyObject_HEAD

• Interoperability features /* Block of memory */


– Sharing multidimensional, typed data char *data;

– The old buffer protocol /* Data type descriptor */


– The old buffer protocol PyArray_Descr *descr;

– Array interface protocol /* Indexing scheme */


• Array siblings: chararray, maskedarray int nd;
npy_intp *dimensions;
– chararray: vectorized string operations npy_intp *strides;
– masked_array missing data
/* Other stuff */
– recarray: purely convenience PyObject *base;
• Summary int flags;
PyObject *weakreflist;
• Contributing to NumPy/SciPy } PyArrayObject;
– Why
– Reporting bugs
8.1.2 Block of memory
– Contributing to documentation
– Contributing features >>> x = np.array([1, 2, 3], dtype=np.int32)
>>> x.data
– How to help, in general
<... at ...>
>>> bytes(x.data)
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'
Tip: In this section, NumPy will be imported as follows:
Memory address of the data:
>>> import numpy as np
>>> x.__array_interface__['data'][0]
64803824

The whole __array_interface__:


8.1 Life of ndarray
>>> x.__array_interface__
{'data': (..., False), 'strides': None, 'descr': [('', '<i4')], 'typestr': '<i4',
8.1.1 It’s. . . ˓→'shape': (3,), 'version': 3}

ndarray = Reminder: two ndarrays may share the same memory:


block of memory + indexing scheme + data type descriptor
>>> x = np.array([1, 2, 3, 4])
• raw data >>> y = x[:-1]
>>> x[0] = 9
• how to locate an element
>>> y
• how to interpret an element array([9, 2, 3])

8.1. Life of ndarray 316 8.1. Life of ndarray 317


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Memory does not need to be owned by an ndarray: Example: reading .wav files

>>> x = b'1234' The .wav file header:

x is a string (in Python 3 a bytes), we can represent its data as an array of ints:
chunk_id "RIFF"
>>> y = np.frombuffer(x, dtype=np.int8) chunk_size 4-byte unsigned little-endian integer
>>> y.data format "WAVE"
<... at ...> fmt_id "fmt "
>>> y.base is x fmt_size 4-byte unsigned little-endian integer
True audio_fmt 2-byte unsigned little-endian integer
num_channels 2-byte unsigned little-endian integer
>>> y.flags sample_rate 4-byte unsigned little-endian integer
C_CONTIGUOUS : True byte_rate 4-byte unsigned little-endian integer
F_CONTIGUOUS : True block_align 2-byte unsigned little-endian integer
OWNDATA : False bits_per_sample 2-byte unsigned little-endian integer
WRITEABLE : False data_id "data"
ALIGNED : True data_size 4-byte unsigned little-endian integer
WRITEBACKIFCOPY : False
• 44-byte block of raw data (in the beginning of the file)
The owndata and writeable flags indicate status of the memory block. • . . . followed by data_size bytes of actual sound data.
See also: The .wav file header as a NumPy structured data type:
array interface
>>> wav_header_dtype = np.dtype([
... ("chunk_id", (bytes, 4)), # flexible-sized scalar type, item size 4
8.1.3 Data types ... ("chunk_size", "<u4"), # little-endian unsigned 32-bit integer
... ("format", "S4"), # 4-byte string
... ("fmt_id", "S4"),
The descriptor
... ("fmt_size", "<u4"),
... ("audio_fmt", "<u2"), #
dtype describes a single item in the array:
... ("num_channels", "<u2"), # .. more of the same ...
... ("sample_rate", "<u4"), #
type scalar type of the data, one of: ... ("byte_rate", "<u4"),
int8, int16, float64, et al. (fixed size) ... ("block_align", "<u2"),
str, unicode, void (flexible size) ... ("bits_per_sample", "<u2"),
itemsize size of the data block ... ("data_id", ("S1", (2, 2))), # sub-array, just for fun!
byte- byte order: big-endian > / little-endian < / not applicable | ... ("data_size", "u4"),
order ... #
fields sub-dtypes, if it’s a structured data type ... # the sound data itself cannot be represented here:
shape shape of the array, if it’s a sub-array ... # it does not have a fixed size
... ])

>>> np.dtype(int).type See also:


<class 'numpy.int64'>
>>> np.dtype(int).itemsize wavreader.py
8
>>> wav_header_dtype['format']
>>> np.dtype(int).byteorder
dtype('S4')
'='
>>> wav_header_dtype.fields
mappingproxy({'chunk_id': (dtype('S4'), 0), 'chunk_size': (dtype('uint32'), 4),
˓→'format': (dtype('S4'), 8), 'fmt_id': (dtype('S4'), 12), 'fmt_size': (dtype('uint32

˓→'), 16), 'audio_fmt': (dtype('uint16'), 20), 'num_channels': (dtype('uint16'), 22),

˓→'sample_rate': (dtype('uint32'), 24), 'byte_rate': (dtype('uint32'), 28), 'block_

˓→align': (dtype('uint16'), 32), 'bits_per_sample': (dtype('uint16'), 34), 'data_id':␣

˓→(dtype(('S1', (2, 2))), 36), 'data_size': (dtype('uint32'), 40)})

>>> wav_header_dtype.fields['format']
(dtype('S4'), 8)

• The first element is the sub-dtype in the structured data, corresponding to the name format

8.1. Life of ndarray 318 8.1. Life of ndarray 319


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• The second one is its offset (in bytes) from the beginning of the item Casting

Exercise • Casting in arithmetic, in nutshell:


– only type (not value!) of operands matters
Mini-exercise, make a “sparse” dtype by using offsets, and only some of the fields:
– largest “safe” type able to represent both is picked
>>> wav_header_dtype = np.dtype(dict(
... names=['format', 'sample_rate', 'data_id'], – scalars can “lose” to arrays in some situations
... offsets=[offset_1, offset_2, offset_3], # counted from start of structure in␣ • Casting in general copies data:
˓→bytes

... formats=list of dtypes for each of the fields, >>> x = np.array([1, 2, 3, 4], dtype=float)
... )) >>> x
array([1., 2., 3., 4.])
and use that to read the sample rate, and data_id (as sub-array). >>> y = x.astype(np.int8)
>>> y
array([1, 2, 3, 4], dtype=int8)
>>> f = open('data/test.wav', 'r')
>>> y + 1
>>> wav_header = np.fromfile(f, dtype=wav_header_dtype, count=1)
array([2, 3, 4, 5], dtype=int8)
>>> f.close()
>>> y + 256
>>> print(wav_header)
array([257, 258, 259, 260], dtype=int16)
[ ('RIFF', 17402L, 'WAVE', 'fmt ', 16L, 1, 1, 16000L, 32000L, 2, 16, [['d', 'a'], ['t
>>> y + 256.0
˓→', 'a']], 17366L)]
array([257., 258., 259., 260.])
>>> wav_header['sample_rate']
>>> y + np.array([256], dtype=np.int32)
array([16000], dtype=uint32)
array([257, 258, 259, 260], dtype=int32)
Let’s try accessing the sub-array:
• Casting on setitem: dtype of the array is not changed on item assignment:
>>> wav_header['data_id'] >>> y[:] = y + 1.5
array([[['d', 'a'], >>> y
['t', 'a']]], array([2, 3, 4, 5], dtype=int8)
dtype='|S1')
>>> wav_header.shape
(1,)
Note: Exact rules: see NumPy documentation
>>> wav_header['data_id'].shape
(1, 2, 2)

When accessing sub-arrays, the dimensions get added to the end! Re-interpretation / viewing

Note: There are existing modules such as wavfile, audiolab, etc. for loading sound data. . . • Data block in memory (4 bytes)

0x01 || 0x02 || 0x03 || 0x04


Casting and re-interpretation/views
– 4 of uint8, OR,
casting – 4 of int8, OR,
• on assignment – 2 of int16, OR,
• on array construction – 1 of int32, OR,
• on arithmetic – 1 of float32, OR,
• etc. – ...
• and manually: .astype(dtype) How to switch from one to another?
data re-interpretation 1. Switch the dtype:
• manually: .view(dtype) >>> x = np.array([1, 2, 3, 4], dtype=np.uint8)
>>> x.dtype = "<i2"
>>> x
(continues on next page)

8.1. Life of ndarray 320 8.1. Life of ndarray 321


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


array([ 513, 1027], dtype=int16) >>> assert (y['b'] == 3).all()
>>> 0x0201, 0x0403 >>> assert (y['a'] == 4).all()
(513, 1027)
Solution

0x01 0x02 || 0x03 0x04 >>> y = x.view([('r', 'i1'),


... ('g', 'i1'),
... ('b', 'i1'),
Note: little-endian: least significant byte is on the left in memory ... ('a', 'i1')]
... )[:, :, 0]

2. Create a new view of type uint32, shorthand i4:

>>> y = x.view("<i4") Warning: Another two arrays, each occupying exactly 4 bytes of memory:
>>> y >>> x = np.array([[1, 3], [2, 4]], dtype=np.uint8)
array([67305985], dtype=int32) >>> x
>>> 0x04030201 array([[1, 3],
67305985 [2, 4]], dtype=uint8)
>>> y = x.transpose()
>>> y
0x01 0x02 0x03 0x04 array([[1, 2],
[3, 4]], dtype=uint8)

We view the elements of x (1 byte each) as int16 (2 bytes each):


Note:
>>> x.view(np.int16)
• .view() makes views, does not copy (or alter) the memory block
array([[ 769],
• only changes the dtype (and adjusts array shape): [1026]], dtype=int16)

>>> x[1] = 5 What is happening here? Take a look at the bytes stored in memory by x:
>>> y
>>> x.tobytes()
array([328193], dtype=int32)
b'\x01\x03\x02\x04'
>>> y.base is x
True The \x stands for heXadecimal, so what we are seeing is:
0x01 0x03 0x02 0x04

We ask NumPy to interpret these bytes as elements of dtype int16—each of which occupies two
Mini-exercise: data re-interpretation bytes in memory. Therefore, 0x01 0x03 becomes the first uint16 and 0x02 0x04 the second.

See also: You may then expect to see 0x0103 (259, when converting from hexadecimal to decimal) as the first
result. But your computer likely stores most significant bytes first, and as such reads the number as
view-colors.py 0x0301 or 769 (go on and type 0x0301 into your Python terminal to verify).
You have RGBA data in an array: We can do the same on a copy of y (why doesn’t it work on y directly?):
>>> x = np.zeros((10, 10, 4), dtype=np.int8) >>> y.copy().view(np.int16)
>>> x[:, :, 0] = 1 array([[ 513],
>>> x[:, :, 1] = 2 [1027]], dtype=int16)
>>> x[:, :, 2] = 3
>>> x[:, :, 3] = 4 Can you explain these numbers, 513 and 1027, as well as the output shape of the resulting array?

where the last three dimensions are the R, B, and G, and alpha channels.
How to make a (10, 10) structured array with field names ‘r’, ‘g’, ‘b’, ‘a’ without copying data?

>>> y = ...

>>> assert (y['r'] == 1).all()


>>> assert (y['g'] == 2).all()
(continues on next page)

8.1. Life of ndarray 322 8.1. Life of ndarray 323


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

8.1.4 Indexing scheme: strides – C: last dimensions vary fastest (= smaller strides)
– F: first dimensions vary fastest
Main point
shape = (𝑑1 , 𝑑2 , ..., 𝑑𝑛 )
The question: strides = (𝑠1 , 𝑠2 , ..., 𝑠𝑛 )

>>> x = np.array([[1, 2, 3], 𝑠𝐶


𝑗 = 𝑑𝑗+1 𝑑𝑗+2 ...𝑑𝑛 × itemsize
... [4, 5, 6], 𝑠𝐹
𝑗 = 𝑑1 𝑑2 ...𝑑𝑗−1 × itemsize
... [7, 8, 9]], dtype=np.int8)
>>> x.tobytes('A')
Note: Now we can understand the behavior of .view():
b'\x01\x02\x03\x04\x05\x06\x07\x08\t'
>>> y = np.array([[1, 3], [2, 4]], dtype=np.uint8).transpose()
At which byte in ``x.data`` does the item ``x[1, 2]`` begin? >>> x = y.copy()

The answer (in NumPy) Transposition does not affect the memory layout of the data, only strides
• strides: the number of bytes to jump to find the next element
>>> x.strides
• 1 stride per dimension (2, 1)
>>> y.strides
>>> x.strides (1, 2)
(3, 1)
>>> byte_offset = 3 * 1 + 1 * 2 # to find x[1, 2]
>>> x.tobytes('A')
>>> x.flat[byte_offset]
b'\x01\x02\x03\x04'
6
>>> y.tobytes('A')
>>> x[1, 2]
b'\x01\x03\x02\x04'
6
• the results are different when interpreted as 2 of int16
simple, flexible
• .copy() creates new arrays in the C order (by default)
C and Fortran order

Note: In-place operations with views


Note: The Python built-in bytes returns bytes in C-order by default which can cause confusion when Prior to NumPy version 1.13, in-place operations with views could result in incorrect results for large
trying to inspect memory layout. We use numpy.ndarray.tobytes() with order=A instead, which arrays. Since version 1.13, NumPy includes checks for memory overlap to guarantee that results are
preserves the C or F ordering of the bytes in memory. consistent with the non in-place version (e.g. a = a + a.T produces the same result as a += a.T).
Note however that this may result in the data being copied (as if using a += a.T.copy()), ultimately
resulting in more memory being used than might otherwise be expected for in-place operations!
>>> x = np.array([[1, 2, 3],
... [4, 5, 6]], dtype=np.int16, order='C')
>>> x.strides
(6, 2) Slicing with integers
>>> x.tobytes('A')
b'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00' • Everything can be represented by changing only shape, strides, and possibly adjusting the data
pointer!
• Need to jump 6 bytes to find the next row
• Never makes copies of the data
• Need to jump 2 bytes to find the next column
>>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32)
>>> y = np.array(x, order='F') >>> y = x[::-1]
>>> y.strides >>> y
(2, 4) array([6, 5, 4, 3, 2, 1], dtype=int32)
>>> y.tobytes('A') >>> y.strides
b'\x01\x00\x04\x00\x02\x00\x05\x00\x03\x00\x06\x00' (-4,)

• Need to jump 2 bytes to find the next row >>> y = x[2:]


• Need to jump 4 bytes to find the next column >>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0]
8
• Similarly to higher dimensions: (continues on next page)

8.1. Life of ndarray 324 8.1. Life of ndarray 325


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) See also:


stride-fakedims.py
>>> x = np.zeros((10, 10, 10), dtype=float)
>>> x.strides Exercise
(800, 80, 8)
array([1, 2, 3, 4], dtype=np.int8)
>>> x[::2,::3,::4].strides
(1600, 240, 32)
-> array([[1, 2, 3, 4],
[1, 2, 3, 4],
• Similarly, transposes never make copies (it just swaps strides):
[1, 2, 3, 4]], dtype=np.int8)
>>> x = np.zeros((10, 10, 10), dtype=float)
>>> x.strides using only as_strided.:
(800, 80, 8)
Hint: byte_offset = stride[0]*index[0] + stride[1]*index[1] + ...
>>> x.T.strides
(8, 80, 800)
Spoiler
But: not all reshaping operations can be represented by playing with strides: Stride can also be 0 :

>>> a = np.arange(6, dtype=np.int8).reshape(3, 2) >>> x = np.array([1, 2, 3, 4], dtype=np.int8)


>>> b = a.T >>> y = as_strided(x, strides=(0, 1), shape=(3, 4))
>>> b.strides >>> y
(1, 2) array([[1, 2, 3, 4],
[1, 2, 3, 4],
So far, so good. However: [1, 2, 3, 4]], dtype=int8)
>>> y.base.base is x
>>> bytes(a.data) True
b'\x00\x01\x02\x03\x04\x05'
>>> b
array([[0, 2, 4],
Broadcasting
[1, 3, 5]], dtype=int8)
>>> c = b.reshape(3*2)
• Doing something useful with it: outer product of [1, 2, 3, 4] and [5, 6, 7]
>>> c
array([0, 2, 4, 1, 3, 5], dtype=int8) >>> x = np.array([1, 2, 3, 4], dtype=np.int16)
>>> x2 = as_strided(x, strides=(0, 1*2), shape=(3, 4))
Here, there is no way to represent the array c given one stride and the block of memory for a. Therefore, >>> x2
the reshape operation needs to make a copy here. array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]], dtype=int16)
Example: fake dimensions with strides

Stride manipulation >>> y = np.array([5, 6, 7], dtype=np.int16)


>>> y2 = as_strided(y, strides=(1*2, 0), shape=(3, 4))
>>> y2
>>> from numpy.lib.stride_tricks import as_strided
array([[5, 5, 5, 5],
>>> help(as_strided)
[6, 6, 6, 6],
Help on function as_strided in module numpy.lib.stride_tricks:
[7, 7, 7, 7]], dtype=int16)
...

>>> x2 * y2
array([[ 5, 10, 15, 20],
Warning: as_strided does not check that you stay inside the memory block bounds. . .
[ 6, 12, 18, 24],
[ 7, 14, 21, 28]], dtype=int16)
>>> x = np.array([1, 2, 3, 4], dtype=np.int16)
>>> as_strided(x, strides=(2*2, ), shape=(2, ))
array([1, 3], dtype=int16)
>>> x[::2]
array([1, 3], dtype=int16)

8.1. Life of ndarray 326 8.1. Life of ndarray 327


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

. . . seems somehow familiar . . .


See also:
>>> x = np.array([1, 2, 3, 4], dtype=np.int16)
>>> y = np.array([5, 6, 7], dtype=np.int16) stride-diagonals.py
>>> x[np.newaxis,:] * y[:,np.newaxis] Challenge
array([[ 5, 10, 15, 20],
[ 6, 12, 18, 24], Compute the tensor trace:
[ 7, 14, 21, 28]], dtype=int16)
>>> x = np.arange(5*5*5*5).reshape(5, 5, 5, 5)
>>> s = 0
• Internally, array broadcasting is indeed implemented using 0-strides. >>> for i in range(5):
... for j in range(5):
More tricks: diagonals ... s += x[j, i, j, i]

See also: by striding, and using sum() on the result.

stride-diagonals.py >>> y = as_strided(x, shape=(5, 5), strides=(TODO, TODO))


>>> s2 = ...
Challenge
>>> assert s == s2
• Pick diagonal entries of the matrix: (assume C memory order):
Solution
>>> x = np.array([[1, 2, 3],
... [4, 5, 6], >>> y = as_strided(x, shape=(5, 5), strides=((5*5*5 + 5)*x.itemsize,
... [7, 8, 9]], dtype=np.int32) ... (5*5 + 1)*x.itemsize))
>>> s2 = y.sum()
>>> x_diag = as_strided(x, shape=(3,), strides=(???,))

• Pick the first super-diagonal entries [2, 6]. CPU cache effects
• And the sub-diagonals?
Memory layout can affect performance:
(Hint to the last two: slicing first moves the point where striding
starts from.) In [1]: x = np.zeros((20000,))
Solution In [2]: y = np.zeros((20000*67,))[::67]
Pick diagonals:
In [3]: x.shape, y.shape
>>> x_diag = as_strided(x, shape=(3, ), strides=((3+1)*x.itemsize, )) Out[3]: ((20000,), (20000,))
>>> x_diag
array([1, 5, 9], dtype=int32) In [4]: %timeit x.sum()
5.13 us +- 14.3 ns per loop (mean +- std. dev. of 7 runs, 100,000 loops each)
Slice first, to adjust the data pointer:
In [5]: %timeit y.sum()
>>> as_strided(x[0, 1:], shape=(2, ), strides=((3+1)*x.itemsize, )) 22.3 us +- 1.43 us per loop (mean +- std. dev. of 7 runs, 10,000 loops each)
array([2, 6], dtype=int32)
In [6]: x.strides, y.strides
>>> as_strided(x[1:, 0], shape=(2, ), strides=((3+1)*x.itemsize, )) Out[6]: ((8,), (536,))
array([4, 8], dtype=int32)

Smaller strides are faster?


Note: Using np.diag

>>> y = np.diag(x, k=1)


>>> y
array([2, 6], dtype=int32)

However,

>>> y.flags.owndata
False

8.1. Life of ndarray 328 8.1. Life of ndarray 329


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• CPU pulls data from main memory to its cache in blocks Parts of an Ufunc
• If many array items consecutively operated on fit in a single block (small stride):
1. Provided by user
– ⇒ fewer transfers needed
void ufunc_loop(void **args, int *dimensions, int *steps, void *data)
– ⇒ faster {
See also: /*
* int8 output = elementwise_function(int8 input_1, int8 input_2)
• numexpr is designed to mitigate cache effects when evaluating array expressions. *
• numba is a compiler for Python code, that is aware of numpy arrays. * This function must compute the ufunc for many values at once,
* in the way shown below.
*/
8.1.5 Findings in dissection char *input_1 = (char*)args[0];
char *input_2 = (char*)args[1];
char *output = (char*)args[2];
int i;

for (i = 0; i < dimensions[0]; ++i) {


*output = elementwise_function(*input_1, *input_2);
input_1 += steps[0];
input_2 += steps[1];
output += steps[2];
}
}

• memory block: may be shared, .base, .data 2. The NumPy part, built by
• data type descriptor: structured data, sub-arrays, byte order, casting, viewing, .astype(), .view() char types[3]
• strided indexing: strides, C/F-order, slicing w/ integers, as_strided, broadcasting, stride tricks,
diag, CPU cache coherence types[0] = NPY_BYTE /* type of first input arg */
types[1] = NPY_BYTE /* type of second input arg */
types[2] = NPY_BYTE /* type of third input arg */
8.2 Universal functions PyObject *python_ufunc = PyUFunc_FromFuncAndData(
ufunc_loop,
8.2.1 What they are? NULL,
types,
• Ufunc performs and elementwise operation on all elements of an array. 1, /* ntypes */
2, /* num_inputs */
Examples: 1, /* num_outputs */
identity_element,
np.add, np.subtract, scipy.special.*, ...
name,
docstring,
• Automatically support: broadcasting, casting, . . . unused)
• The author of an ufunc only has to supply the elementwise operation, NumPy takes care of the
rest. • A ufunc can also support multiple different input-output type combinations.
• The elementwise operation needs to be implemented in C (or, e.g., Cython)

8.2. Universal functions 330 8.2. Universal functions 331


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Making it easier (continued from previous page)


# The elementwise function
3. ufunc_loop is of very generic form, and NumPy provides pre-made ones # ------------------------

PyUfunc_f_f float elementwise_func(float input_1) cdef void mandel_single_point(double complex *z_in,


PyUfunc_ff_f float elementwise_func(float input_1, float input_2) double complex *c_in,
PyUfunc_d_d double elementwise_func(double input_1) double complex *z_out) nogil:
PyUfunc_dd_d double elementwise_func(double input_1, double input_2) #
PyUfunc_D_D elementwise_func(npy_cdouble *input, npy_cdouble* output) # The Mandelbrot iteration
PyUfunc_DD_D elementwise_func(npy_cdouble *in1, npy_cdouble *in2, npy_cdouble* #
out)
#
• Only elementwise_func needs to be supplied # Some points of note:
#
• . . . except when your elementwise function is not in one of the above forms # - It's *NOT* allowed to call any Python functions here.
#
# The Ufunc loop runs with the Python Global Interpreter Lock released.
8.2.2 Exercise: building an ufunc from scratch # Hence, the ``nogil``.
#
The Mandelbrot fractal is defined by the iteration # - And so all local variables must be declared with ``cdef``
#
𝑧 ← 𝑧2 + 𝑐 # - Note also that this function receives *pointers* to the data
#
where 𝑐 = 𝑥 + 𝑖𝑦 is a complex number. This iteration is repeated – if 𝑧 stays finite no matter how long
the iteration runs, 𝑐 belongs to the Mandelbrot set. cdef double complex z = z_in[0]
• Make ufunc called mandel(z0, c) that computes: cdef double complex c = c_in[0]
cdef int k # the integer we use in the for loop
z = z0
for k in range(iterations): #
z = z*z + c # TODO: write the Mandelbrot iteration for one point here,
# as you would write it in Python.
say, 100 iterations or until z.real**2 + z.imag**2 > 1000. Use it to determine which c are in #
the Mandelbrot set. # Say, use 100 as the maximum number of iterations, and 1000
# as the cutoff for z.real**2 + z.imag**2.
• Our function is a simple one, so make use of the PyUFunc_* helpers.
#
• Write it in Cython
TODO: mandelbrot iteration should go here
See also:
mandel.pyx, mandelplot.py # Return the answer for this point
z_out[0] = z
#
# Fix the parts marked by TODO
# # Boilerplate Cython definitions
#
# # Pulls definitions from the NumPy C headers.
# Compile this file by (Cython >= 0.12 required because of the complex vars) # -------------------------------------------
#
# cython mandel.pyx from numpy cimport import_array, import_ufunc
# python setup.py build_ext -i from numpy cimport (PyUFunc_FromFuncAndData,
# PyUFuncGenericFunction)
# and try it out with, in this directory, from numpy cimport NPY_CDOUBLE, NP_DOUBLE, NPY_LONG
#
# >>> import mandel # Import all pre-defined loop functions
# >>> mandel.mandel(0, 1 + 2j) # you won't need all of them - keep the relevant ones
#
# from numpy cimport (
PyUFunc_f_f_As_d_d,
(continues on next page)
(continues on next page)

8.2. Universal functions 332 8.2. Universal functions 333


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


PyUFunc_d_d, loop_func[0] = ... TODO: suitable PyUFunc_* ...
PyUFunc_f_f, input_output_types[0] = ... TODO ...
PyUFunc_g_g, ... TODO: fill in rest of input_output_types ...
PyUFunc_F_F_As_D_D,
PyUFunc_F_F, # This thing is passed as the ``data`` parameter for the generic
PyUFunc_D_D, # PyUFunc_* loop, to let it know which function it should call.
PyUFunc_G_G, elementwise_funcs[0] = <void*>mandel_single_point
PyUFunc_ff_f_As_dd_d,
PyUFunc_ff_f, # Construct the ufunc:
PyUFunc_dd_d,
PyUFunc_gg_g, mandel = PyUFunc_FromFuncAndData(
PyUFunc_FF_F_As_DD_D, loop_func,
PyUFunc_DD_D, elementwise_funcs,
PyUFunc_FF_F, input_output_types,
PyUFunc_GG_G) 1, # number of supported input types
TODO, # number of input args
TODO, # number of output args
# Required module initialization 0, # `identity` element, never mind this
# ------------------------------ "mandel", # function name
"mandel(z, c) -> computes z*z + c", # docstring
import_array() 0 # unused
import_ufunc() )

Reminder: some pre-made Ufunc loops:


# The actual ufunc declaration
# ----------------------------
PyUfunc_f_f float elementwise_func(float input_1)
PyUfunc_ff_f float elementwise_func(float input_1, float input_2)
cdef PyUFuncGenericFunction loop_func[1]
PyUfunc_d_d double elementwise_func(double input_1)
cdef char input_output_types[3]
PyUfunc_dd_d double elementwise_func(double input_1, double input_2)
cdef void *elementwise_funcs[1]
PyUfunc_D_D elementwise_func(complex_double *input, complex_double* output)
PyUfunc_DD_D elementwise_func(complex_double *in1, complex_double *in2,
#
complex_double* out)
# Reminder: some pre-made Ufunc loops:
#
# ================ ======================================================= Type codes:
# ``PyUfunc_f_f`` ``float elementwise_func(float input_1)``
# ``PyUfunc_ff_f`` ``float elementwise_func(float input_1, float input_2)`` NPY_BOOL, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT,
# ``PyUfunc_d_d`` ``double elementwise_func(double input_1)`` NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE,
# ``PyUfunc_dd_d`` ``double elementwise_func(double input_1, double input_2)`` NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_DATETIME,
# ``PyUfunc_D_D`` ``elementwise_func(complex_double *input, complex_double* complex_ NPY_TIMEDELTA, NPY_OBJECT, NPY_STRING, NPY_UNICODE, NPY_VOID
˓→double)``

# ``PyUfunc_DD_D`` ``elementwise_func(complex_double *in1, complex_double *in2,␣


˓→complex_double* out)`` 8.2.3 Solution: building an ufunc from scratch
# ================ =======================================================
# # The elementwise function
# The full list is above. # ------------------------
#
# cdef void mandel_single_point(double complex *z_in,
# Type codes: double complex *c_in,
# double complex *z_out) nogil:
# NPY_BOOL, NPY_BYTE, NPY_UBYTE, NPY_SHORT, NPY_USHORT, NPY_INT, NPY_UINT, #
# NPY_LONG, NPY_ULONG, NPY_LONGLONG, NPY_ULONGLONG, NPY_FLOAT, NPY_DOUBLE, # The Mandelbrot iteration
# NPY_LONGDOUBLE, NPY_CFLOAT, NPY_CDOUBLE, NPY_CLONGDOUBLE, NPY_DATETIME, #
# NPY_TIMEDELTA, NPY_OBJECT, NPY_STRING, NPY_UNICODE, NPY_VOID
# #
# Some points of note:
(continues on next page) (continues on next page)

8.2. Universal functions 334 8.2. Universal functions 335


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


# input_output_types[2] = NPY_CDOUBLE
# - It's *NOT* allowed to call any Python functions here.
# elementwise_funcs[0] = <void*>mandel_single_point
# The Ufunc loop runs with the Python Global Interpreter Lock released.
# Hence, the ``nogil``. mandel = PyUFunc_FromFuncAndData(
# loop_func,
# - And so all local variables must be declared with ``cdef`` elementwise_funcs,
# input_output_types,
# - Note also that this function receives *pointers* to the data; 1, # number of supported input types
# the "traditional" solution to passing complex variables around 2, # number of input args
# 1, # number of output args
0, # `identity` element, never mind this
cdef double complex z = z_in[0] "mandel", # function name
cdef double complex c = c_in[0] "mandel(z, c) -> computes iterated z*z + c", # docstring
cdef int k # the integer we use in the for loop 0 # unused
)
# Straightforward iteration
"""
for k in range(100): Plot Mandelbrot
z = z*z + c ================
if z.real**2 + z.imag**2 > 1000:
break Plot the Mandelbrot ensemble.

# Return the answer for this point """


z_out[0] = z
import numpy as np
import mandel
# Boilerplate Cython definitions
# x = np.linspace(-1.7, 0.6, 1000)
# Pulls definitions from the NumPy C headers. y = np.linspace(-1.4, 1.4, 1000)
# ------------------------------------------- c = x[None, :] + 1j * y[:, None]
z = mandel.mandel(c, c)
from numpy cimport import_array, import_ufunc
from numpy cimport (PyUFunc_FromFuncAndData, import matplotlib.pyplot as plt
PyUFuncGenericFunction)
from numpy cimport NPY_CDOUBLE plt.imshow(abs(z) ** 2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4])
from numpy cimport PyUFunc_DD_D plt.gray()
plt.show()
# Required module initialization
# ------------------------------

import_array()
import_ufunc()

# The actual ufunc declaration


# ----------------------------

cdef PyUFuncGenericFunction loop_func[1]


cdef char input_output_types[3]
cdef void *elementwise_funcs[1]

loop_func[0] = PyUFunc_DD_D

input_output_types[0] = NPY_CDOUBLE
input_output_types[1] = NPY_CDOUBLE Note: Most of the boilerplate could be automated by these Cython modules:
(continues on next page)

8.2. Universal functions 336 8.2. Universal functions 337


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

https://github.com/cython/cython/wiki/MarkLodato-CreatingUfuncs 8.2.4 Generalized ufuncs

ufunc
Several accepted input types output = elementwise_function(input)
Both output and input can be a single array element only.
E.g. supporting both single- and double-precision versions
generalized ufunc
cdef void mandel_single_point(double complex *z_in,
double complex *c_in, output and input can be arrays with a fixed number of dimensions
double complex *z_out) nogil: For example, matrix trace (sum of diag elements):
...
input shape = (n, n)
cdef void mandel_single_point_singleprec(float complex *z_in, output shape = () i.e. scalar
float complex *c_in,
float complex *z_out) nogil: (n, n) -> ()
...
Matrix product:
cdef PyUFuncGenericFunction loop_funcs[2]
cdef char input_output_types[3*2] input_1 shape = (m, n)
cdef void *elementwise_funcs[1*2] input_2 shape = (n, p)
output shape = (m, p)
loop_funcs[0] = PyUFunc_DD_D
input_output_types[0] = NPY_CDOUBLE (m, n), (n, p) -> (m, p)
input_output_types[1] = NPY_CDOUBLE
input_output_types[2] = NPY_CDOUBLE • This is called the “signature” of the generalized ufunc
elementwise_funcs[0] = <void*>mandel_single_point • The dimensions on which the g-ufunc acts, are “core dimensions”

loop_funcs[1] = PyUFunc_FF_F
input_output_types[3] = NPY_CFLOAT Status in NumPy
input_output_types[4] = NPY_CFLOAT
input_output_types[5] = NPY_CFLOAT • g-ufuncs are in NumPy already . . .
elementwise_funcs[1] = <void*>mandel_single_point_singleprec
• new ones can be created with PyUFunc_FromFuncAndDataAndSignature
mandel = PyUFunc_FromFuncAndData( • most linear-algebra functions are implemented as g-ufuncs to enable working with stacked arrays:
loop_func,
elementwise_funcs, >>> import numpy as np
input_output_types, >>> rng = np.random.default_rng(27446968)
2, # number of supported input types <---------------- >>> np.linalg.det(rng.random((3, 5, 5)))
2, # number of input args array([ 0.01829761, -0.0077266 , -0.05336566])
1, # number of output args >>> np.linalg._umath_linalg.det.signature
0, # `identity` element, never mind this '(m,m)->()'
"mandel", # function name
"mandel(z, c) -> computes iterated z*z + c", # docstring • matrix multiplication this way could be useful for operating on many small matrices at once
0 # unused • Also see tensordot and einsum
)

Generalized ufunc loop

Matrix multiplication (m,n),(n,p) -> (m,p)

void gufunc_loop(void **args, int *dimensions, int *steps, void *data)


{
char *input_1 = (char*)args[0]; /* these are as previously */
char *input_2 = (char*)args[1];
char *output = (char*)args[2];

int input_1_stride_m = steps[3]; /* strides for the core dimensions */


(continues on next page)

8.2. Universal functions 338 8.2. Universal functions 339


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> from PIL import Image
int input_1_stride_n = steps[4]; /* are added after the non-core */ >>> data = np.zeros((200, 200, 4), dtype=np.uint8)
int input_2_strides_n = steps[5]; /* steps */ >>> data[:, :] = [255, 0, 0, 255] # Red
int input_2_strides_p = steps[6]; >>> # In PIL, RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA]
int output_strides_n = steps[7]; >>> data = data.view(np.int32).squeeze()
int output_strides_p = steps[8]; >>> img = Image.frombuffer("RGBA", (200, 200), data, "raw", "RGBA", 0, 1)
>>> img.save('test.png')
int m = dimension[1]; /* core dimensions are added after */
int n = dimension[2]; /* the main dimension; order as in */ Q:
int p = dimension[3]; /* signature */
Check what happens if data is now modified, and img saved again.
int i;

for (i = 0; i < dimensions[0]; ++i) { 8.3.3 The old buffer protocol


matmul_for_strided_matrices(input_1, input_2, output,
strides for each array...); """
From buffer
input_1 += steps[0]; ============
input_2 += steps[1];
output += steps[2]; Show how to exchange data between numpy and a library that only knows
} the buffer interface.
} """

import numpy as np
import Image
8.3 Interoperability features
# Let's make a sample image, RGBA format
8.3.1 Sharing multidimensional, typed data x = np.zeros((200, 200, 4), dtype=np.int8)
Suppose you
x[:, :, 0] = 254 # red
1. Write a library than handles (multidimensional) binary data, x[:, :, 3] = 255 # opaque
2. Want to make it easy to manipulate the data with NumPy, or whatever other library,
data = x.view(np.int32) # Check that you understand why this is OK!
3. . . . but would not like to have NumPy as a dependency.
img = Image.frombuffer("RGBA", (200, 200), data)
Currently, 3 solutions:
img.save("test.png")
1. the “old” buffer interface
#
2. the array interface
# Modify the original data, and save again.
3. the “new” buffer interface (PEP 3118) #
# It turns out that PIL, which knows next to nothing about NumPy,
# happily shares the same data.
8.3.2 The old buffer protocol #

• Only 1-D buffers x[:, :, 1] = 254


img.save("test2.png")
• No data type information
• C-level interface; PyBufferProcs tp_as_buffer in the type object
• But it’s integrated into Python (e.g. strings support it)
Mini-exercise using Pillow (Python Imaging Library):
See also:
pilbuffer.py

8.3. Interoperability features 340 8.3. Interoperability features 341


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


'typestr': '|u1'}
>>> x = np.asarray(img)
>>> x.shape
(200, 200, 4)

Note: A more C-friendly variant of the array interface is also defined.

8.4 Array siblings: chararray, maskedarray

8.4.1 chararray: vectorized string operations

>>> x = np.array(['a', ' bbb', ' ccc']).view(np.chararray)


>>> x.lstrip(' ')
chararray(['a', 'bbb', 'ccc'],
dtype='...')
>>> x.upper()
chararray(['A', ' BBB', ' CCC'],
dtype='...')

Note: .view() has a second meaning: it can make an ndarray an instance of a specialized ndarray
subclass
8.3.4 Array interface protocol

• Multidimensional buffers
8.4.2 masked_array missing data
• Data type information present
• NumPy-specific approach; slowly deprecated (but not going away) Masked arrays are arrays that may have missing or invalid entries.

• Not integrated in Python otherwise For example, suppose we have an array where the fourth entry is invalid:

See also: >>> x = np.array([1, 2, 3, -99, 5])


Documentation: https://numpy.org/doc/stable/reference/arrays.interface.html
One way to describe this is to create a masked array:
>>> x = np.array([[1, 2], [3, 4]])
>>> mx = np.ma.masked_array(x, mask=[0, 0, 0, 1, 0])
>>> x.__array_interface__
>>> mx
{'data': (171694552, False), # memory address of data, is readonly?
masked_array(data=[1, 2, 3, --, 5],
'descr': [('', '<i4')], # data type descriptor
mask=[False, False, False, True, False],
'typestr': '<i4', # same, in another form
fill_value=999999)
'strides': None, # strides; or None if in C-order
'shape': (2, 2),
'version': 3, Masked mean ignores masked data:
} >>> mx.mean()
2.75
:: >>> np.mean(mx)
2.75
>>> from PIL import Image
>>> img = Image.open('data/test.png')
>>> img.__array_interface__
{'version': 3, Warning: Not all NumPy functions respect masks, for instance np.dot, so check the return types.
'data': ...,
'shape': (200, 200, 4),
The masked_array returns a view to the original array:
(continues on next page)

8.3. Interoperability features 342 8.4. Array siblings: chararray, maskedarray 343
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> mx[1] = 9 Example: Masked statistics


>>> x
array([ 1, 9, 3, -99, 5]) Canadian rangers were distracted when counting hares and lynxes in 1903-1910 and 1917-1918, and
got the numbers are wrong. (Carrot farmers stayed alert, though.) Compute the mean populations
over time, ignoring the invalid numbers.
The mask >>> data = np.loadtxt('data/populations.txt')
>>> populations = np.ma.masked_array(data[:,1:])
You can modify the mask by assigning: >>> year = data[:, 0]

>>> mx[1] = np.ma.masked >>> bad_years = (((year >= 1903) & (year <= 1910))
>>> mx ... | ((year >= 1917) & (year <= 1918)))
masked_array(data=[1, --, 3, --, 5], >>> # '&' means 'and' and '|' means 'or'
mask=[False, True, False, True, False], >>> populations[bad_years, 0] = np.ma.masked
fill_value=999999) >>> populations[bad_years, 1] = np.ma.masked

The mask is cleared on assignment: >>> populations.mean(axis=0)


masked_array(data=[40472.72727272727, 18627.272727272728, 42400.0],
>>> mx[1] = 9 mask=[False, False, False],
>>> mx fill_value=1e+20)
masked_array(data=[1, 9, 3, --, 5],
mask=[False, False, False, True, False], >>> populations.std(axis=0)
fill_value=999999) masked_array(data=[21087.656489006717, 15625.799814240254, 3322.5062255844787],
mask=[False, False, False],
The mask is also available directly: fill_value=1e+20)
>>> mx.mask Note that Matplotlib knows about masked arrays:
array([False, False, False, True, False])
>>> plt.plot(year, populations, 'o-')
The masked entries can be filled with a given value to get an usual array back: [<matplotlib.lines.Line2D object at ...>, ...]

>>> x2 = mx.filled(-1)
>>> x2
array([ 1, 9, 3, -1, 5])

The mask can also be cleared:

>>> mx.mask = np.ma.nomask


>>> mx
masked_array(data=[1, 9, 3, -99, 5],
mask=[False, False, False, False, False],
fill_value=999999)

Domain-aware functions

The masked array package also contains domain-aware functions:

>>> np.ma.log(np.array([1, 2, -1, -2, 3, -5])) 8.4.3 recarray: purely convenience


masked_array(data=[0.0, 0.693147180559..., --, --, 1.098612288668..., --],
mask=[False, False, True, True, False, True], >>> arr = np.array([('a', 1), ('b', 2)], dtype=[('x', 'S1'), ('y', int)])
fill_value=1e+20) >>> arr2 = arr.view(np.recarray)
>>> arr2.x
array([b'a', b'b'], dtype='|S1')
Note: Streamlined and more seamless support for dealing with missing data in arrays is making its >>> arr2.y
way into NumPy 1.7. Stay tuned! array([1, 2])

8.4. Array siblings: chararray, maskedarray 344 8.4. Array siblings: chararray, maskedarray 345
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

8.5 Summary (continued from previous page)


This also happens with long arguments, and so
np.random.permutation(X.shape[0]) where X is an array fails on 64
• Anatomy of the ndarray: data, dtype, strides.
bit windows (where shape is a tuple of longs).
• Universal functions: elementwise operations, how to make new ones
It would be great if it could cast to integer or at least raise a
• Ndarray subclasses
proper error for non-integer types.
• Various buffer interfaces for integration with other tools
I'm using NumPy 1.4.1, built from the official tarball, on Windows
• Recent additions: PEP 3118, generalized ufuncs
64 with Visual studio 2008, on Python.org 64-bit Python.

0. What are you trying to do?


8.6 Contributing to NumPy/SciPy
1. Small code snippet reproducing the bug (if possible)
Get this tutorial: https://www.euroscipy.org/talk/882 • What actually happens
• What you’d expect
8.6.1 Why 2. Platform (Windows / Linux / OSX, 32/64 bits, x86/PPC, . . . )

• “There’s a bug?” 3. Version of NumPy/SciPy

• “I don’t understand what this is supposed to do?” >>> print(np.__version__)


1...
• “I have this fancy code. Would you like to have it?”
• “I’d like to help! What can I do?” Check that the following is what you expect

>>> print(np.__file__)
8.6.2 Reporting bugs /...

• Bug tracker (prefer this) In case you have old/broken NumPy installations lying around.
– https://github.com/numpy/numpy/issues If unsure, try to remove existing NumPy installations, and reinstall. . .
– https://github.com/scipy/scipy/issues
– Click the “Sign up” link to get an account 8.6.3 Contributing to documentation
• Mailing lists (https://numpy.org/community/) 1. Documentation editor
– If you’re unsure • https://numpy.org/doc/stable/
– No replies in a week or so? Just file a bug ticket. • Registration
– Register an account
Good bug report
– Subscribe to scipy-dev mailing list (subscribers-only)
Title: numpy.random.permutations fails for non-integer arguments – Problem with mailing lists: you get mail
∗ But: you can turn mail delivery off
I'm trying to generate random permutations, using numpy.random.permutations
∗ “change your subscription options”, at the bottom of
When calling numpy.random.permutation with non-integer arguments https://mail.python.org/mailman3/lists/scipy-dev.python.org/
it fails with a cryptic error message::
– Send a mail @ scipy-dev mailing list; ask for activation:
>>> rng.permutation(12)
array([ 2, 6, 4, 1, 8, 11, 10, 5, 9, 3, 7, 0]) To: [email protected]
>>> rng.permutation(12.) #doctest: +SKIP
Traceback (most recent call last): Hi,
File "<stdin>", line 1, in <module>
File "_generator.pyx", line 4844, in numpy.random._generator.Generator.permutation I'd like to edit NumPy/SciPy docstrings. My account is XXXXX
numpy.exceptions.AxisError: axis 0 is out of bounds for array of dimension 0
Cheers,
N. N.
(continues on next page)

8.5. Summary 346 8.6. Contributing to NumPy/SciPy 347


Scientific Python Lectures, Edition 2024.2rc0.dev0

• Check the style guide:


– https://numpy.org/doc/stable/
– Don’t be intimidated; to fix a small thing, just fix it
• Edit
2. Edit sources and send patches (as for bugs)

9
3. Complain on the mailing list

8.6.4 Contributing features


CHAPTER
The contribution of features is documented on https://numpy.org/doc/stable/dev/

8.6.5 How to help, in general

• Bug fixes always welcome!


– What irks you most
– Browse the tracker
• Documentation work
Debugging code
– API docs: improvements to docstrings
∗ Know some SciPy module well?
– User guide
∗ https://numpy.org/doc/stable/user/
• Ask on communication channels: Author: Gaël Varoquaux

– numpy-discussion list This section explores tools to understand better your code base: debugging, to find and fix bugs.

– scipy-dev list It is not specific to the scientific Python community, but the strategies that we will employ are tailored
to its needs.

Prerequisites

• NumPy
• IPython
• nosetests
• pyflakes
• gdb for the C-debugging part.

Chapter contents

• Avoiding bugs
– Coding best practices to avoid getting in trouble
– pyflakes: fast static analysis
• Debugging workflow
• Using the Python debugger
– Invoking the debugger

8.6. Contributing to NumPy/SciPy 348 349


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

– Debugger commands and interaction Running pyflakes on the current edited file

• Debugging segmentation faults using gdb You can bind a key to run pyflakes in the current buffer.
• In kate Menu: ‘settings -> configure kate
– In plugins enable ‘external tools’
9.1 Avoiding bugs
– In external Tools’, add pyflakes:

9.1.1 Coding best practices to avoid getting in trouble kdialog --title "pyflakes %f ilename" --msgbox "$(pyflakes %f ilename)"

• In TextMate
Brian Kernighan Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a shell variable:

“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes
as clever as you can be when you write it, how will you ever debug it?”
Then Ctrl-Shift-V is binded to a pyflakes report
• We all write buggy code. Accept it. Deal with it. • In vim In your .vimrc (binds F5 to pyflakes):
• Write your code with testing and debugging in mind. autocmd FileType python let &mp = 'echo "*** running % ***" ; pyflakes %'
• Keep It Simple, Stupid (KISS). autocmd FileType tex,mp,rst,python imap <Esc>[15~ <C-O>:make!^M
autocmd FileType tex,mp,rst,python map <Esc>[15~ :make!^M
– What is the simplest thing that could possibly work? autocmd FileType tex,mp,rst,python set autowrite
• Don’t Repeat Yourself (DRY).
• In emacs In your .emacs (binds F5 to pyflakes):
– Every piece of knowledge must have a single, unambiguous, authoritative representation within
a system. (defun pyflakes-thisfile () (interactive)
– Constants, algorithms, etc. . . (compile (format "pyflakes %s " (buffer-file-name)))
)
• Try to limit interdependencies of your code. (Loose Coupling)
• Give your variables, functions and modules meaningful names (not mathematics names) (define-minor-mode pyflakes-mode
"Toggle pyflakes mode.
With no argument, this command toggles the mode.
9.1.2 pyflakes: fast static analysis Non-null prefix argument turns on the mode.
Null prefix argument turns off the mode."
They are several static analysis tools in Python; to name a few: ;; The initial value.
nil
• pylint ;; The indicator for the mode line.
• pychecker " Pyflakes"
;; The minor mode bindings.
• pyflakes '( ([f5] . pyflakes-thisfile) )
• flake8 )

Here we focus on pyflakes, which is the simplest tool. (add-hook 'python-mode-hook (lambda () (pyflakes-mode t)))
• Fast, simple
• Detects syntax errors, missing imports, typos on names.
A type-as-go spell-checker like integration
Another good recommendation is the flake8 tool which is a combination of pyflakes and pep8. Thus, in
addition to the types of errors that pyflakes catches, flake8 detects violations of the recommendation in • In vim
PEP8 style guide.
– Use the pyflakes.vim plugin:
Integrating pyflakes (or flake8) in your editor or IDE is highly recommended, it does yield productivity
1. download the zip file from https://www.vim.org/scripts/script.php?script_id=2441
gains.
2. extract the files in ~/.vim/ftplugin/python
3. make sure your vimrc has filetype plugin indent on

9.1. Avoiding bugs 350 9.1. Avoiding bugs 351


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

9.3 Using the Python debugger

The python debugger, pdb: https://docs.python.org/3/library/pdb.html, allows you to inspect your code
interactively.
Specifically it allows you to:
– Alternatively: use the syntastic plugin. This can be configured to use flake8 too and also
• View the source code.
handles on-the-fly checking for many other languages.
• Walk up and down the call stack.
• Inspect values of variables.
• Modify values of variables.
• Set breakpoints.

print

Yes, print statements do work as a debugging tool. However to inspect runtime, it is often more
efficient to use the debugger.

• In emacs
9.3.1 Invoking the debugger
Use the flymake mode with pyflakes, documented on https://www.emacswiki.org/emacs/FlyMake
and included in Emacs 26 and more recent. To activate it, use M-x (meta-key then x) and enter
Ways to launch the debugger:
flymake-mode at the prompt. To enable it automatically when opening a Python file, add the
following line to your .emacs file: 1. Postmortem, launch debugger after module errors.

(add-hook 'python-mode-hook '(lambda () (flymake-mode))) 2. Launch the module with the debugger.
3. Call the debugger inside the module

9.2 Debugging workflow Postmortem

If you do have a non trivial bug, this is when debugging strategies kick in. There is no silver bullet. Yet, Situation: You’re working in IPython and you get a traceback.
strategies help: Here we debug the file index_error.py. When running it, an IndexError is raised. Type %debug and
For debugging a given problem, the favorable situation is when the problem is drop into the debugger.
isolated in a small number of lines of code, outside framework or application In [1]: %run index_error.py
code, with short modify-run-fail cycles ---------------------------------------------------------------------------
1. Make it fail reliably. Find a test case that makes the code fail every time. IndexError Traceback (most recent call last)
File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:10
2. Divide and Conquer. Once you have a failing test case, isolate the failing code. 6 print(lst[len(lst)])
• Which module. 9 if __name__ == "__main__":
---> 10 index_error()
• Which function.
• Which line of code. File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:6, in index_
˓→error()
=> isolate a small reproducible failure: a test case 4 def index_error():
3. Change one thing at a time and re-run the failing test case. 5 lst = list("foobar")
----> 6 print(lst[len(lst)])
4. Use the debugger to understand what is going wrong.
5. Take notes and be patient. It may take a while. IndexError: list index out of range

In [2]: %debug
Note: Once you have gone through this process: isolated a tight piece of code reproducing the bug > /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
and fix the bug using this piece of code, add the corresponding code to your test suite. ˓→py(6)index_error()

4 def index_error():
(continues on next page)

9.2. Debugging workflow 352 9.3. Using the Python debugger 353
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Step-by-step execution


5 lst = list("foobar")
----> 6 print(lst[len(lst)]) Situation: You believe a bug exists in a module but are not sure where.
7 For instance we are trying to debug wiener_filtering.py. Indeed the code runs, but the filtering does
8 not work well.
ipdb> list • Run the script in IPython with the debugger using %run -d wiener_filtering.py :
1 """Small snippet to raise an IndexError."""
In [1]: %run -d wiener_filtering.py
2
*** Blank or comment
3
*** Blank or comment
4 def index_error():
*** Blank or comment
5 lst = list("foobar")
NOTE: Enter 'c' at the ipdb> prompt to continue execution.
----> 6 print(lst[len(lst)])
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
7
˓→filtering.py(1)<module>()
8
----> 1 """Wiener filtering a noisy raccoon face: this module is buggy"""
9 if __name__ == "__main__":
2
10 index_error()
3 import numpy as np
4 import scipy as sp
ipdb> len(lst)
5 import matplotlib.pyplot as plt
6
ipdb> print(lst[len(lst) - 1])
r • Set a break point at line 29 using b 29:
ipdb> quit ipdb> n
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(3)<module>()
Post-mortem debugging without IPython 1 """Wiener filtering a noisy raccoon face: this module is buggy"""
2
In some situations you cannot use IPython, for instance to debug a script that wants to be called from ----> 3 import numpy as np
the command line. In this case, you can call the script with python -m pdb script.py: 4 import scipy as sp
$ python -m pdb index_error.py 5 import matplotlib.pyplot as plt
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.py(1)
˓→<module>()
ipdb> b 29
-> """Small snippet to raise an IndexError.""" Breakpoint 1 at /home/jarrod/src/scientific-python-lectures/advanced/debugging/
˓→wiener_filtering.py:29
(Pdb) continue
Traceback (most recent call last):
File "/usr/lib64/python3.11/pdb.py", line 1793, in main • Continue execution to next breakpoint with c(ont(inue)):
pdb._run(target)
File "/usr/lib64/python3.11/pdb.py", line 1659, in _run ipdb> c
self.run(target.code) > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(29)iterated_wiener()
File "/usr/lib64/python3.11/bdb.py", line 600, in run
exec(cmd, globals, locals) 27 Do not use this: this is crappy code to demo bugs!
File "<string>", line 1, in <module> 28 """
File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error. 1--> 29 noisy_img = noisy_img
˓→py", line 10, in <module>
30 denoised_img = local_mean(noisy_img, size=size)
index_error() 31 l_var = local_var(noisy_img, size=size)
File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
˓→py", line 6, in index_error
• Step into code with n(ext) and s(tep): next jumps to the next statement in the current execution
print(lst[len(lst)]) context, while step will go across execution contexts, i.e. enable exploring inside function calls:
~~~^^^^^^^^^^ ipdb> s
IndexError: list index out of range > /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
Uncaught exception. Entering post mortem debugging ˓→filtering.py(30)iterated_wiener()
Running 'cont' or 'step' will restart the program 28 """
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error. 1 29 noisy_img = noisy_img
˓→py(6)index_error()
---> 30 denoised_img = local_mean(noisy_img, size=size)
-> print(lst[len(lst)]) 31 l_var = local_var(noisy_img, size=size)
(Pdb) 32 for i in range(3):
(continues on next page)

9.3. Using the Python debugger 354 9.3. Using the Python debugger 355
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


File ~/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:35, in␣
ipdb> n ˓→iterated_wiener(noisy_img, size)

> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_ 33 res = noisy_img - denoised_img


˓→filtering.py(31)iterated_wiener() 34 noise = (res**2).sum() / res.size
1 29 noisy_img = noisy_img ---> 35 noise_level = 1 - noise / l_var
30 denoised_img = local_mean(noisy_img, size=size) 36 noise_level[noise_level < 0] = 0
---> 31 l_var = local_var(noisy_img, size=size) 37 denoised_img = np.int64(noise_level * res)
32 for i in range(3):
33 res = noisy_img - denoised_img FloatingPointError: divide by zero encountered in divide

• Step a few lines and explore the local variables:


ipdb> n Other ways of starting a debugger
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(32)iterated_wiener() • Raising an exception as a poor man break point
30 denoised_img = local_mean(noisy_img, size=size)
31 l_var = local_var(noisy_img, size=size) If you find it tedious to note the line number to set a break point, you can simply raise an exception
---> 32 for i in range(3): at the point that you want to inspect and use IPython’s %debug. Note that in this case you cannot
33 res = noisy_img - denoised_img step or continue the execution.
34 noise = (res**2).sum() / res.size • Debugging test failures using nosetests

ipdb> print(l_var) You can run nosetests --pdb to drop in post-mortem debugging on exceptions, and nosetests
[[2571 2782 3474 ... 3008 2922 3141] --pdb-failure to inspect test failures using the debugger.
[2105 708 475 ... 469 354 2884] In addition, you can use the IPython interface for the debugger in nose by installing the nose plugin
[1697 420 645 ... 273 236 2517] ipdbplugin. You can than pass --ipdb and --ipdb-failure options to nosetests.
...
[2437 345 432 ... 413 387 4188] • Calling the debugger explicitly
[2598 179 247 ... 367 441 3909] Insert the following line where you want to drop in the debugger:
[2808 2525 3117 ... 4413 4454 4385]]
ipdb> print(l_var.min()) import pdb; pdb.set_trace()
0

Oh dear, nothing but integers, and 0 variation. Here is our bug, we are doing integer arithmetic. Warning: When running nosetests, the output is captured, and thus it seems that the debugger
does not work. Simply run the nosetests with the -s flag.
Raising exception on numerical errors

When we run the wiener_filtering.py file, the following warnings are raised: Graphical debuggers and alternatives
In [2]: %run wiener_filtering.py
• pudb is a good semi-graphical debugger with a text user interface in the console.
/home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.
˓→py:35: RuntimeWarning: divide by zero encountered in divide • The Visual Studio Code integrated development environment includes a debugging mode.
noise_level = 1 - noise / l_var
• The Mu editor is a simple Python editor that includes a debugging mode.
We can turn these warnings in exception, which enables us to do post-mortem debugging on them,
and find our problem more quickly:
In [3]: np.seterr(all='raise')
Out[3]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} 9.3.2 Debugger commands and interaction

In [4]: %run wiener_filtering.py


--------------------------------------------------------------------------- l(list) Lists the code at the current position
FloatingPointError Traceback (most recent call last) u(p) Walk up the call stack
File ~/src/scientific-python-lectures/advanced/debugging/wiener_filtering.py:52 d(own) Walk down the call stack
49 plt.matshow(face[cut], cmap=plt.cm.gray) n(ext) Execute the next line (does not go down in new functions)
50 plt.matshow(noisy_face[cut], cmap=plt.cm.gray) s(tep) Execute the next statement (goes down in new functions)
---> 52 denoised_face = iterated_wiener(noisy_face) bt Print the call stack
53 plt.matshow(denoised_face[cut], cmap=plt.cm.gray) a Print the local variables
55 plt.show() !command Execute the given Python command (by opposition to pdb commands

9.3. Using the Python debugger 356 9.3. Using the Python debugger 357
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Warning: Debugger commands are not Python code
at numpy/core/src/multiarray/ctors.c:365
You cannot name the variables the way you want. For instance, if in you cannot override the variables 365 _FAST_MOVE(Int32);
in the current frame with the same name: use different names than your local variable when (gdb)
typing code in the debugger.
We get a segfault, and gdb captures it for post-mortem debugging in the C level stack (not the Python
call stack). We can debug the C call stack using gdb’s commands:
Getting help when in the debugger
(gdb) up
#1 0x004af4f5 in _copy_from_same_shape (dest=<value optimized out>,
Type h or help to access the interactive help: src=<value optimized out>, myfunc=0x496780 <_strided_byte_copy>,
ipdb> help swap=0)
at numpy/core/src/multiarray/ctors.c:748
Documented commands (type help <topic>): 748 myfunc(dit->dataptr, dest->strides[maxaxis],
========================================
EOF commands enable ll pp s until As you can see, right now, we are in the C code of numpy. We would like to know what is the Python
a condition exceptions longlist psource skip_hidden up code that triggers this segfault, so we go up the stack until we hit the Python execution loop:
alias cont exit n q skip_predicates w
(gdb) up
args context h next quit source whatis
#8 0x080ddd23 in call_function (f=
b continue help p r step where
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/
break d ignore pdef restart tbreak
˓→core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote␣
bt debug j pdoc return u
˓→0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0)
c disable jump pfile retval unalias
at ../Python/ceval.c:3750
cl display l pinfo run undisplay
3750 ../Python/ceval.c: No such file or directory.
clear down list pinfo2 rv unt
in ../Python/ceval.c
Miscellaneous help topics:
(gdb) up
==========================
#9 PyEval_EvalFrameEx (f=
exec pdb
Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/
˓→core/arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote␣
Undocumented commands:
˓→0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0)
======================
at ../Python/ceval.c:2412
interact
2412 in ../Python/ceval.c
(gdb)

9.4 Debugging segmentation faults using gdb Once we are in the Python execution loop, we can use our special Python helper function. For instance
we can find the corresponding Python code:

If you have a segmentation fault, you cannot debug it with pdb, as it crashes the Python interpreter (gdb) pyframe
before it can drop in the debugger. Similarly, if you have a bug in C code embedded in Python, pdb is /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/arrayprint.py (158): _
useless. For this we turn to the gnu debugger, gdb, available on Linux. ˓→leading_trailing

(gdb)
Before we start with gdb, let us add a few Python-specific tools to it. For this we add a few macros to
our ~/.gdbinit. The optimal choice of macro depends on your Python version and your gdb version. I
have added a simplified version in gdbinit, but feel free to read DebuggingWithGdb. This is numpy code, we need to go up until we find code that we have written:

To debug with gdb the Python script segfault.py, we can run the script in gdb as follows (gdb) up
...
$ gdb python (gdb) up
... #34 0x080dc97a in PyEval_EvalFrameEx (f=
(gdb) run segfault.py Frame 0x82f064c, for file segfault.py, line 11, in print_big_array (small_array=
Starting program: /usr/bin/python segfault.py ˓→<numpy.ndarray at remote 0x853ecf0>, big_array=<numpy.ndarray at remote 0x853ed20>),

[Thread debugging using libthread_db enabled] ˓→ throwflag=0) at ../Python/ceval.c:1630

1630 ../Python/ceval.c: No such file or directory.


Program received signal SIGSEGV, Segmentation fault. in ../Python/ceval.c
_strided_byte_copy (dst=0x8537478 "\360\343G", outstrides=4, src= (gdb) pyframe
0x86c0690 <Address 0x86c0690 out of bounds>, instrides=32, N=3, segfault.py (12): print_big_array
elsize=4)
(continues on next page) The corresponding code is:

9.4. Debugging segmentation faults using gdb 358 9.4. Debugging segmentation faults using gdb 359
Scientific Python Lectures, Edition 2024.2rc0.dev0

def make_big_array(small_array):
big_array = stride_tricks.as_strided(
small_array, shape=(int(2e6), int(2e6)), strides=(32, 32)
)
return big_array

Thus the segfault happens when printing big_array[-10:]. The reason is simply that big_array has
been allocated with its end outside the program memory.

Note: For a list of Python-specific commands defined in the gdbinit, read the source of this file.
CHAPTER 10
Wrap up exercise

The following script is well documented and hopefully legible. It seeks to answer a problem of actual
interest for numerical computing, but it does not work. . . Can you debug it?
Python source code: to_debug.py Optimizing code

Donald Knuth

“Premature optimization is the root of all evil”

Author: Gaël Varoquaux


This chapter deals with strategies to make Python code go faster.

Prerequisites

• line_profiler

Chapters contents

• Optimization workflow
• Profiling Python code
– Timeit
– Profiler
– Line-profiler
• Making code go faster
– Algorithmic optimization
∗ Example of the SVD

9.4. Debugging segmentation faults using gdb 360 361


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Writing faster numerical code 10.2.2 Profiler


– Additional Links Useful when you have a large program to profile, for example the following file:

# For this example to run, you also need the 'ica.py' file

10.1 Optimization workflow import numpy as np


import scipy as sp
1. Make it work: write the code in a simple legible ways.
from ica import fastica
2. Make it work reliably: write automated test cases, make really sure that your algorithm is right
and that if you break it, the tests will capture the breakage.
3. Optimize the code by profiling simple use-cases to find the bottlenecks and speeding up these # @profile # uncomment this line to run with line_profiler
bottleneck, finding a better algorithm or implementation. Keep in mind that a trade off should def test():
be found between profiling on a realistic example and the simplicity and speed of execution of the rng = np.random.default_rng()
code. For efficient work, it is best to work with profiling runs lasting around 10s. data = rng.random((5000, 100))
u, s, v = sp.linalg.svd(data)
pca = u[:, :10].T @ data
results = fastica(pca.T, whiten=False)
10.2 Profiling Python code
if __name__ == "__main__":
No optimization without measuring! test()

• Measure: profiling, timing


Note: This is a combination of two unsupervised learning techniques, principal component analysis
• You’ll have surprises: the fastest code is not always what you think
(PCA) and independent component analysis (ICA). PCA is a technique for dimensionality reduction,
i.e. an algorithm to explain the observed variance in your data using less dimensions. ICA is a source
separation technique, for example to unmix multiple signals that have been recorded through multiple
10.2.1 Timeit sensors. Doing a PCA first and then an ICA can be useful if you have more sensors than signals. For
more information see: the FastICA example from scikits-learn.
In IPython, use timeit (https://docs.python.org/3/library/timeit.html) to time elementary operations:
To run it, you also need to download the ica module. In IPython we can time the script:
In [1]: import numpy as np
In [6]: %run -t demo.py
In [2]: a = np.arange(1000) IPython CPU timings (estimated):
User : 14.3929 s.
In [3]: %timeit a ** 2 System: 0.256016 s.
867 ns +- 2.86 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)
and profile it:
In [4]: %timeit a ** 2.1
15.3 us +- 24.9 ns per loop (mean +- std. dev. of 7 runs, 100,000 loops each) In [7]: %run -p demo.py
916 function calls in 14.551 CPU seconds
In [5]: %timeit a * a Ordered by: internal time
978 ns +- 13.9 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each) ncalls tottime percall cumtime percall filename:lineno (function)
1 14.457 14.457 14.479 14.479 decomp.py:849 (svd)
Use this to guide your choice between strategies. 1 0.054 0.054 0.054 0.054 {method 'random_sample' of 'mtrand.
˓→RandomState' objects}

1 0.017 0.017 0.021 0.021 function_base.py:645 (asarray_chkfinite)


Note: For long running calls, using %time instead of %timeit; it is less precise but faster
54 0.011 0.000 0.011 0.000 {numpy.core._dotblas.dot}
2 0.005 0.002 0.005 0.002 {method 'any' of 'numpy.ndarray' objects}
6 0.001 0.000 0.001 0.000 ica.py:195 (gprime)
6 0.001 0.000 0.001 0.000 ica.py:192 (g)
14 0.001 0.000 0.001 0.000 {numpy.linalg.lapack_lite.dsyevd}
19 0.001 0.000 0.001 0.000 twodim_base.py:204 (diag)
1 0.001 0.001 0.008 0.008 ica.py:69 (_ica_par)
1 0.001 0.001 14.551 14.551 {execfile}
(continues on next page)

10.1. Optimization workflow 362 10.2. Profiling Python code 363


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


107 0.000 0.000 0.001 0.000 defmatrix.py:239 (__array_finalize__)
7 0.000 0.000 0.004 0.001 ica.py:58 (_sym_decorrelation) Line # Hits Time Per Hit % Time Line Contents
7 0.000 0.000 0.002 0.000 linalg.py:841 (eigh) ==============================================================
172 0.000 0.000 0.000 0.000 {isinstance} 9 @profile
1 0.000 0.000 14.551 14.551 demo.py:1 (<module>) 10 def test():
29 0.000 0.000 0.000 0.000 numeric.py:180 (asarray) 11 1 69.0 69.0 0.0 rng = np.random.default_rng()
35 0.000 0.000 0.000 0.000 defmatrix.py:193 (__new__) 12 1 2453.0 2453.0 0.2 data = rng.random((5000, 100))
35 0.000 0.000 0.001 0.000 defmatrix.py:43 (asmatrix) 13 1 1274715.0 1274715.0 99.7 u, s, v = sp.linalg.svd(data)
21 0.000 0.000 0.001 0.000 defmatrix.py:287 (__mul__) 14 1 413.0 413.0 0.0 pca = u[:, :10].T @ data
41 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros} 15 1 1094.0 1094.0 0.1 results = fastica(pca.T,␣
28 0.000 0.000 0.000 0.000 {method 'transpose' of 'numpy.ndarray'␣ ˓→whiten=False)

˓→objects}

1 0.000 0.000 0.008 0.008 ica.py:97 (fastica) The SVD is taking all the time. We need to optimise this line.
...

Clearly the svd (in decomp.py) is what takes most of our time, a.k.a. the bottleneck. We have to find a 10.3 Making code go faster
way to make this step go faster, or to avoid this step (algorithmic optimization). Spending time on the
rest of the code is useless.
Once we have identified the bottlenecks, we need to make the corresponding code go faster.

Profiling outside of IPython, running ``cProfile``


10.3.1 Algorithmic optimization
Similar profiling can be done outside of IPython, simply calling the built-in Python profilers cProfile
and profile. The first thing to look for is algorithmic optimization: are there ways to compute less, or better?
$ python -m cProfile -o demo.prof demo.py For a high-level view of the problem, a good understanding of the maths behind the algorithm helps.
However, it is not uncommon to find simple changes, like moving computation or memory allocation
Using the -o switch will output the profiler results to the file demo.prof to view with an external tool. outside a for loop, that bring in big gains.
This can be useful if you wish to process the profiler output with a visualization tool.

Example of the SVD

10.2.3 Line-profiler In both examples above, the SVD - Singular Value Decomposition - is what takes most of the time.
Indeed, the computational cost of this algorithm is roughly 𝑛3 in the size of the input matrix.
The profiler tells us which function takes most of the time, but not where it is called.
However, in both of these example, we are not using all the output of the SVD, but only the first few rows
For this, we use the line_profiler: in the source file, we decorate a few functions that we want to inspect of its first return argument. If we use the svd implementation of SciPy, we can ask for an incomplete
with @profile (no need to import it) version of the SVD. Note that implementations of linear algebra in SciPy are richer then those in NumPy
and should be preferred.
@profile
def test(): In [8]: %timeit np.linalg.svd(data)
rng = np.random.default_rng() 1 loops, best of 3: 14.5 s per loop
data = rng.random((5000, 100))
u, s, v = linalg.svd(data) In [9]: import scipy as sp
pca = u[:, :10] @ data
results = fastica(pca.T, whiten=False) In [10]: %timeit sp.linalg.svd(data)
1 loops, best of 3: 14.2 s per loop
Then we run the script using the kernprof command, with switches -l, --line-by-line and -v,
--view to use the line-by-line profiler and view the results in addition to saving them: In [11]: %timeit sp.linalg.svd(data, full_matrices=False)
1 loops, best of 3: 295 ms per loop
$ kernprof -l -v demo.py
In [12]: %timeit np.linalg.svd(data, full_matrices=False)
Wrote profile results to demo.py.lprof 1 loops, best of 3: 293 ms per loop
Timer unit: 1e-06 s
We can then use this insight to optimize the previous code:
Total time: 1.27874 s
File: demo.py def test():
Function: test at line 9 rng = np.random.default_rng()
(continues on next page) (continues on next page)

10.2. Profiling Python code 364 10.3. Making code go faster 365
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


data = rng.random((5000, 100)) In [20]: %timeit global a ; a *= 0
u, s, v = sp.linalg.svd(data, full_matrices=False) 10 loops, best of 3: 48.4 ms per loop
pca = u[:, :10].T @ data
results = fastica(pca.T, whiten=False) note: we need global a in the timeit so that it work, as it is assigning to a, and thus considers it
as a local variable.
In [13]: import demo • Be easy on the memory: use views, and not copies

In [14]: %timeit demo. Copying big arrays is as costly as making simple numerical operations on them:
demo.fastica demo.np demo.prof.pdf demo.py demo.pyc
In [21]: a = np.zeros(1e7)
demo.linalg demo.prof demo.prof.png demo.py.lprof demo.test
In [22]: %timeit a.copy()
In [15]: %timeit demo.test()
10 loops, best of 3: 124 ms per loop
ica.py:65: RuntimeWarning: invalid value encountered in sqrt
W = (u * np.diag(1.0/np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W
In [23]: %timeit a + 1
1 loops, best of 3: 17.5 s per loop
10 loops, best of 3: 112 ms per loop
In [16]: import demo_opt
• Beware of cache effects
In [17]: %timeit demo_opt.test() Memory access is cheaper when it is grouped: accessing a big array in a continuous way is much
1 loops, best of 3: 208 ms per loop faster than random access. This implies amongst other things that smaller strides are faster
(see CPU cache effects):
Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can be computed with arpack,
available in scipy.sparse.linalg.eigsh. In [24]: c = np.zeros((1e4, 1e4), order='C')

In [25]: %timeit c.sum(axis=0)


Computational linear algebra 1 loops, best of 3: 3.89 s per loop

For certain algorithms, many of the bottlenecks will be linear algebra computations. In this case, In [26]: %timeit c.sum(axis=1)
using the right function to solve the right problem is key. For instance, an eigenvalue problem with 1 loops, best of 3: 188 ms per loop
a symmetric matrix is easier to solve than with a general matrix. Also, most often, you can avoid
inverting a matrix and use a less costly (and more numerically stable) operation. In [27]: c.strides
Know your computational linear algebra. When in doubt, explore scipy.linalg, and use %timeit to Out[27]: (80000, 8)
try out different alternatives on your data.
This is the reason why Fortran ordering or C ordering may make a big difference on operations:

In [28]: rng = np.random.default_rng()


10.4 Writing faster numerical code In [29]: a = rng.random((20, 2**18))

A complete discussion on advanced use of NumPy is found in chapter Advanced NumPy, or in the article In [30]: b = rng.random((20, 2**18))
The NumPy array: a structure for efficient numerical computation by van der Walt et al. Here we discuss
only some commonly encountered tricks to make code faster. In [31]: %timeit b @ a.T
8.1 ms +- 14.6 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
• Vectorizing for loops
Find tricks to avoid for loops using NumPy arrays. For this, masks and indices arrays can be In [32]: c = np.ascontiguousarray(a.T)
useful.
In [33]: %timeit b @ c
• Broadcasting
8.04 ms +- 23.8 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
Use broadcasting to do operations on arrays as small as possible before combining them.
Note that copying the data to work around this effect may not be worth it:
• In place operations

In [18]: a = np.zeros(1e7) In [34]: %timeit c = np.ascontiguousarray(a.T)


16.5 ms +- 192 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
In [19]: %timeit global a ; a = 0*a
10 loops, best of 3: 111 ms per loop Using numexpr can be useful to automatically optimize code for such effects.
• Use compiled code
(continues on next page)

10.4. Writing faster numerical code 366 10.4. Writing faster numerical code 367
Scientific Python Lectures, Edition 2024.2rc0.dev0

The last resort, once you are sure that all the high-level optimizations have been explored, is to
transfer the hot spots, i.e. the few lines or functions in which most of the time is spent, to compiled
code. For compiled code, the preferred option is to use Cython: it is easy to transform exiting
Python code in compiled code, and with a good use of the NumPy support yields efficient code on
NumPy arrays, for instance by unrolling loops.

Warning: For all the above: profile and time your choices. Don’t base your optimization on

11
theoretical considerations.

10.4.1 Additional Links CHAPTER


• If you need to profile memory usage, you could try the memory_profiler
• If you need to profile down into C extensions, you could try using gperftools from Python with
yep.
• If you would like to track performance of your code across time, i.e. as you make new commits to
your repository, you could try: asv
• If you need some interactive visualization why not try RunSnakeRun
Sparse Arrays in SciPy

Author: Robert Cimrman

11.1 Introduction

(dense) matrix is:


• mathematical object
• data structure for storing a 2D array of values
important features:
• memory allocated once for all items
– usually a contiguous chunk, think NumPy ndarray
• fast access to individual items (*)

10.4. Writing faster numerical code 368 369


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

11.1.1 Why Sparse Matrices? 11.1.5 Sparsity Structure Visualization

• the memory grows like n**2 for dense matrix • spy() from matplotlib
• small example (double precision matrix): • example plots:

>>> import numpy as np


>>> import matplotlib.pyplot as plt
>>> x = np.linspace(0, 1e6, 10)
>>> plt.plot(x, 8.0 * (x**2) / 1e6, lw=5)
[<matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel('size n')
Text(...'size n')
>>> plt.ylabel('memory [MB]')
Text(...'memory [MB]')

11.1.2 Sparse Matrices vs. Sparse Matrix Storage Schemes

• sparse matrix is a matrix, which is almost empty


• storing all the zeros is wasteful -> store only nonzero items
• think compression
• pros: huge memory savings
• cons: slow access to individual items, but it depends on actual storage scheme.

11.1.3 Typical Applications

• solution of partial differential equations (PDEs)


– the finite element method
– mechanical engineering, electrotechnics, physics, . . .
• graph theory
– nonzero at (i, j) means that node i is connected to node j
• natural language processing
– nonzero at (i, j) means that the document i contains the word j
• ...

11.1.4 Prerequisites

• numpy
• scipy
• matplotlib (optional)
• ipython (the enhancements come handy)

11.1. Introduction 370 11.1. Introduction 371


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

11.2 Storage Schemes • data and indices usually stored in 1D NumPy arrays

• seven sparse array types in scipy.sparse: 11.2.2 Sparse Array Classes


1. csr_array: Compressed Sparse Row format
Diagonal Format (DIA)
2. csc_array: Compressed Sparse Column format
3. bsr_array: Block Sparse Row format • very simple scheme

4. lil_array: List of Lists format • diagonals in dense NumPy array of shape (n_diag, length)

5. dok_array: Dictionary of Keys format – fixed length -> waste space a bit when far from main diagonal

6. coo_array: COOrdinate format (aka IJV, triplet format) – subclass of _data_matrix (sparse array classes with .data attribute)

7. dia_array: DIAgonal format • offset for each diagonal

• each suitable for some tasks – 0 is the main diagonal

• many employ sparsetools C++ module by Nathan Bell – negative offset = below

• assume the following is imported: – positive offset = above


• fast matrix * vector (sparsetools)
>>> import numpy as np
>>> import scipy as sp • fast and easy item-wise operations
>>> import matplotlib.pyplot as plt
– manipulate data array directly (fast NumPy machinery)
• warning for Numpy users: • constructor accepts:
– passing a sparse array object to NumPy functions that expect ndarray/matrix does not – dense array/matrix
work. Use sparse functions.
– sparse array/matrix
– the older csr_matrix classes use ‘*’ for matrix multiplication (dot product) and
– shape tuple (create empty array)
‘A.multiply(B)’ for elementwise multiplication.
– (data, offsets) tuple
– the newer csr_array uses ‘@’ for dot product and ‘*’ for elementwise multiplication
• no slicing, no individual item access
– sparse arrays can be 1D or 2D, but not nD for n > 2 (unlike Numpy arrays).
• use:

11.2.1 Common Methods – rather specialized


– solving PDEs by finite differences
• all scipy.sparse array classes are subclasses of sparray
– with an iterative solver
– default implementation of arithmetic operations
∗ always converts to CSR Examples
∗ subclasses override for efficiency
• create some DIA arrays:
– shape, data type, set/get
– indices of nonzero values in the array >>> data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
>>> data
– format conversion, interaction with NumPy (toarray()) array([[1, 2, 3, 4],
– ... [1, 2, 3, 4],
[1, 2, 3, 4]])
• attributes: >>> offsets = np.array([0, -1, 2])
– mtx.T - transpose (same as mtx.transpose()) >>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4))
>>> mtx
– mtx.real - real part of complex matrix <4x4 sparse array of type '<... 'numpy.int64'>'
– mtx.imag - imaginary part of complex matrix with 9 stored elements (3 diagonals) in DIAgonal format>
>>> mtx.toarray()
– mtx.size - the number of nonzeros (same as self.getnnz()) array([[1, 0, 3, 0],
– mtx.shape - the number of rows and columns (tuple) [1, 2, 0, 4],
(continues on next page)

11.2. Storage Schemes 372 11.2. Storage Schemes 373


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) List of Lists Format (LIL)


[0, 2, 3, 0],
[0, 0, 3, 4]]) • row-based linked list
– each row is a Python list (sorted) of column indices of non-zero elements
>>> data = np.arange(12).reshape((3, 4)) + 1
>>> data – rows stored in a NumPy array (dtype=np.object)
array([[ 1, 2, 3, 4], – non-zero values data stored analogously
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]]) • efficient for constructing sparse arrays incrementally
>>> mtx = sp.sparse.dia_array((data, offsets), shape=(4, 4)) • constructor accepts:
>>> mtx.data
array([[ 1, 2, 3, 4], – dense array/matrix
[ 5, 6, 7, 8], – sparse array/matrix
[ 9, 10, 11, 12]])
>>> mtx.offsets – shape tuple (create empty array)
array([ 0, -1, 2], dtype=int32) • flexible slicing, changing sparsity structure is efficient
>>> print(mtx)
(0, 0) 1 • slow arithmetic, slow column slicing due to being row-based
(1, 1) 2 • use:
(2, 2) 3
(3, 3) 4 – when sparsity pattern is not known apriori or changes
(1, 0) 5 – example: reading a sparse array from a text file
(2, 1) 6
(3, 2) 7
(0, 2) 11 Examples
(1, 3) 12
>>> mtx.toarray() • create an empty LIL array:
array([[ 1, 0, 11, 0],
[ 5, 2, 0, 12], >>> mtx = sp.sparse.lil_array((4, 5))
[ 0, 6, 3, 0],
[ 0, 0, 7, 4]]) • prepare random data:

• explanation with a scheme: >>> rng = np.random.default_rng(27446968)


>>> data = np.round(rng.random((2, 3)))
offset: row >>> data
array([[1., 0., 1.],
2: 9 [0., 0., 1.]])
1: --10------
0: 1 . 11 . • assign the data using fancy indexing:
-1: 5 2 . 12
-2: . 6 3 . >>> mtx[:2, [1, 2, 3]] = data
-3: . . 7 4 >>> mtx
---------8 <4x5 sparse array of type '<... 'numpy.float64'>'
with 3 stored elements in List of Lists format>
• matrix-vector multiplication >>> print(mtx)
(0, 1) 1.0
>>> vec = np.ones((4, )) (0, 3) 1.0
>>> vec (1, 3) 1.0
array([1., 1., 1., 1.]) >>> mtx.toarray()
>>> mtx @ vec array([[0., 1., 0., 1., 0.],
array([12., 19., 9., 11.]) [0., 0., 0., 1., 0.],
>>> (mtx * vec).toarray() [0., 0., 0., 0., 0.],
array([[ 1., 0., 11., 0.], [0., 0., 0., 0., 0.]])
[ 5., 2., 0., 12.], >>> mtx.toarray()
[ 0., 6., 3., 0.], array([[0., 1., 0., 1., 0.],
[ 0., 0., 7., 4.]]) [0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])

11.2. Storage Schemes 374 11.2. Storage Schemes 375


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• more slicing and indexing: Examples

>>> mtx = sp.sparse.lil_array([[0, 1, 2, 0], [3, 0, 1, 0], [1, 0, 0, 1]])


>>> mtx.toarray() • create a DOK array element by element:
array([[0, 1, 2, 0], >>> mtx = sp.sparse.dok_array((5, 5), dtype=np.float64)
[3, 0, 1, 0], >>> mtx
[1, 0, 0, 1]]...) <5x5 sparse array of type '<... 'numpy.float64'>'
>>> print(mtx) with 0 stored elements in Dictionary Of Keys format>
(0, 1) 1 >>> for ir in range(5):
(0, 2) 2 ... for ic in range(5):
(1, 0) 3 ... mtx[ir, ic] = 1.0 * (ir != ic)
(1, 2) 1 >>> mtx
(2, 0) 1 <5x5 sparse array of type '<... 'numpy.float64'>'
(2, 3) 1 with 20 stored elements in Dictionary Of Keys format>
>>> mtx[:2, :] >>> mtx.toarray()
<2x4 sparse array of type '<... 'numpy.int64'>' array([[0., 1., 1., 1., 1.],
with 4 stored elements in List of Lists format> [1., 0., 1., 1., 1.],
>>> mtx[:2, :].toarray() [1., 1., 0., 1., 1.],
array([[0, 1, 2, 0], [1., 1., 1., 0., 1.],
[3, 0, 1, 0]]...) [1., 1., 1., 1., 0.]])
>>> mtx[1:2, [0,2]].toarray()
array([[3, 1]]...) • slicing and indexing:
>>> mtx.toarray()
array([[0, 1, 2, 0], >>> mtx[1, 1]
[3, 0, 1, 0], 0.0
[1, 0, 0, 1]]...) >>> mtx[[1], 1:3]
<1x2 sparse array of type '<... 'numpy.float64'>'
with 1 stored elements in Dictionary Of Keys format>
>>> mtx[[1], 1:3].toarray()
array([[0., 1.]])
Dictionary of Keys Format (DOK) >>> mtx[[2, 1], 1:3].toarray()
array([[1., 0.],
• subclass of Python dict [0., 1.]])
– keys are (row, column) index tuples (no duplicate entries allowed)
– values are corresponding non-zero values
• efficient for constructing sparse arrays incrementally
Coordinate Format (COO)
• constructor accepts:
– dense array/matrix • also known as the ‘ijv’ or ‘triplet’ format

– sparse array/matrix – three NumPy arrays: row, col, data.

– shape tuple (create empty array) – attribute coords is the tuple (row, col)

• efficient O(1) access to individual elements – data[i] is value at (row[i], col[i]) position

• flexible slicing, changing sparsity structure is efficient – permits duplicate entries

• can be efficiently converted to a coo_array once constructed – subclass of _data_matrix (sparse matrix classes with .data attribute)

• slow arithmetic (for loops with dict.items()) • fast format for constructing sparse arrays

• use: • constructor accepts:

– when sparsity pattern is not known apriori or changes – dense array/matrix


– sparse array/matrix
– shape tuple (create empty matrix)
– (data, coords) tuple
• very fast conversion to and from CSR/CSC formats

11.2. Storage Schemes 376 11.2. Storage Schemes 377


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• fast matrix * vector (sparsetools) Compressed Sparse Row Format (CSR)


• fast and easy item-wise operations
• row oriented
– manipulate data array directly (fast NumPy machinery)
– three NumPy arrays: indices, indptr, data
• no slicing, no arithmetic (directly, converts to CSR)
∗ indices is array of column indices
• use:
∗ data is array of corresponding nonzero values
– facilitates fast conversion among sparse formats
∗ indptr points to row starts in indices and data
– when converting to other format (usually CSR or CSC), duplicate entries are summed
∗ length of indptr is n_row + 1, last item = number of values = length of both
together
indices and data
∗ facilitates efficient construction of finite element matrices
∗ nonzero values of the i-th row are data[indptr[i]:indptr[i + 1]] with column indices
indices[indptr[i]:indptr[i + 1]]
Examples ∗ item (i, j) can be accessed as data[indptr[i] + k], where k is position of j in in-
dices[indptr[i]:indptr[i + 1]]
• create empty COO array:
– subclass of _cs_matrix (common CSR/CSC functionality)
>>> mtx = sp.sparse.coo_array((3, 4), dtype=np.int8) ∗ subclass of _data_matrix (sparse array classes with .data attribute)
>>> mtx.toarray()
array([[0, 0, 0, 0], • fast matrix vector products and other arithmetic (sparsetools)
[0, 0, 0, 0], • constructor accepts:
[0, 0, 0, 0]], dtype=int8)
– dense array/matrix
• create using (data, ij) tuple: – sparse array/matrix
>>> row = np.array([0, 3, 1, 0]) – shape tuple (create empty array)
>>> col = np.array([0, 3, 1, 2])
>>> data = np.array([4, 5, 7, 9]) – (data, coords) tuple
>>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4)) – (data, indices, indptr) tuple
>>> mtx
<4x4 sparse array of type '<... 'numpy.int64'>' • efficient row slicing, row-oriented operations
with 4 stored elements in COOrdinate format> • slow column slicing, expensive changes to the sparsity structure
>>> mtx.toarray()
array([[4, 0, 9, 0], • use:
[0, 7, 0, 0], – actual computations (most linear solvers support this format)
[0, 0, 0, 0],
[0, 0, 0, 5]])
Examples
• duplicates entries are summed together:
• create empty CSR array:
>>> row = np.array([0, 0, 1, 3, 1, 0, 0])
>>> col = np.array([0, 2, 1, 3, 1, 0, 0]) >>> mtx = sp.sparse.csr_array((3, 4), dtype=np.int8)
>>> data = np.array([1, 1, 1, 1, 1, 1, 1]) >>> mtx.toarray()
>>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4)) array([[0, 0, 0, 0],
>>> mtx.toarray() [0, 0, 0, 0],
array([[3, 0, 1, 0], [0, 0, 0, 0]], dtype=int8)
[0, 2, 0, 0],
[0, 0, 0, 0], • create using (data, coords) tuple:
[0, 0, 0, 1]])
>>> row = np.array([0, 0, 1, 2, 2, 2])
• no slicing. . . : >>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> mtx[2, 3] >>> mtx = sp.sparse.csr_array((data, (row, col)), shape=(3, 3))
Traceback (most recent call last): >>> mtx
... <3x3 sparse array of type '<... 'numpy.int64'>'
TypeError: 'coo_array' object ... with 6 stored elements in Compressed Sparse Row format>
>>> mtx.toarray()
(continues on next page)

11.2. Storage Schemes 378 11.2. Storage Schemes 379


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) • use:


array([[1, 0, 2], – actual computations (most linear solvers support this format)
[0, 0, 3],
[4, 5, 6]]...)
>>> mtx.data Examples
array([1, 2, 3, 4, 5, 6]...)
>>> mtx.indices • create empty CSC array:
array([0, 2, 2, 0, 1, 2])
>>> mtx.indptr >>> mtx = sp.sparse.csc_array((3, 4), dtype=np.int8)
array([0, 2, 3, 6]) >>> mtx.toarray()
array([[0, 0, 0, 0],
• create using (data, indices, indptr) tuple: [0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2]) • create using (data, coords) tuple:
>>> indptr = np.array([0, 2, 3, 6])
>>> mtx = sp.sparse.csr_array((data, indices, indptr), shape=(3, 3)) >>> row = np.array([0, 0, 1, 2, 2, 2])
>>> mtx.toarray() >>> col = np.array([0, 2, 2, 0, 1, 2])
array([[1, 0, 2], >>> data = np.array([1, 2, 3, 4, 5, 6])
[0, 0, 3], >>> mtx = sp.sparse.csc_array((data, (row, col)), shape=(3, 3))
[4, 5, 6]]) >>> mtx
<3x3 sparse array of type '<... 'numpy.int64'>'
with 6 stored elements in Compressed Sparse Column format>
>>> mtx.toarray()
array([[1, 0, 2],
Compressed Sparse Column Format (CSC) [0, 0, 3],
[4, 5, 6]]...)
• column oriented >>> mtx.data
– three NumPy arrays: indices, indptr, data array([1, 4, 5, 2, 3, 6]...)
>>> mtx.indices
∗ indices is array of row indices array([0, 2, 2, 0, 1, 2])
∗ data is array of corresponding nonzero values >>> mtx.indptr
array([0, 2, 3, 6])
∗ indptr points to column starts in indices and data
∗ length is n_col + 1, last item = number of values = length of both indices and • create using (data, indices, indptr) tuple:
data
>>> data = np.array([1, 4, 5, 2, 3, 6])
∗ nonzero values of the i-th column are data[indptr[i]:indptr[i+1]] with row indices >>> indices = np.array([0, 2, 2, 0, 1, 2])
indices[indptr[i]:indptr[i+1]] >>> indptr = np.array([0, 2, 3, 6])
>>> mtx = sp.sparse.csc_array((data, indices, indptr), shape=(3, 3))
∗ item (i, j) can be accessed as data[indptr[j]+k], where k is position of i in in-
>>> mtx.toarray()
dices[indptr[j]:indptr[j+1]]
array([[1, 0, 2],
– subclass of _cs_matrix (common CSR/CSC functionality) [0, 0, 3],
[4, 5, 6]])
∗ subclass of _data_matrix (sparse array classes with .data attribute)
• fast matrix vector products and other arithmetic (sparsetools)
• constructor accepts:
– dense array/matrix Block Compressed Row Format (BSR)

– sparse array/matrix • basically a CSR with dense sub-matrices of fixed shape instead of scalar items
– shape tuple (create empty array) – block size (R, C) must evenly divide the shape of the matrix (M, N)
– (data, coords) tuple – three NumPy arrays: indices, indptr, data
– (data, indices, indptr) tuple ∗ indices is array of column indices for each block
• efficient column slicing, column-oriented operations ∗ data is array of corresponding nonzero values of shape (nnz, R, C)
• slow row slicing, expensive changes to the sparsity structure ∗ ...

11.2. Storage Schemes 380 11.2. Storage Schemes 381


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

– subclass of _cs_matrix (common CSR/CSC functionality) (continued from previous page)

∗ subclass of _data_matrix (sparse matrix classes with .data attribute) array([[1, 0, 2],
[0, 0, 3],
• fast matrix vector products and other arithmetic (sparsetools) [4, 5, 6]]...)
• constructor accepts: >>> mtx.data
array([[[1]],
– dense array/matrix
– sparse array/matrix [[2]],

– shape tuple (create empty array) [[3]],


– (data, coords) tuple
[[4]],
– (data, indices, indptr) tuple
• many arithmetic operations considerably more efficient than CSR for sparse matrices with dense [[5]],
sub-matrices
[[6]]]...)
• use: >>> mtx.indices
– like CSR array([0, 2, 2, 0, 1, 2])
>>> mtx.indptr
– vector-valued finite element discretizations array([0, 2, 3, 6])

Examples • create using (data, indices, indptr) tuple with (2, 2) block size:

>>> indptr = np.array([0, 2, 3, 6])


• create empty BSR array with (1, 1) block size (like CSR. . . ): >>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
>>> mtx = sp.sparse.bsr_array((3, 4), dtype=np.int8) >>> mtx = sp.sparse.bsr_array((data, indices, indptr), shape=(6, 6))
>>> mtx >>> mtx.toarray()
<3x4 sparse array of type '<... 'numpy.int8'>' array([[1, 1, 0, 0, 2, 2],
with 0 stored elements (blocksize = 1x1) in Block Sparse Row format> [1, 1, 0, 0, 2, 2],
>>> mtx.toarray() [0, 0, 0, 0, 3, 3],
array([[0, 0, 0, 0], [0, 0, 0, 0, 3, 3],
[0, 0, 0, 0], [4, 4, 5, 5, 6, 6],
[0, 0, 0, 0]], dtype=int8) [4, 4, 5, 5, 6, 6]])
>>> data
• create empty BSR array with (3, 2) block size: array([[[1, 1],
[1, 1]],
>>> mtx = sp.sparse.bsr_array((3, 4), blocksize=(3, 2), dtype=np.int8)
>>> mtx
[[2, 2],
<3x4 sparse array of type '<... 'numpy.int8'>'
[2, 2]],
with 0 stored elements (blocksize = 3x2) in Block Sparse Row format>
>>> mtx.toarray()
[[3, 3],
array([[0, 0, 0, 0],
[3, 3]],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
[[4, 4],
[4, 4]],
– a bug?
• create using (data, coords) tuple with (1, 1) block size (like CSR. . . ): [[5, 5],
[5, 5]],
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2]) [[6, 6],
>>> data = np.array([1, 2, 3, 4, 5, 6]) [6, 6]]])
>>> mtx = sp.sparse.bsr_array((data, (row, col)), shape=(3, 3))
>>> mtx
<3x3 sparse array of type '<... 'numpy.int64'>'
with 6 stored elements (blocksize = 1x1) in Block Sparse Row format>
>>> mtx.toarray()
(continues on next page)

11.2. Storage Schemes 382 11.2. Storage Schemes 383


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

11.2.3 Summary – wrappers now live in scikits.umfpack


– check-out the new scikits.suitesparse by Nathaniel Smith
Table 1: Summary of storage schemes.
format matrix get fancy set item fancy solvers note Examples
* vector item get set
• import the whole module, and see its docstring:
CSR sparse- yes yes slow . any has data array, fast row-wise
tools ops >>> help(sp.sparse.linalg.spsolve)
CSC sparse- yes yes slow . any has data array, fast column- Help on function spsolve in module scipy.sparse.linalg._dsolve.linsolve:
tools wise ops ...
BSR sparse- . . . . special- has data array, specialized
tools ized • both superlu and umfpack can be used (if the latter is installed) as follows:
COO sparse- . . . . itera- has data array, facilitates
tools tive fast conversion – prepare a linear system:
DIA sparse- . . . . itera- has data array, specialized
>>> import numpy as np
tools tive
>>> mtx = sp.sparse.spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5,␣
LIL via yes yes yes yes itera- arithmetic via CSR, incre-
˓→5, "csc")
CSR tive mental construction
>>> mtx.toarray()
DOK python yes one yes yes itera- O(1) item access, incremen-
array([[ 1, 5, 0, 0, 0],
axis tive tal construction, slow arith-
[ 0, 2, 8, 0, 0],
only metic
[ 0, 0, 3, 9, 0],
[ 0, 0, 0, 4, 10],
[ 0, 0, 0, 0, 5]])
>>> rhs = np.array([1, 2, 3, 4, 5], dtype=np.float32)

11.3 Linear System Solvers – solve as single precision real:

>>> mtx1 = mtx.astype(np.float32)


• sparse matrix/eigenvalue problem solvers live in scipy.sparse.linalg >>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False)
>>> print(x)
• the submodules:
[106. -21. 5.5 -1.5 1. ]
– dsolve: direct factorization methods for solving linear systems >>> print("Error: %s " % (mtx1 * x - rhs))
Error: [0. 0. 0. 0. 0.]
– isolve: iterative methods for solving linear systems
– eigen: sparse eigenvalue problem solvers – solve as double precision real:
• all solvers are accessible from: >>> mtx2 = mtx.astype(np.float64)
>>> import scipy as sp >>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True)
>>> sp.sparse.linalg.__all__ >>> print(x)
['ArpackError', 'ArpackNoConvergence', ..., 'use_solver'] [106. -21. 5.5 -1.5 1. ]
>>> print("Error: %s " % (mtx2 * x - rhs))
Error: [0. 0. 0. 0. 0.]

11.3.1 Sparse Direct Solvers – solve as single precision complex:

• default solver: SuperLU >>> mtx1 = mtx.astype(np.complex64)


>>> x = sp.sparse.linalg.spsolve(mtx1, rhs, use_umfpack=False)
– included in SciPy >>> print(x)
– real and complex systems [106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j]
>>> print("Error: %s " % (mtx1 * x - rhs))
– both single and double precision Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]
• optional: umfpack
– solve as double precision complex:
– real and complex systems
– double precision only >>> mtx2 = mtx.astype(np.complex128)
>>> x = sp.sparse.linalg.spsolve(mtx2, rhs, use_umfpack=True)
– recommended for performance >>> print(x)
(continues on next page)

11.3. Linear System Solvers 384 11.3. Linear System Solvers 385
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Common Parameters


[106. +0.j -21. +0.j 5.5+0.j -1.5+0.j 1. +0.j]
>>> print("Error: %s " % (mtx2 * x - rhs)) • mandatory:
Error: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j] A
[{sparse array/matrix, dense array/matrix, LinearOperator}] The N-by-N matrix of the linear
""" system.
Solve a linear system
b
=======================
[{array, matrix}] Right hand side of the linear system. Has shape (N,) or (N,1).
Construct a 1000x1000 lil_array and add some values to it, convert it • optional:
to CSR format and solve A x = b for x:and solve a linear system with a
x0
direct solver.
[{array, matrix}] Starting guess for the solution.
"""
tol
import numpy as np [float] Relative tolerance to achieve before terminating.
import scipy as sp
maxiter
import matplotlib.pyplot as plt
[integer] Maximum number of iterations. Iteration will stop after maxiter steps even if the
specified tolerance has not been achieved.
rng = np.random.default_rng(27446968)
M
mtx = sp.sparse.lil_array((1000, 1000), dtype=np.float64) [{sparse array/matrix, dense array/matrix, LinearOperator}] Preconditioner for A. The pre-
mtx[0, :100] = rng.random(100) conditioner should approximate the inverse of A. Effective preconditioning dramatically im-
mtx[1, 100:200] = mtx[0, :100] proves the rate of convergence, which implies that fewer iterations are needed to reach a given
mtx.setdiag(rng.random(1000)) error tolerance.
callback
plt.clf()
[function] User-supplied function to call after each iteration. It is called as callback(xk), where
plt.spy(mtx, marker=".", markersize=2)
xk is the current solution vector.
plt.show()

mtx = mtx.tocsr() LinearOperator Class


rhs = rng.random(1000)
• common interface for performing matrix vector products
x = sp.sparse.linalg.spsolve(mtx, rhs)
• useful abstraction that enables using dense and sparse matrices within the solvers, as well as
print(f"residual: { np.linalg.norm(mtx * x - rhs)!r} ") matrix-free solutions
• has shape and matvec() (+ some optional parameters)
• examples/direct_solve.py
• example:

>>> import numpy as np


11.3.2 Iterative Solvers
>>> import scipy as sp
>>> def mv(v):
• the isolve module contains the following solvers: ... return np.array([2 * v[0], 3 * v[1]])
– bicg (BIConjugate Gradient) ...
>>> A = sp.sparse.linalg.LinearOperator((2, 2), matvec=mv)
– bicgstab (BIConjugate Gradient STABilized) >>> A
– cg (Conjugate Gradient) - symmetric positive definite matrices only <2x2 _CustomLinearOperator with dtype=float64>
>>> A.matvec(np.ones(2))
– cgs (Conjugate Gradient Squared) array([2., 3.])
– gmres (Generalized Minimal RESidual) >>> A * np.ones(2)
array([2., 3.])
– minres (MINimum RESidual)
– qmr (Quasi-Minimal Residual)

11.3. Linear System Solvers 386 11.3. Linear System Solvers 387
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

A Few Notes on Preconditioning (continued from previous page)


plt.axis("equal")
• problem specific plt.axis("off")
• often hard to develop plt.show()

• if not sure, try ILU – examples/pyamg_with_lobpcg.py


– available in scipy.sparse.linalg as spilu() • example by Nils Wagner:
– examples/lobpcg_sakurai.py
11.3.3 Eigenvalue Problem Solvers • output:

The eigen module $ python examples/lobpcg_sakurai.py


Results by LOBPCG for n=2500
• arpack * a collection of Fortran77 subroutines designed to solve large scale eigenvalue problems
[ 0.06250083 0.06250028 0.06250007]
• lobpcg (Locally Optimal Block Preconditioned Conjugate Gradient Method) * works very well in
combination with PyAMG * example by Nathan Bell:
Exact eigenvalues
"""
Compute eigenvectors and eigenvalues using a preconditioned eigensolver [ 0.06250005 0.0625002 0.06250044]
=======================================================================
Elapsed time 7.01
In this example Smoothed Aggregation (SA) is used to precondition
the LOBPCG eigensolver on a two-dimensional Poisson problem with
Dirichlet boundary conditions.
"""

import scipy as sp
import matplotlib.pyplot as plt

from pyamg import smoothed_aggregation_solver


from pyamg.gallery import poisson

N = 100
K = 9
A = poisson((N, N), format="csr")

# create the AMG hierarchy


ml = smoothed_aggregation_solver(A)

# initial approximation to the K eigenvectors


X = sp.rand(A.shape[0], K)

# preconditioner based on ml
M = ml.aspreconditioner()

# compute eigenvalues and eigenvectors with LOBPCG


W, V = sp.sparse.linalg.lobpcg(A, X, M=M, tol=1e-8, largest=False)

# plot the eigenvectors


plt.figure(figsize=(9, 9))

for i in range(K):
plt.subplot(3, 3, i + 1)
plt.title("Eigenvector %d " % i)
plt.pcolor(V[:, i].reshape(N, N))
(continues on next page)

11.3. Linear System Solvers 388 11.3. Linear System Solvers 389
Scientific Python Lectures, Edition 2024.2rc0.dev0

11.4 Other Interesting Packages

• PyAMG
– algebraic multigrid solvers
– https://github.com/pyamg/pyamg
• Pysparse
– own sparse matrix classes
– matrix and eigenvalue problem solvers
– https://pysparse.sourceforge.net/
CHAPTER 12
Image manipulation and processing
using NumPy and SciPy

Authors: Emmanuelle Gouillart, Gaël Varoquaux


This section addresses basic image manipulation and processing using the core scientific modules NumPy
and SciPy. Some of the operations covered by this tutorial may be useful for other kinds of multidimen-
sional array processing than image processing. In particular, the submodule scipy.ndimage provides
functions operating on n-dimensional NumPy arrays.
See also:
For more advanced image processing and image-specific routines, see the tutorial scikit-image: image
processing, dedicated to the skimage module.

Image = 2-D numerical array

(or 3-D: CT, MRI, 2D + time; 4-D, . . . )


Here, image == NumPy array np.array

Tools used in this tutorial:


• numpy: basic array manipulation
• scipy: scipy.ndimage submodule dedicated to image processing (n-dimensional images). See the
documentation:

>>> import scipy as sp

Common tasks in image processing:

11.4. Other Interesting Packages 390 391


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Input/Output, displaying images


• Basic manipulations: cropping, flipping, rotating, . . .
• Image filtering: denoising, sharpening
• Image segmentation: labeling pixels corresponding to different objects
• Classification
• Feature extraction
• Registration
• ...

Chapters contents

• Opening and writing to image files


• Displaying images
• Basic manipulations
– Statistical information
– Geometrical transformations
• Image filtering
– Blurring/smoothing
Creating a NumPy array from an image file:
– Sharpening
>>> import imageio.v3 as iio
– Denoising
>>> face = sp.datasets.face()
– Mathematical morphology >>> iio.imwrite('face.png', face) # First we need to create the PNG file
• Feature extraction
>>> face = iio.imread('face.png')
– Edge detection >>> type(face)
<class 'numpy.ndarray'>
– Segmentation
>>> face.shape, face.dtype
• Measuring objects properties: scipy.ndimage.measurements ((768, 1024, 3), dtype('uint8'))
• Full code examples
dtype is uint8 for 8-bit images (0-255)
• Examples for the image processing chapter
Opening raw files (camera, 3-D images)

>>> face.tofile('face.raw') # Create raw file


>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
12.1 Opening and writing to image files >>> face_from_raw.shape
(2359296,)
Writing an array to a file: >>> face_from_raw.shape = (768, 1024, 3)

import scipy as sp Need to know the shape and dtype of the image (how to separate data bytes).
import imageio.v3 as iio
For large data, use np.memmap for memory mapping:
f = sp.datasets.face() >>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
iio.imwrite("face.png", f) # uses the Image module (PIL)
(data are read from the file, and not loaded into memory)
import matplotlib.pyplot as plt
Working on a list of image files
plt.imshow(f)
>>> rng = np.random.default_rng(27446968)
plt.show()
>>> for i in range(10):
... im = rng.integers(0, 256, 10000, dtype=np.uint8).reshape((100, 100))
(continues on next page)

12.1. Opening and writing to image files 392 12.1. Opening and writing to image files 393
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


... iio.imwrite(f'random_{ i: 02d} .png', im)
>>> from glob import glob
>>> filelist = glob('random*.png')
>>> filelist.sort()

12.2 Displaying images

Use matplotlib and imshow to display an image inside a matplotlib figure:

>>> f = sp.datasets.face(gray=True) # retrieve a grayscale image


>>> import matplotlib.pyplot as plt
>>> plt.imshow(f, cmap=plt.cm.gray)
<matplotlib.image.AxesImage object at 0x...>

Increase contrast by setting min and max values:

>>> plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200)


<matplotlib.image.AxesImage object at 0x...>
>>> # Remove axes and ticks 12.3 Basic manipulations
>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5) Images are arrays: use the whole numpy machinery.

Draw contour lines:

>>> plt.contour(f, [50, 200])


<matplotlib.contour.QuadContourSet ...>

For smooth intensity variations, use interpolation='bilinear'. For fine inspection of intensity varia- >>> face = sp.datasets.face(gray=True)
tions, use interpolation='nearest': >>> face[0, 40]
127
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='bilinear') >>> # Slicing
<matplotlib.image.AxesImage object at 0x...> >>> face[10:13, 20:23]
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest') array([[141, 153, 145],
<matplotlib.image.AxesImage object at 0x...> [133, 134, 125],
[ 96, 92, 94]], dtype=uint8)
See also: >>> face[100:120] = 255
More interpolation methods are in Matplotlib’s examples. >>>
>>> lx, ly = face.shape
>>> X, Y = np.ogrid[0:lx, 0:ly]
(continues on next page)

12.2. Displaying images 394 12.3. Basic manipulations 395


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


>>> mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4
>>> # Masks
>>> face[mask] = 0
>>> # Fancy indexing
>>> face[range(400), range(400)] = 255

12.3.2 Geometrical transformations

>>> face = sp.datasets.face(gray=True)


>>> lx, ly = face.shape
>>> # Cropping
>>> crop_face = face[lx // 4: - lx // 4, ly // 4: - ly // 4]
>>> # up <-> down flip
>>> flip_ud_face = np.flipud(face)
>>> # rotation
>>> rotate_face = sp.ndimage.rotate(face, 45)
>>> rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False)

12.3.1 Statistical information

>>> face = sp.datasets.face(gray=True)


>>> face.mean()
113.48026784261067 12.4 Image filtering
>>> face.max(), face.min()
(250, 0)
Local filters: replace the value of pixels by a function of the values of neighboring pixels.
np.histogram Neighbourhood: square (choose size), disk, or more complicated structuring element.

Exercise

• Open as an array the scikit-image logo (https://scikit-image.org/_static/img/logo.png), or


an image that you have on your computer.
• Crop a meaningful part of the image, for example the python circle in the logo.
• Display the image array using matplotlib. Change the interpolation method and zoom to see
the difference. 12.4.1 Blurring/smoothing
• Transform your image to greyscale
Gaussian filter from scipy.ndimage:
• Increase the contrast of the image by changing its minimum and maximum values. Optional:
use scipy.stats.scoreatpercentile (read the docstring!) to saturate 5% of the darkest pixels >>> face = sp.datasets.face(gray=True)
and 5% of the lightest pixels. >>> blurred_face = sp.ndimage.gaussian_filter(face, sigma=3)
>>> very_blurred = sp.ndimage.gaussian_filter(face, sigma=5)
• Save the array to two different file formats (png, jpg, tiff)
Uniform filter

>>> local_mean = sp.ndimage.uniform_filter(face, size=11)

12.3. Basic manipulations 396 12.4. Image filtering 397


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> med_denoised = sp.ndimage.median_filter(noisy, 3)

Median filter: better result for straight boundaries (low curvature):


12.4.2 Sharpening >>> im = np.zeros((20, 20))
>>> im[5:-5, 5:-5] = 1
Sharpen a blurred image: >>> im = sp.ndimage.distance_transform_bf(im)
>>> face = sp.datasets.face(gray=True).astype(float) >>> rng = np.random.default_rng()
>>> blurred_f = sp.ndimage.gaussian_filter(face, 3) >>> im_noise = im + 0.2 * rng.standard_normal(im.shape)
>>> im_med = sp.ndimage.median_filter(im_noise, 3)
increase the weight of edges by adding an approximation of the Laplacian:

>>> filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1)


>>> alpha = 30
>>> sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)

Other rank filter: scipy.ndimage.maximum_filter, scipy.ndimage.percentile_filter


Other local non-linear filters: Wiener (scipy.signal.wiener), etc.
Non-local filters

Exercise: denoising

12.4.3 Denoising • Create a binary image (of 0s and 1s) with several objects (circles, ellipses, squares, or random
shapes).
Noisy face:
• Add some noise (e.g., 20% of noise)
>>> f = sp.datasets.face(gray=True) • Try two different denoising methods for denoising the image: gaussian filtering and median
>>> f = f[230:290, 220:320] filtering.
>>> rng = np.random.default_rng()
>>> noisy = f + 0.4 * f.std() * rng.random(f.shape) • Compare the histograms of the two different denoised images. Which one is the closest to the
histogram of the original (noise-free) image?
A Gaussian filter smoothes the noise out. . . and the edges as well:

>>> gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) See also:


More denoising filters are available in skimage.denoising, see the scikit-image: image processing tuto-
Most local linear isotropic filters blur the image (scipy.ndimage.uniform_filter) rial.
A median filter preserves better the edges:

12.4. Image filtering 398 12.4. Image filtering 399


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.4.4 Mathematical morphology (continued from previous page)


[0, 0, 0, 0, 0, 0, 0],
See wikipedia for a definition of mathematical morphology. [0, 0, 0, 0, 0, 0, 0],
Probe an image with a simple shape (a structuring element), and modify this image according to how [0, 0, 0, 0, 0, 0, 0],
the shape locally fits or misses the image. [0, 0, 0, 0, 0, 0, 0]])

Structuring element:

>>> el = sp.ndimage.generate_binary_structure(2, 1)
>>> el
array([[False, True, False],
[ True, True, True],
[False, True, False]])
>>> el.astype(int)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])

Dilation: maximum filter:

>>> a = np.zeros((5, 5))


>>> a[2, 2] = 1
>>> a
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> sp.ndimage.binary_dilation(a).astype(a.dtype)
array([[0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring [0., 1., 1., 1., 0.],
element.: [0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0.]])
>>> a = np.zeros((7,7), dtype=int)
>>> a[1:6, 2:5] = 1
Also works for grey-valued images:
>>> a
array([[0, 0, 0, 0, 0, 0, 0], >>> rng = np.random.default_rng(27446968)
[0, 0, 1, 1, 1, 0, 0], >>> im = np.zeros((64, 64))
[0, 0, 1, 1, 1, 0, 0], >>> x, y = (63*rng.random((2, 8))).astype(int)
[0, 0, 1, 1, 1, 0, 0], >>> im[x, y] = np.arange(8)
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0], >>> bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5,␣
[0, 0, 0, 0, 0, 0, 0]]) ˓→5)))
>>> sp.ndimage.binary_erosion(a).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0], >>> square = np.zeros((16, 16))
[0, 0, 0, 0, 0, 0, 0], >>> square[4:-4, 4:-4] = 1
[0, 0, 0, 1, 0, 0, 0], >>> dist = sp.ndimage.distance_transform_bf(square)
[0, 0, 0, 1, 0, 0, 0], >>> dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), \
[0, 0, 0, 1, 0, 0, 0], ... structure=np.ones((3, 3)))
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]) Opening: erosion + dilation:
>>> # Erosion removes objects smaller than the structure
>>> sp.ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype) >>> a = np.zeros((5,5), dtype=int)
array([[0, 0, 0, 0, 0, 0, 0], >>> a[1:4, 1:4] = 1; a[4, 4] = 1
[0, 0, 0, 0, 0, 0, 0], >>> a
[0, 0, 0, 0, 0, 0, 0], array([[0, 0, 0, 0, 0],
(continues on next page) (continues on next page)

12.4. Image filtering 400 12.4. Image filtering 401


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.5 Feature extraction

12.5.1 Edge detection

Synthetic data:

>>> im = np.zeros((256, 256))


>>> im[64:-64, 64:-64] = 1
(continued from previous page) >>>
>>> im = sp.ndimage.rotate(im, 15, mode='constant')
[0, 1, 1, 1, 0],
>>> im = sp.ndimage.gaussian_filter(im, 8)
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 1]]) Use a gradient operator (Sobel) to find high intensity variations:
>>> # Opening removes small objects >>> sx = sp.ndimage.sobel(im, axis=0, mode='constant')
>>> sp.ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int) >>> sy = sp.ndimage.sobel(im, axis=1, mode='constant')
array([[0, 0, 0, 0, 0], >>> sob = np.hypot(sx, sy)
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]])
>>> # Opening can also smooth corners
>>> sp.ndimage.binary_opening(a).astype(int)
array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]])

Application: remove noise:

>>> square = np.zeros((32, 32))


>>> square[10:-10, 10:-10] = 1
>>> rng = np.random.default_rng(27446968) 12.5.2 Segmentation
>>> x, y = (32*rng.random((2, 20))).astype(int)
>>> square[x, y] = 1 • Histogram-based segmentation (no spatial information)

>>> open_square = sp.ndimage.binary_opening(square) >>> n = 10


>>> l = 256
>>> eroded_square = sp.ndimage.binary_erosion(square) >>> im = np.zeros((l, l))
>>> reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square) >>> rng = np.random.default_rng(27446968)
>>> points = l*rng.random((2, n**2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n))

>>> mask = (im > im.mean()).astype(float)


>>> mask += 0.1 * im
>>> img = mask + 0.2*rng.standard_normal(mask.shape)

>>> hist, bin_edges = np.histogram(img, bins=60)


>>> bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:])
Closing: dilation + erosion
>>> binary_img = img > 0.5
Many other mathematical morphology operations: hit and miss transform, tophat, etc.
Use mathematical morphology to clean up the result:

>>> # Remove small white regions


>>> open_img = sp.ndimage.binary_opening(binary_img)
(continues on next page)

12.4. Image filtering 402 12.5. Feature extraction 403


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

See also:
Other Scientific Packages provide algorithms that can be useful for image processing. In this example,
we use the spectral clustering function of the scikit-learn in order to segment glued objects.

>>> from sklearn.feature_extraction import image


>>> from sklearn.cluster import spectral_clustering

>>> l = 100
>>> x, y = np.indices((l, l))

>>> center1 = (28, 24)


>>> center2 = (40, 50)
>>> center3 = (67, 58)
>>> center4 = (24, 70)
>>> radius1, radius2, radius3, radius4 = 16, 14, 15, 14
(continued from previous page)
>>> # Remove small black hole >>> circle1 = (x - center1[0])**2 + (y - center1[1])**2 < radius1**2
>>> close_img = sp.ndimage.binary_closing(open_img) >>> circle2 = (x - center2[0])**2 + (y - center2[1])**2 < radius2**2
>>> circle3 = (x - center3[0])**2 + (y - center3[1])**2 < radius3**2
>>> circle4 = (x - center4[0])**2 + (y - center4[1])**2 < radius4**2

>>> # 4 circles
>>> img = circle1 + circle2 + circle3 + circle4
>>> mask = img.astype(bool)
>>> img = img.astype(float)

>>> rng = np.random.default_rng()


>>> img += 1 + 0.2*rng.standard_normal(img.shape)
>>> # Convert the image into a graph with the value of the gradient on
>>> # the edges.
>>> graph = image.img_to_graph(img, mask=mask)
Exercise
>>> # Take a decreasing function of the gradient: we take it weakly
Check that reconstruction operations (erosion + propagation) produce a better result than open- >>> # dependent from the gradient the segmentation is close to a voronoi
ing/closing: >>> graph.data = np.exp(-graph.data/graph.data.std())

>>> eroded_img = sp.ndimage.binary_erosion(binary_img) >>> labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack')


>>> reconstruct_img = sp.ndimage.binary_propagation(eroded_img, mask=binary_img) >>> label_im = -np.ones(mask.shape)
>>> tmp = np.logical_not(reconstruct_img) >>> label_im[mask] = labels
>>> eroded_tmp = sp.ndimage.binary_erosion(tmp)
>>> reconstruct_final = np.logical_not(sp.ndimage.binary_propagation(eroded_tmp,␣
˓→mask=tmp))

>>> np.abs(mask - close_img).mean()


0.00640699...
>>> np.abs(mask - reconstruct_final).mean()
0.00082232...

Exercise

Check how a first denoising step (e.g. with a median filter) modifies the histogram, and check that
the resulting histogram-based segmentation is more accurate.

See also:
More advanced segmentation algorithms are found in the scikit-image: see scikit-image: image pro-
cessing.

12.5. Feature extraction 404 12.5. Feature extraction 405


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.6 Measuring objects properties: scipy.ndimage.measurements

Synthetic data:

>>> n = 10
>>> l = 256
>>> im = np.zeros((l, l))
>>> rng = np.random.default_rng(27446968)
>>> points = l * rng.random((2, n**2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n))
>>> mask = im > im.mean()

• Analysis of connected components


Label connected components: scipy.dimage.label:

>>> label_im, nb_labels = sp.ndimage.label(mask)


>>> nb_labels # how many regions?
28 >>> slice_x, slice_y = sp.ndimage.find_objects(label_im)[3]
>>> plt.imshow(label_im) >>> roi = im[slice_x, slice_y]
<matplotlib.image.AxesImage object at 0x...> >>> plt.imshow(roi)
<matplotlib.image.AxesImage object at 0x...>

Compute size, mean_value, etc. of each region:

>>> sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))


>>> mean_vals = sp.ndimage.sum(im, label_im, range(1, nb_labels + 1))
Other spatial measures: scipy.ndimage.center_of_mass, scipy.ndimage.maximum_position, etc.
Clean up small connect components:
Can be used outside the limited scope of segmentation applications.
>>> mask_size = sizes < 1000 Example: block mean:
>>> remove_pixel = mask_size[label_im]
>>> remove_pixel.shape >>> f = sp.datasets.face(gray=True)
(256, 256) >>> sx, sy = f.shape
>>> label_im[remove_pixel] = 0 >>> X, Y = np.ogrid[0:sx, 0:sy]
>>> plt.imshow(label_im) >>> regions = (sy//6) * (X//4) + (Y//6) # note that we use broadcasting
<matplotlib.image.AxesImage object at 0x...> >>> block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1,
... regions.max() +1))
Now reassign labels with np.searchsorted: >>> block_mean.shape = (sx // 4, sy // 6)

>>> labels = np.unique(label_im) When regions are regular blocks, it is more efficient to use stride tricks (Example: fake dimensions with
>>> label_im = np.searchsorted(labels, label_im) strides).

Find region of interest enclosing object: Non-regularly-spaced blocks: radial mean:

12.6. Measuring objects properties: scipy.ndimage.measurements 406 12.6. Measuring objects properties: scipy.ndimage.measurements 407
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> def disk_structure(n):


... struct = np.zeros((2 * n + 1, 2 * n + 1))
... x, y = np.indices((2 * n + 1, 2 * n + 1))
... mask = (x - n)**2 + (y - n)**2 <= n**2
... struct[mask] = 1
... return struct.astype(bool)
...
>>>
>>> def granulometry(data, sizes=None):
... s = max(data.shape)
... if sizes is None:
... sizes = range(1, s/2, 2)
... granulo = [sp.ndimage.binary_opening(data, \
... structure=disk_structure(n)).sum() for n in sizes]
... return granulo
...
>>>
>>> rng = np.random.default_rng(27446968)
>>> n = 10
>>> l = 256
>>> im = np.zeros((l, l))
>>> points = l*rng.random((2, n**2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> sx, sy = f.shape >>> im = sp.ndimage.gaussian_filter(im, sigma=l/(4.*n))
>>> X, Y = np.ogrid[0:sx, 0:sy] >>>
>>> r = np.hypot(X - sx/2, Y - sy/2) >>> mask = im > im.mean()
>>> rbin = (20* r/r.max()).astype(int) >>>
>>> radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1)) >>> granulo = granulometry(mask, sizes=np.arange(2, 19, 4))

12.7 Full code examples

12.8 Examples for the image processing chapter

• Other measures 12.8.1 Displaying a Raccoon Face


Correlation function, Fourier/wavelet spectrum, etc. Small example to plot a raccoon face.
One example with mathematical morphology: granulometry

12.6. Measuring objects properties: scipy.ndimage.measurements 408 12.7. Full code examples 409
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.2 Image interpolation

The example demonstrates image interpolation on a Raccoon face.

import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True)

plt.figure(figsize=(8, 4))
import scipy as sp
import imageio.v3 as iio plt.subplot(1, 2, 1)
plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray)
f = sp.datasets.face() plt.axis("off")
iio.imwrite("face.png", f) # uses the Image module (PIL)
plt.subplot(1, 2, 2)
import matplotlib.pyplot as plt plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")
plt.imshow(f)
plt.show() plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)
plt.show()
Total running time of the script: (0 minutes 0.549 seconds)
Total running time of the script: (0 minutes 0.156 seconds)

12.8. Examples for the image processing chapter 410 12.8. Examples for the image processing chapter 411
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.3 Plot the block mean of an image 12.8.4 Image manipulation and NumPy arrays

An example showing how to use broad-casting to plot the mean of blocks of an image. This example shows how to do image manipulation using common NumPy arrays tricks.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

face = sp.datasets.face(gray=True)
face[10:13, 20:23]
face[100:120] = 255

lx, ly = face.shape
X, Y = np.ogrid[0:lx, 0:ly]
mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4
face[mask] = 0
import numpy as np face[range(400), range(400)] = 255
import scipy as sp
import matplotlib.pyplot as plt plt.figure(figsize=(3, 3))
plt.axes([0, 0, 1, 1])
f = sp.datasets.face(gray=True) plt.imshow(face, cmap=plt.cm.gray)
sx, sy = f.shape plt.axis("off")
X, Y = np.ogrid[0:sx, 0:sy]
plt.show()
regions = sy // 6 * (X // 4) + Y // 6
block_mean = sp.ndimage.mean(f, labels=regions, index=np.arange(1, regions.max() + 1)) Total running time of the script: (0 minutes 0.161 seconds)
block_mean.shape = (sx // 4, sy // 6)

plt.figure(figsize=(5, 5))
plt.imshow(block_mean, cmap=plt.cm.gray)
plt.axis("off")

plt.show()

Total running time of the script: (0 minutes 0.180 seconds)

12.8. Examples for the image processing chapter 412 12.8. Examples for the image processing chapter 413
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.5 Radial mean 12.8.6 Display a Raccoon Face

This example shows how to do a radial mean with scikit-image. An example that displays a raccoon face with matplotlib.

import scipy as sp
import matplotlib.pyplot as plt

f = sp.datasets.face(gray=True)

plt.figure(figsize=(10, 3.6))

plt.subplot(131)
plt.imshow(f, cmap=plt.cm.gray)

plt.subplot(132)
plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200)
plt.axis("off")

plt.subplot(133)
plt.imshow(f, cmap=plt.cm.gray)
plt.contour(f, [50, 200])
import numpy as np
plt.axis("off")
import scipy as sp
import matplotlib.pyplot as plt
plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.
˓→99)
f = sp.datasets.face(gray=True)
plt.show()
sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy]
Total running time of the script: (0 minutes 0.370 seconds)

r = np.hypot(X - sx / 2, Y - sy / 2)

rbin = (20 * r / r.max()).astype(int)


radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1))

plt.figure(figsize=(5, 5))
plt.axes([0, 0, 1, 1])
plt.imshow(rbin, cmap=plt.cm.nipy_spectral)
plt.axis("off")

plt.show()

Total running time of the script: (0 minutes 0.175 seconds)

12.8. Examples for the image processing chapter 414 12.8. Examples for the image processing chapter 415
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.7 Image sharpening 12.8.8 Blurring of images

This example shows how to sharpen an image in noiseless situation by applying the filter inverse to the An example showing various processes that blur an image.
blur.

import scipy as sp
import scipy as sp import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
face = sp.datasets.face(gray=True)
f = sp.datasets.face(gray=True).astype(float) blurred_face = sp.ndimage.gaussian_filter(face, sigma=3)
blurred_f = sp.ndimage.gaussian_filter(f, 3) very_blurred = sp.ndimage.gaussian_filter(face, sigma=5)
local_mean = sp.ndimage.uniform_filter(face, size=11)
filter_blurred_f = sp.ndimage.gaussian_filter(blurred_f, 1)
plt.figure(figsize=(9, 3))
alpha = 30 plt.subplot(131)
sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f) plt.imshow(blurred_face, cmap=plt.cm.gray)
plt.axis("off")
plt.figure(figsize=(12, 4)) plt.subplot(132)
plt.imshow(very_blurred, cmap=plt.cm.gray)
plt.subplot(131) plt.axis("off")
plt.imshow(f, cmap=plt.cm.gray) plt.subplot(133)
plt.axis("off") plt.imshow(local_mean, cmap=plt.cm.gray)
plt.subplot(132) plt.axis("off")
plt.imshow(blurred_f, cmap=plt.cm.gray)
plt.axis("off") plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.
plt.subplot(133) ˓→99)

plt.imshow(sharpened, cmap=plt.cm.gray)
plt.axis("off") plt.show()

plt.tight_layout() Total running time of the script: (0 minutes 0.275 seconds)


plt.show()

Total running time of the script: (0 minutes 0.443 seconds)

12.8. Examples for the image processing chapter 416 12.8. Examples for the image processing chapter 417
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.9 Synthetic data 12.8.10 Opening, erosion, and propagation

The example generates and displays simple synthetic data. This example shows simple operations of mathematical morphology.

import numpy as np
import numpy as np import scipy as sp
import scipy as sp import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
square = np.zeros((32, 32))
rng = np.random.default_rng(27446968) square[10:-10, 10:-10] = 1
n = 10 rng = np.random.default_rng(27446968)
l = 256 x, y = (32 * rng.random((2, 20))).astype(int)
im = np.zeros((l, l)) square[x, y] = 1
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 open_square = sp.ndimage.binary_opening(square)
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))
eroded_square = sp.ndimage.binary_erosion(square)
mask = im > im.mean() reconstruction = sp.ndimage.binary_propagation(eroded_square, mask=square)
label_im, nb_labels = sp.ndimage.label(mask) plt.figure(figsize=(9.5, 3))
plt.subplot(131)
plt.figure(figsize=(9, 3)) plt.imshow(square, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")
plt.subplot(131) plt.subplot(132)
plt.imshow(im) plt.imshow(open_square, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off") plt.axis("off")
plt.subplot(132) plt.subplot(133)
plt.imshow(mask, cmap=plt.cm.gray) plt.imshow(reconstruction, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off") plt.axis("off")
plt.subplot(133)
plt.imshow(label_im, cmap=plt.cm.nipy_spectral) plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.
plt.axis("off") ˓→99)

plt.show()
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1)
plt.show()
Total running time of the script: (0 minutes 0.039 seconds)
Total running time of the script: (0 minutes 0.075 seconds)

12.8. Examples for the image processing chapter 418 12.8. Examples for the image processing chapter 419
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.11 Image denoising 12.8.12 Geometrical transformations

This example demoes image denoising on a Raccoon face. This examples demos some simple geometrical transformations on a Raccoon face.

import numpy as np
import numpy as np import scipy as sp
import scipy as sp import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
face = sp.datasets.face(gray=True)
rng = np.random.default_rng(27446968) lx, ly = face.shape
# Cropping
f = sp.datasets.face(gray=True) crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4]
f = f[230:290, 220:320] # up <-> down flip
flip_ud_face = np.flipud(face)
noisy = f + 0.4 * f.std() * rng.random(f.shape) # rotation
rotate_face = sp.ndimage.rotate(face, 45)
gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2) rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False)
med_denoised = sp.ndimage.median_filter(noisy, 3)
plt.figure(figsize=(12.5, 2.5))

plt.figure(figsize=(12, 2.8))
plt.subplot(151)
plt.subplot(131) plt.imshow(face, cmap=plt.cm.gray)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220) plt.axis("off")
plt.axis("off") plt.subplot(152)
plt.title("noisy", fontsize=20) plt.imshow(crop_face, cmap=plt.cm.gray)
plt.subplot(132) plt.axis("off")
plt.imshow(gauss_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) plt.subplot(153)
plt.axis("off") plt.imshow(flip_ud_face, cmap=plt.cm.gray)
plt.title("Gaussian filter", fontsize=20) plt.axis("off")
plt.subplot(133) plt.subplot(154)
plt.imshow(med_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) plt.imshow(rotate_face, cmap=plt.cm.gray)
plt.axis("off") plt.axis("off")
plt.title("Median filter", fontsize=20) plt.subplot(155)
plt.imshow(rotate_face_noreshape, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1) plt.axis("off")
plt.show()
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)
Total running time of the script: (0 minutes 0.212 seconds)
plt.show()

Total running time of the script: (0 minutes 0.460 seconds)

12.8. Examples for the image processing chapter 420 12.8. Examples for the image processing chapter 421
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.13 Find the bounding box of an object 12.8.14 Measurements from images

This example shows how to extract the bounding box of the largest object This examples shows how to measure quantities from various images.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)
n = 10
l = 256 import numpy as np
im = np.zeros((l, l)) import scipy as sp
points = l * rng.random((2, n**2)) import matplotlib.pyplot as plt
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) rng = np.random.default_rng(27446968)
n = 10
mask = im > im.mean() l = 256
im = np.zeros((l, l))
label_im, nb_labels = sp.ndimage.label(mask) points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
# Find the largest connected component im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))
sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))
mask_size = sizes < 1000 mask = im > im.mean()
remove_pixel = mask_size[label_im]
label_im[remove_pixel] = 0 label_im, nb_labels = sp.ndimage.label(mask)
labels = np.unique(label_im)
label_im = np.searchsorted(labels, label_im) sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))
mask_size = sizes < 1000
# Now that we have only one connected component, extract it's bounding box remove_pixel = mask_size[label_im]
slice_x, slice_y = sp.ndimage.find_objects(label_im == 4)[0] label_im[remove_pixel] = 0
roi = im[slice_x, slice_y] labels = np.unique(label_im)
label_clean = np.searchsorted(labels, label_im)
plt.figure(figsize=(4, 2))
plt.axes([0, 0, 1, 1])
plt.imshow(roi) plt.figure(figsize=(6, 3))
plt.axis("off")
plt.subplot(121)
plt.show() plt.imshow(label_im, cmap=plt.cm.nipy_spectral)
plt.axis("off")
Total running time of the script: (0 minutes 0.018 seconds) plt.subplot(122)
plt.imshow(label_clean, vmax=nb_labels, cmap=plt.cm.nipy_spectral)
plt.axis("off")

plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1)


plt.show()

12.8. Examples for the image processing chapter 422 12.8. Examples for the image processing chapter 423
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.040 seconds) 12.8.16 Denoising an image with the median filter

This example shows the original image, the noisy image, the denoised one (with the median filter) and
the difference between the two.
12.8.15 Total Variation denoising

This example demoes Total-Variation (TV) denoising on a Raccoon face.

import numpy as np
import numpy as np
import scipy as sp
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
rng = np.random.default_rng(27446968)
from skimage.restoration import denoise_tv_chambolle
im = np.zeros((20, 20))
rng = np.random.default_rng(27446968)
im[5:-5, 5:-5] = 1
im = sp.ndimage.distance_transform_bf(im)
f = sp.datasets.face(gray=True)
im_noise = im + 0.2 * rng.normal(size=im.shape)
f = f[230:290, 220:320]
im_med = sp.ndimage.median_filter(im_noise, 3)
noisy = f + 0.4 * f.std() * rng.random(f.shape)
plt.figure(figsize=(16, 5))
tv_denoised = denoise_tv_chambolle(noisy, weight=10)
plt.subplot(141)
plt.imshow(im, interpolation="nearest")
plt.figure(figsize=(12, 2.8))
plt.axis("off")
plt.title("Original image", fontsize=20)
plt.subplot(131)
plt.subplot(142)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.imshow(im_noise, interpolation="nearest", vmin=0, vmax=5)
plt.axis("off")
plt.axis("off")
plt.title("noisy", fontsize=20)
plt.title("Noisy image", fontsize=20)
plt.subplot(132)
plt.subplot(143)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.imshow(im_med, interpolation="nearest", vmin=0, vmax=5)
plt.axis("off")
plt.axis("off")
plt.title("TV denoising", fontsize=20)
plt.title("Median filter", fontsize=20)
plt.subplot(144)
tv_denoised = denoise_tv_chambolle(noisy, weight=50)
plt.imshow(np.abs(im - im_med), cmap=plt.cm.hot, interpolation="nearest")
plt.subplot(133)
plt.axis("off")
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.title("Error", fontsize=20)
plt.axis("off")
plt.title("(more) TV denoising", fontsize=20)
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0, right=1)
plt.show()
plt.show()
Total running time of the script: (0 minutes 0.220 seconds)
Total running time of the script: (0 minutes 0.144 seconds)

12.8. Examples for the image processing chapter 424 12.8. Examples for the image processing chapter 425
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.17 Histogram segmentation Total running time of the script: (0 minutes 0.132 seconds)

This example does simple histogram analysis to perform segmentation.

12.8.18 Greyscale dilation

This example illustrates greyscale mathematical morphology.

import numpy as np import numpy as np


import scipy as sp import scipy as sp
import matplotlib.pyplot as plt import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968) im = np.zeros((64, 64))


n = 10 rng = np.random.default_rng(27446968)
l = 256 x, y = (63 * rng.random((2, 8))).astype(int)
im = np.zeros((l, l)) im[x, y] = np.arange(8)
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 bigger_points = sp.ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5)))
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))
square = np.zeros((16, 16))
mask = (im > im.mean()).astype(float) square[4:-4, 4:-4] = 1
dist = sp.ndimage.distance_transform_bf(square)
mask += 0.1 * im dilate_dist = sp.ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3)))

img = mask + 0.2 * rng.normal(size=mask.shape) plt.figure(figsize=(12.5, 3))


plt.subplot(141)
hist, bin_edges = np.histogram(img, bins=60) plt.imshow(im, interpolation="nearest", cmap=plt.cm.nipy_spectral)
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) plt.axis("off")
plt.subplot(142)
binary_img = img > 0.5 plt.imshow(bigger_points, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.axis("off")
plt.figure(figsize=(11, 4)) plt.subplot(143)
plt.imshow(dist, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.subplot(131) plt.axis("off")
plt.imshow(img) plt.subplot(144)
plt.axis("off") plt.imshow(dilate_dist, interpolation="nearest", cmap=plt.cm.nipy_spectral)
plt.subplot(132) plt.axis("off")
plt.plot(bin_centers, hist, lw=2)
plt.axvline(0.5, color="r", ls="--", lw=2) plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.
˓→99)
plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes)
plt.yticks([]) plt.show()
plt.subplot(133)
plt.imshow(binary_img, cmap=plt.cm.gray, interpolation="nearest") Total running time of the script: (0 minutes 0.053 seconds)
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)


plt.show()

12.8. Examples for the image processing chapter 426 12.8. Examples for the image processing chapter 427
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.19 Finding edges with Sobel filters (continued from previous page)

The Sobel filter is one of the simplest way of finding edges. plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9)

plt.show()

Total running time of the script: (0 minutes 0.219 seconds)

12.8.20 Cleaning segmentation with mathematical morphology

An example showing how to clean segmentation with mathematical morphology: removing small regions
and holes.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt

rng = np.random.default_rng(27446968)

im = np.zeros((256, 256))
im[64:-64, 64:-64] = 1

im = sp.ndimage.rotate(im, 15, mode="constant") import numpy as np


im = sp.ndimage.gaussian_filter(im, 8) import scipy as sp
import matplotlib.pyplot as plt
sx = sp.ndimage.sobel(im, axis=0, mode="constant")
sy = sp.ndimage.sobel(im, axis=1, mode="constant") rng = np.random.default_rng(27446968)
sob = np.hypot(sx, sy) n = 10
l = 256
plt.figure(figsize=(16, 5)) im = np.zeros((l, l))
plt.subplot(141) points = l * rng.random((2, n**2))
plt.imshow(im, cmap=plt.cm.gray) im[(points[0]).astype(int), (points[1]).astype(int)] = 1
plt.axis("off") im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))
plt.title("square", fontsize=20)
plt.subplot(142) mask = (im > im.mean()).astype(float)
plt.imshow(sx)
plt.axis("off")
plt.title("Sobel (x direction)", fontsize=20) img = mask + 0.3 * rng.normal(size=mask.shape)
plt.subplot(143)
plt.imshow(sob) binary_img = img > 0.5
plt.axis("off")
plt.title("Sobel filter", fontsize=20) # Remove small white regions
open_img = sp.ndimage.binary_opening(binary_img)
im += 0.07 * rng.random(im.shape) # Remove small black hole
close_img = sp.ndimage.binary_closing(open_img)
sx = sp.ndimage.sobel(im, axis=0, mode="constant")
sy = sp.ndimage.sobel(im, axis=1, mode="constant") plt.figure(figsize=(12, 3))
sob = np.hypot(sx, sy)
l = 128
plt.subplot(144)
plt.imshow(sob) plt.subplot(141)
plt.axis("off") plt.imshow(binary_img[:l, :l], cmap=plt.cm.gray)
plt.title("Sobel for noisy image", fontsize=20) plt.axis("off")
plt.subplot(142)
(continues on next page) (continues on next page)

12.8. Examples for the image processing chapter 428 12.8. Examples for the image processing chapter 429
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


plt.imshow(open_img[:l, :l], cmap=plt.cm.gray) hist, bin_edges = np.histogram(img, bins=60)
plt.axis("off") bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])
plt.subplot(143)
plt.imshow(close_img[:l, :l], cmap=plt.cm.gray) classif = GaussianMixture(n_components=2)
plt.axis("off") classif.fit(img.reshape((img.size, 1)))
plt.subplot(144)
plt.imshow(mask[:l, :l], cmap=plt.cm.gray) threshold = np.mean(classif.means_)
plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") binary_img = img > threshold
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) plt.figure(figsize=(11, 4))

plt.show() plt.subplot(131)
plt.imshow(img)
Total running time of the script: (0 minutes 0.078 seconds) plt.axis("off")
plt.subplot(132)
plt.plot(bin_centers, hist, lw=2)
plt.axvline(0.5, color="r", ls="--", lw=2)
12.8.21 Segmentation with Gaussian mixture models plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes)
plt.yticks([])
plt.subplot(133)
This example performs a Gaussian mixture model analysis of the image histogram to find the right
plt.imshow(binary_img, cmap=plt.cm.gray, interpolation="nearest")
thresholds for separating foreground from background.
plt.axis("off")

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)


plt.show()

Total running time of the script: (0 minutes 0.747 seconds)

12.8.22 Watershed segmentation

This example shows how to do segmentation with watershed.

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture

rng = np.random.default_rng(27446968)
n = 10
l = 256
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))

mask = (im > im.mean()).astype(float) import numpy as np


from skimage.segmentation import watershed
from skimage.feature import peak_local_max
img = mask + 0.3 * rng.normal(size=mask.shape) import matplotlib.pyplot as plt
import scipy as sp
(continues on next page) (continues on next page)

12.8. Examples for the image processing chapter 430 12.8. Examples for the image processing chapter 431
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


import matplotlib.pyplot as plt
# Generate an initial image with two overlapping circles
x, y = np.indices((80, 80))
x1, y1, x2, y2 = 28, 28, 44, 52 def disk_structure(n):
r1, r2 = 16, 20 struct = np.zeros((2 * n + 1, 2 * n + 1))
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 x, y = np.indices((2 * n + 1, 2 * n + 1))
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 mask = (x - n) ** 2 + (y - n) ** 2 <= n**2
image = np.logical_or(mask_circle1, mask_circle2) struct[mask] = 1
# Now we want to separate the two objects in image return struct.astype(bool)
# Generate the markers as local maxima of the distance
# to the background
distance = sp.ndimage.distance_transform_edt(image) def granulometry(data, sizes=None):
peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) s = max(data.shape)
peak_mask = np.zeros_like(distance, dtype=bool) if sizes is None:
peak_mask[tuple(peak_idx.T)] = True sizes = range(1, s / 2, 2)
markers = sp.ndimage.label(peak_mask)[0] granulo = [
labels = watershed(-distance, markers, mask=image) sp.ndimage.binary_opening(data, structure=disk_structure(n)).sum()
for n in sizes
plt.figure(figsize=(9, 3.5)) ]
plt.subplot(131) return granulo
plt.imshow(image, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(132) rng = np.random.default_rng(27446968)
plt.imshow(-distance, interpolation="nearest") n = 10
plt.axis("off") l = 256
plt.subplot(133) im = np.zeros((l, l))
plt.imshow(labels, cmap="nipy_spectral", interpolation="nearest") points = l * rng.random((2, n**2))
plt.axis("off") im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))
plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)
plt.show() mask = im > im.mean()

Total running time of the script: (0 minutes 0.059 seconds) granulo = granulometry(mask, sizes=np.arange(2, 19, 4))

plt.figure(figsize=(6, 2.2))

12.8.23 Granulometry plt.subplot(121)


plt.imshow(mask, cmap=plt.cm.gray)
opened = sp.ndimage.binary_opening(mask, structure=disk_structure(10))
This example performs a simple granulometry analysis.
opened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14))
plt.contour(opened, [0.5], colors="b", linewidths=2)
plt.contour(opened_more, [0.5], colors="r", linewidths=2)
plt.axis("off")
plt.subplot(122)
plt.plot(np.arange(2, 19, 4), granulo, "ok", ms=8)

plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.


˓→95)

plt.show()

Total running time of the script: (0 minutes 0.251 seconds)

import numpy as np
import scipy as sp
(continues on next page)

12.8. Examples for the image processing chapter 432 12.8. Examples for the image processing chapter 433
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

12.8.24 Segmentation with spectral clustering (continued from previous page)


˓→99)
This example uses spectral clustering to do segmentation. plt.show()
import numpy as np
import matplotlib.pyplot as plt

from sklearn.feature_extraction import image


from sklearn.cluster import spectral_clustering

l = 100
x, y = np.indices((l, l))

center1 = (28, 24)


center2 = (40, 50)
center3 = (67, 58)
center4 = (24, 70)

radius1, radius2, radius3, radius4 = 16, 14, 15, 14

circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2


circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2
circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2
circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2 Total running time of the script: (0 minutes 0.403 seconds)

4 circles

img = circle1 + circle2 + circle3 + circle4


mask = img.astype(bool)
img = img.astype(float)
See also:
rng = np.random.default_rng(27446968)
img += 1 + 0.2 * rng.normal(size=img.shape) More on image-processing:
• The chapter on Scikit-image
# Convert the image into a graph with the value of the gradient on the
# edges. • Other, more powerful and complete modules: OpenCV (Python bindings), CellProfiler, ITK with
graph = image.img_to_graph(img, mask=mask) Python bindings

# Take a decreasing function of the gradient: we take it weakly


# dependent from the gradient the segmentation is close to a voronoi
graph.data = np.exp(-graph.data / graph.data.std())

# Force the solver to be arpack, since amg is numerically


# unstable on this example
labels = spectral_clustering(graph, n_clusters=4)
label_im = -np.ones(mask.shape)
label_im[mask] = labels

plt.figure(figsize=(6, 3))
plt.subplot(121)
plt.imshow(img, cmap=plt.cm.nipy_spectral, interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(label_im, cmap=plt.cm.nipy_spectral, interpolation="nearest")
plt.axis("off")

plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.


(continues on next page)

12.8. Examples for the image processing chapter 434 12.8. Examples for the image processing chapter 435
Scientific Python Lectures, Edition 2024.2rc0.dev0

Chapters contents

• Knowing your problem


– Convex versus non-convex optimization
– Smooth and non-smooth problems
– Noisy versus exact cost functions

CHAPTER 13 – Constraints
• A review of the different optimizers
– Getting started: 1D optimization
– Gradient based methods
– Newton and quasi-newton methods
• Full code examples
• Examples for the mathematical optimization chapter
– Gradient-less methods
– Global optimizers
Mathematical optimization: finding • Practical guide to optimization with SciPy

minima of functions – Choosing a method


– Making your optimizer faster
– Computing gradients
– Synthetic exercices
• Special case: non-linear least-squares
– Minimizing the norm of a vector function
Authors: Gaël Varoquaux
– Curve fitting
Mathematical optimization deals with the problem of finding numerically minimums (or maximums or
zeros) of a function. In this context, the function is called cost function, or objective function, or energy. • Optimization with constraints

Here, we are interested in using scipy.optimize for black-box optimization: we do not rely on the – Box bounds
mathematical expression of the function that we are optimizing. Note that this expression can often be – General constraints
used for more efficient, non black-box, optimization.
• Full code examples

Prerequisites • Examples for the mathematical optimization chapter

• NumPy
• SciPy
13.1 Knowing your problem
• Matplotlib
Not all optimization problems are equal. Knowing your problem enables you to choose the right tool.
See also:
References Dimensionality of the problem
Mathematical optimization is very . . . mathematical. If you want performance, it really pays to read
The scale of an optimization problem is pretty much set by the dimensionality of the problem, i.e. the
the books:
number of scalar variables on which the search is performed.
• Convex Optimization by Boyd and Vandenberghe (pdf available free online).
• Numerical Optimization, by Nocedal and Wright. Detailed reference on gradient descent methods.
• Practical Methods of Optimization by Fletcher: good at hand-waving explanations.

436 13.1. Knowing your problem 437


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.1.1 Convex versus non-convex optimization 13.1.3 Noisy versus exact cost functions

Noisy (blue) and non-noisy (green) functions


A convex function: A non-convex function
• f is above all its tangents.
• equivalently, for two point A, B, f(C) lies Noisy gradients
below the segment [f(A), f(B])], if A < C <
B Many optimization methods rely on gradients of the objective function. If the gradient function is not
given, they are computed numerically, which induces errors. In such situation, even if the objective
function is not noisy, a gradient-based optimization may be a noisy optimization.
Optimizing convex functions is easy. Optimizing non-convex functions can be very hard.

Note: It can be proven that for a convex function a local minimum is also a global minimum. Then, 13.1.4 Constraints
in some sense, the minimum is unique.

13.1.2 Smooth and non-smooth problems

Optimizations under constraints


Here:
−1 < 𝑥1 < 1
−1 < 𝑥2 < 1

A smooth function: A non-smooth function


The gradient is defined everywhere, and is a continuous function

Optimizing smooth functions is easier (true in the context of black-box optimization, otherwise Lin-
ear Programming is an example of methods which deal very efficiently with piece-wise linear functions).

13.1. Knowing your problem 438 13.1. Knowing your problem 439
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.2 A review of the different optimizers


Note: You can use different solvers using the parameter method.

13.2.1 Getting started: 1D optimization


Note: scipy.optimize.minimize_scalar() can also be used for optimization constrained to an
Let’s get started by finding the minimum of the scalar function 𝑓 (𝑥) = exp[(𝑥−0.7)2 ]. scipy.optimize.
interval using the parameter bounds.
minimize_scalar() uses Brent’s method to find the minimum of a function:

>>> import numpy as np


>>> import scipy as sp
>>> def f(x):
13.2.2 Gradient based methods
... return -np.exp(-(x - 0.5)**2)
>>> result = sp.optimize.minimize_scalar(f) Some intuitions about gradient descent
>>> result.success # check if solver was successful
True Here we focus on intuitions, not code. Code will follow.
>>> x_min = result.x Gradient descent basically consists in taking small steps in the direction of the gradient, that is the
>>> x_min direction of the steepest descent.
0.50...
>>> x_min - 0.5
Table 3: Fixed step gradient descent
5.8...e-09

Table 1: Brent’s method on a quadratic function: it converges


in 3 iterations, as the quadratic approximation is then exact.

A well-conditioned
quadratic function.

An ill-conditioned
Table 2: Brent’s method on a non-convex function: note that
quadratic function.
the fact that the optimizer avoided the local minimum is a matter
The core problem of gradient-
of luck.
methods on ill-conditioned
problems is that the gradient
tends not to point in the direc-
tion of the minimum.

We can see that very anisotropic (ill-conditioned) functions are harder to optimize.

Take home message: conditioning number and preconditioning

If you know natural scaling for your variables, prescale them so that they behave similarly. This is
related to preconditioning.

Also, it clearly can be advantageous to take bigger steps. This is done in gradient descent code using a
line search.

13.2. A review of the different optimizers 440 13.2. A review of the different optimizers 441
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Conjugate gradient descent


Table 4: Adaptive step gradient descent
The gradient descent algorithms above are toys not to be used on real problems.
As can be seen from the above experiments, one of the problems of the simple gradient descent algorithms,
is that it tends to oscillate across a valley, each time following the direction of the gradient, that makes
it cross the valley. The conjugate gradient solves this problem by adding a friction term: each step
depends on the two last values of the gradient and sharp turns are reduced.

Table 5: Conjugate gradient descent

A well-conditioned quadratic
function.

An ill-conditioned non-
quadratic function.

An ill-conditioned quadratic
function.

An ill-conditioned very non-


quadratic function.

An ill-conditioned non-
quadratic function. SciPy provides scipy.optimize.minimize() to find the minimum of scalar functions of one or more
variables. The simple conjugate gradient method can be used by setting the parameter method to CG

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> sp.optimize.minimize(f, [2, -1], method="CG")
message: Optimization terminated successfully.
success: True
status: 0
fun: 1.650...e-11
x: [ 1.000e+00 1.000e+00]
An ill-conditioned very non- nit: 13
quadratic function. jac: [-6.15...e-06 2.53...e-07]
nfev: 81
The more a function looks like a quadratic function (elliptic iso-curves), the easier it is to optimize. njev: 27

Gradient methods need the Jacobian (gradient) of the function. They can compute it numerically, but
will perform better if you can pass them the gradient:

>>> def jacobian(x):


... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2, 1], method="CG", jac=jacobian)


message: Optimization terminated successfully.
(continues on next page)

13.2. A review of the different optimizers 442 13.2. A review of the different optimizers 443
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


success: True
status: 0
fun: 2.95786...e-14
x: [ 1.000e+00 1.000e+00]
nit: 8
jac: [ 7.183e-07 -2.990e-07]
nfev: 16
njev: 16

Note that the function has only been evaluated 27 times, compared to 108 without the gradient. An ill-conditioned
quadratic function:
Note that, as the quadratic ap-
13.2.3 Newton and quasi-newton methods proximation is exact, the New-
ton method is blazing fast
Newton methods: using the Hessian (2nd differential)

Newton methods use a local quadratic approximation to compute the jump direction. For this purpose,
they rely on the 2 first derivative of the function: the gradient and the Hessian.

An ill-conditioned non-
quadratic function:
Here we are optimizing a Gaus-
sian, which is always below its
quadratic approximation. As a
result, the Newton method over-
shoots and leads to oscillations.

An ill-conditioned very non-


quadratic function:

In SciPy, you can use the Newton method by setting method to Newton-CG in scipy.optimize.
minimize(). Here, CG refers to the fact that an internal inversion of the Hessian is performed by
conjugate gradient

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def jacobian(x):
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian)


message: Optimization terminated successfully.
success: True
status: 0
fun: 1.5601357400786612e-15
(continues on next page)

13.2. A review of the different optimizers 444 13.2. A review of the different optimizers 445
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


x: [ 1.000e+00 1.000e+00]
nit: 10
jac: [ 1.058e-07 -7.483e-08]
nfev: 11
njev: 33
nhev: 0

Note that compared to a conjugate gradient (above), Newton’s method has required less function evalua-
tions, but more gradient evaluations, as it uses it to approximate the Hessian. Let’s compute the Hessian
and pass it to the algorithm:

>>> def hessian(x): # Computed with sympy


... return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
>>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian, hess=hessian)
message: Optimization terminated successfully.
success: True import numpy as np
status: 0 import matplotlib.pyplot as plt
fun: 1.6277298383706738e-15
x: [ 1.000e+00 1.000e+00] rng = np.random.default_rng(27446968)
nit: 10
jac: [ 1.110e-07 -7.781e-08] x = np.linspace(-5, 5, 101)
nfev: 11 x_ = np.linspace(-5, 5, 31)
njev: 11
nhev: 10
def f(x):
return -np.exp(-(x**2))
Note: At very high-dimension, the inversion of the Hessian can be costly and unstable (large scale >
250).
# A smooth function
plt.figure(1, figsize=(3, 2.5))
plt.clf()
Note: Newton optimizers should not to be confused with Newton’s root finding method, based on the
same principles, scipy.optimize.newton(). plt.plot(x_, f(x_) + 0.2 * np.random.normal(size=31), linewidth=2)
plt.plot(x, f(x), linewidth=2)

Quasi-Newton methods: approximating the Hessian on the fly plt.ylim(ymin=-1.3)


plt.axis("off")
BFGS: BFGS (Broyden-Fletcher-Goldfarb-Shanno algorithm) refines at each step an approximation of plt.tight_layout()
the Hessian. plt.show()

Total running time of the script: (0 minutes 0.019 seconds)


13.3 Full code examples

13.4 Examples for the mathematical optimization chapter

13.4.1 Noisy optimization problem

Draws a figure explaining noisy vs non-noisy optimization

13.3. Full code examples 446 13.4. Examples for the mathematical optimization chapter 447
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.2 Smooth vs non-smooth (continued from previous page)


plt.ylim(ymin=-0.2)
Draws a figure to explain smooth versus non smooth optimization. plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.047 seconds)

13.4.3 Curve fitting

A curve fitting example

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-1.5, 1.5, 101)

# A smooth function
plt.figure(1, figsize=(3, 2.5))
plt.clf()
import numpy as np
plt.plot(x, np.sqrt(0.2 + x**2), linewidth=2) import scipy as sp
plt.text(-1, 0, "$f$", size=20) import matplotlib.pyplot as plt

plt.ylim(ymin=-0.2) rng = np.random.default_rng(27446968)


plt.axis("off")
plt.tight_layout()
# Our test function
# A non-smooth function def f(t, omega, phi):
plt.figure(2, figsize=(3, 2.5)) return np.cos(omega * t + phi)
plt.clf()
plt.plot(x, np.abs(x), linewidth=2)
plt.text(-1, 0, "$f$", size=20) # Our x and y data
x = np.linspace(0, 3, 50)
(continues on next page) (continues on next page)

13.4. Examples for the mathematical optimization chapter 448 13.4. Examples for the mathematical optimization chapter 449
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


import numpy as np
y = f(x, 1.5, 1) + 0.1 * np.random.normal(size=50) import matplotlib.pyplot as plt

# Fit the model: the parameters omega and phi can be found in the x = np.linspace(-1, 2)
# `params` vector
params, params_cov = sp.optimize.curve_fit(f, x, y) plt.figure(1, figsize=(3, 2.5))
plt.clf()
# plot the data and the fitted curve
t = np.linspace(0, 3, 1000) # A convex function
plt.plot(x, x**2, linewidth=2)
plt.figure(1) plt.text(-0.7, -(0.6**2), "$f$", size=20)
plt.clf()
plt.plot(x, y, "bx") # The tangent in one point
plt.plot(t, f(t, *params), "r-") plt.plot(x, 2 * x - 1)
plt.show() plt.plot(1, 1, "k+")
plt.text(0.3, -0.75, "Tangent to $f$", size=15)
Total running time of the script: (0 minutes 0.066 seconds) plt.text(1, 1 - 0.5, "C", size=15)

# Convexity as barycenter
plt.plot([0.35, 1.85], [0.35**2, 1.85**2])
13.4.4 Convex function plt.plot([0.35, 1.85], [0.35**2, 1.85**2], "k+")
plt.text(0.35 - 0.2, 0.35**2 + 0.1, "A", size=15)
A figure showing the definition of a convex function plt.text(1.85 - 0.2, 1.85**2, "B", size=15)

plt.ylim(ymin=-1)
plt.axis("off")
plt.tight_layout()

# Convexity as barycenter
plt.figure(2, figsize=(3, 2.5))
plt.clf()
plt.plot(x, x**2 + np.exp(-5 * (x - 0.5) ** 2), linewidth=2)
plt.text(-0.7, -(0.6**2), "$f$", size=20)

plt.ylim(ymin=-1)
plt.axis("off")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.055 seconds)

13.4.5 Finding a minimum in a flat neighborhood

An exercise of finding minimum. This exercise is hard because the function is very flat around the
minimum (all its derivatives are zero). Thus gradient information is unreliable.
The function admits a minimum in [0, 0]. The challenge is to get within 1e-7 of this minimum, starting
at x0 = [1, 1].
The solution that we adopt here is to give up on using gradient or information based on local differences,
and to rely on the Powell algorithm. With 162 function evaluations, we get to 1e-8 of the solution.
import numpy as np

import scipy as sp
import matplotlib.pyplot as plt

(continues on next page)

13.4. Examples for the mathematical optimization chapter 450 13.4. Examples for the mathematical optimization chapter 451
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

def f(x):
return np.exp(-1 / (0.01 * x[0] ** 2 + x[1] ** 2))

# A well-conditionned version of f:
def g(x):
return f([10 * x[0], x[1]])

# The gradient of g. We won't use it here for the optimization.


def g_prime(x):
r = np.sqrt(x[0] ** 2 + x[1] ** 2)
return 2 / r**3 * g(x) * x / r

result = sp.optimize.minimize(g, [1, 1], method="Powell", tol=1e-10)


x_min = result.x

Some pretty plotting

plt.figure(0)
plt.clf()
t = np.linspace(-1.1, 1.1, 100)
plt.plot(t, f([0, t]))

plt.figure(1)
plt.clf()
X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j]
plt.imshow(
f([X, Y]).T, cmap=plt.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], origin="lower"
)
plt.contour(X, Y, f([X, Y]), cmap=plt.cm.gnuplot)

# Plot the gradient


dX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]])
# Adjust for our preconditioning
dX *= 0.1
plt.quiver(X[::5, ::5], Y[::5, ::5], dX, dY, color=".5")

# Plot our solution


plt.plot(x_min[0], x_min[1], "r+", markersize=15)

plt.show()


Total running time of the script: (0 minutes 0.143 seconds)

13.4. Examples for the mathematical optimization chapter 452 13.4. Examples for the mathematical optimization chapter 453
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.6 Optimization with constraints (continued from previous page)


def constraint(x):
An example showing how to do optimization with general constraints using SLSQP and cobyla. return np.atleast_1d(1.5 - np.sum(np.abs(x)))

sp.optimize.minimize(
f, np.array([0, 0]), method="SLSQP", constraints={"fun": constraint, "type": "ineq
˓→"}

accumulated = np.array(accumulator)
plt.plot(accumulated[:, 0], accumulated[:, 1])

plt.show()

Total running time of the script: (0 minutes 0.055 seconds)

import numpy as np 13.4.7 Brent’s method


import matplotlib.pyplot as plt
import scipy as sp Illustration of 1D optimization: Brent’s method

x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04]
x = x.T
y = y.T

plt.figure(1, figsize=(3, 2.5))


plt.clf()
plt.axes([0, 0, 1, 1])

contours = plt.contour(
np.sqrt((x - 3) ** 2 + (y - 2) ** 2),
extent=[-2.03, 4.2, -1.6, 3.2],
cmap=plt.cm.gnuplot,
)
plt.clabel(contours, inline=1, fmt="%1.1f ", fontsize=14)
plt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], "k", linewidth=2) •
plt.fill_between([-1.5, 0, 1.5], [0, -1.5, 0], [0, 1.5, 0], color=".8")
plt.axvline(0, color="k")
plt.axhline(0, color="k")

plt.text(-0.9, 2.8, "$x_2$", size=20)


plt.text(3.6, -0.6, "$x_1$", size=20)
plt.axis("tight")
plt.axis("off")

# And now plot the optimization path


accumulator = []

def f(x):
# Store the list of function calls
accumulator.append(x)
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)

(continues on next page)

13.4. Examples for the mathematical optimization chapter 454 13.4. Examples for the mathematical optimization chapter 455
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# A convex function
plt.plot(x, f(x), linewidth=2)

# Apply brent method. To have access to the iteration, do this in an


# artificial way: allow the algorithm to iter only once
all_x = []
all_y = []
for iter in range(30):
result = sp.optimize.minimize_scalar(
f,
bracket=(-5, 2.9, 4.5),
method="Brent",
• options={"maxiter": iter},
tol=np.finfo(1.0).eps,
)
if result.success:
print("Converged at ", iter)
break

this_x = result.x
all_x.append(this_x)
all_y.append(f(this_x))
if iter < 6:
plt.text(
this_x - 0.05 * np.sign(this_x) - 0.05,
f(this_x) + 1.2 * (0.3 - iter % 2),
iter + 1,
size=12,
)

plt.plot(all_x[:10], all_y[:10], "k+", markersize=12, markeredgewidth=2)


Converged at 6 plt.plot(all_x[-1], all_y[-1], "rx", markersize=12)


Converged at 23 plt.axis("off")
plt.ylim(ymin=-1, ymax=8)

plt.figure(figsize=(4, 3))
plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2)
plt.ylabel("Error on f(x)")
plt.xlabel("Iteration")
import numpy as np plt.tight_layout()
import matplotlib.pyplot as plt
import scipy as sp plt.show()

x = np.linspace(-1, 3, 100) Total running time of the script: (0 minutes 0.285 seconds)
x_0 = np.exp(-1)

def f(x):
return (x - x_0) ** 2 + epsilon * np.exp(-5 * (x - 0.5 - x_0) ** 2)

for epsilon in (0, 1):


plt.figure(figsize=(3, 2.5))
plt.axes([0, 0, 1, 1])
(continues on next page)

13.4. Examples for the mathematical optimization chapter 456 13.4. Examples for the mathematical optimization chapter 457
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.8 Constraint optimization: visualizing the geometry (continued from previous page)
[-1.5, -1.5, 1.5, 1.5, -1.5], [-1.5, 1.5, 1.5, -1.5, -1.5], "k", linewidth=2
A small figure explaining optimization with constraints )
plt.fill_between([-1.5, 1.5], [-1.5, -1.5], [1.5, 1.5], color=".8")
plt.axvline(0, color="k")
plt.axhline(0, color="k")

plt.text(-0.9, 4.4, "$x_2$", size=20)


plt.text(5.6, -0.6, "$x_1$", size=20)
plt.axis("equal")
plt.axis("off")

# And now plot the optimization path


accumulator = []

def f(x):
# Store the list of function calls
• accumulator.append(x)
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)

# We don't use the gradient, as with the gradient, L-BFGS is too fast,
# and finds the optimum without showing us a pretty path
def f_prime(x):
r = np.sqrt((x[0] - 3) ** 2 + (x[0] - 2) ** 2)
return np.array(((x[0] - 3) / r, (x[0] - 2) / r))

sp.optimize.minimize(
f, np.array([0, 0]), method="L-BFGS-B", bounds=((-1.5, 1.5), (-1.5, 1.5))
)

• accumulated = np.array(accumulator)
plt.plot(accumulated[:, 0], accumulated[:, 1])
import numpy as np
import matplotlib.pyplot as plt plt.show()
import scipy as sp
Total running time of the script: (0 minutes 0.102 seconds)
x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05]
x = x.T
y = y.T
13.4.9 Alternating optimization
for i in (1, 2):
# Create 2 figure: only the second one will have the optimization The challenge here is that Hessian of the problem is a very ill-conditioned matrix. This can easily be
# path seen, as the Hessian of the first term in simply 2 * K.T @ K. Thus the conditioning of the problem can
plt.figure(i, figsize=(3, 2.5)) be judged from looking at the conditioning of K.
plt.clf()
plt.axes([0, 0, 1, 1]) import time

contours = plt.contour( import numpy as np


np.sqrt((x - 3) ** 2 + (y - 2) ** 2), import scipy as sp
extent=[-3, 6, -2.5, 5], import matplotlib.pyplot as plt
cmap=plt.cm.gnuplot,
) rng = np.random.default_rng(27446968)
plt.clabel(contours, inline=1, fmt="%1.1f ", fontsize=14)
plt.plot( K = rng.normal(size=(100, 100))
(continues on next page) (continues on next page)

13.4. Examples for the mathematical optimization chapter 458 13.4. Examples for the mathematical optimization chapter 459
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


t0 = time.time()
x_l_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="L-BFGS-B").x
def f(x): print(
return np.sum((K @ (x - 1)) ** 2) + np.sum(x**2) ** 2 f"L-BFGS w f': time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_l_bfgs -
˓→ x_ref) ** 2)): .2f} , f error { f(x_l_bfgs) - f_ref: .2f} "

)
def f_prime(x):
return 2 * K.T @ K @ (x - 1) + 4 * np.sum(x**2) * x t0 = time.time()
x_newton = sp.optimize.minimize(
f, K[0], jac=f_prime, hess=hessian, method="Newton-CG"
def hessian(x): ).x
H = 2 * K.T @ K + 4 * 2 * x * x[:, np.newaxis] print(
return H + 4 * np.eye(H.shape[0]) * np.sum(x**2) f" Newton: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_newton -
˓→ x_ref) ** 2)): .2f} , f error { f(x_newton) - f_ref: .2f} "

Some pretty plotting )

plt.figure(1) plt.show()
plt.clf()
Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j]
# Complete in the additional dimensions with zeros
Z = np.reshape(Z, (2, -1)).copy()
Z.resize((100, Z.shape[-1]))
Z = np.apply_along_axis(f, 0, Z)
Z = np.reshape(Z, X.shape)
plt.imshow(Z.T, cmap=plt.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], origin="lower")
plt.contour(X, Y, Z, cmap=plt.cm.gnuplot)

# A reference but slow solution:


t0 = time.time()
x_ref = sp.optimize.minimize(f, K[0], method="Powell").x
print(f" Powell: time { time.time() - t0: .2f} s")
f_ref = f(x_ref)

# Compare different approaches


t0 = time.time()
x_bfgs = sp.optimize.minimize(f, K[0], method="BFGS").x
print(
f" BFGS: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_bfgs -␣
˓→x_ref) ** 2)): .2f} , f error { f(x_bfgs) - f_ref: .2f} "

t0 = time.time()
x_l_bfgs = sp.optimize.minimize(f, K[0], method="L-BFGS-B").x
print(
f" L-BFGS: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_l_bfgs -
˓→ x_ref) ** 2)): .2f} , f error { f(x_l_bfgs) - f_ref: .2f} "

)
Powell: time 0.20s
BFGS: time 0.90s, x error 0.02, f error -0.03
t0 = time.time() L-BFGS: time 0.07s, x error 0.02, f error -0.03
x_bfgs = sp.optimize.minimize(f, K[0], jac=f_prime, method="BFGS").x BFGS w f': time 0.06s, x error 0.02, f error -0.03
print( L-BFGS w f': time 0.00s, x error 0.02, f error -0.03
f" BFGS w f': time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_bfgs -␣ Newton: time 0.00s, x error 0.02, f error -0.03
˓→x_ref) ** 2)): .2f} , f error { f(x_bfgs) - f_ref: .2f} "

)
Total running time of the script: (0 minutes 1.533 seconds)
(continues on next page)

13.4. Examples for the mathematical optimization chapter 460 13.4. Examples for the mathematical optimization chapter 461
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.4.10 Plotting the comparison of optimizers (continued from previous page)


[
Plots the results from the comparison of optimizers. bench,
],
marker=symbol,
color=color,
)

# Create a legend for the problem type


for cost_name, symbol in zip(sorted(n_dim_bench.keys()), symbols, strict=True):
plt.semilogy(
[
-10,
],
[
0,
],
symbol,
color=".5",
import pickle label=cost_name,
import sys )

import numpy as np plt.xticks(np.arange(n_methods), method_names, size=11)


import matplotlib.pyplot as plt plt.xlim(-0.2, n_methods - 0.5)
plt.legend(loc="best", numpoints=1, handletextpad=0, prop={"size": 12}, frameon=False)
results = pickle.load( plt.ylabel("# function calls (a.u.)")
open(f"helper/compare_optimizers_py{ sys.version_info[0]} .pkl", "rb")
) # Create a second legend for the problem dimensionality
n_methods = len(list(results.values())[0]["Rosenbrock "]) plt.twinx()
n_dims = len(results)
for n_dim, color in zip(sorted(results.keys()), colors, strict=True):
symbols = "o>*Ds" plt.plot(
[
plt.figure(1, figsize=(10, 4)) -10,
plt.clf() ],
[
colors = plt.cm.nipy_spectral(np.linspace(0, 1, n_dims))[:, :3] 0,
],
method_names = list(list(results.values())[0]["Rosenbrock "].keys()) "o",
method_names.sort(key=lambda x: x[::-1], reverse=True) color=color,
label="# dim: %i " % n_dim,
for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate( )
zip(sorted(results.items()), colors, strict=True) plt.legend(
): loc=(0.47, 0.07),
for (cost_name, cost_bench), symbol in zip( numpoints=1,
sorted(n_dim_bench.items()), symbols, strict=True handletextpad=0,
): prop={"size": 12},
for ( frameon=False,
method_index, ncol=2,
method_name, )
) in enumerate(method_names): plt.xlim(-0.2, n_methods - 0.5)
this_bench = cost_bench[method_name]
bench = np.mean(this_bench) plt.xticks(np.arange(n_methods), method_names)
plt.semilogy( plt.yticks(())
[
method_index + 0.1 * n_dim_index, plt.tight_layout()
], plt.show()
(continues on next page)

13.4. Examples for the mathematical optimization chapter 462 13.4. Examples for the mathematical optimization chapter 463
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Total running time of the script: (0 minutes 0.621 seconds) (continued from previous page)
all_f_i.append(f([x_i, y_i]))
dx_i, dy_i = f_prime(np.asarray([x_i, y_i]))
if adaptative:
13.4.11 Gradient descent # Compute a step size using a line_search to satisfy the Wolf
# conditions
An example demoing gradient descent by creating figures that trace the evolution of the optimizer. step = sp.optimize.line_search(
f,
import numpy as np f_prime,
import matplotlib.pyplot as plt np.r_[x_i, y_i],
import scipy as sp -np.r_[dx_i, dy_i],
np.r_[dx_i, dy_i],
import sys c2=0.05,
import os )
step = step[0]
sys.path.append(os.path.abspath("helper")) if step is None:
from cost_functions import ( step = 0
mk_quad, else:
mk_gauss, step = 1
rosenbrock, x_i += -step * dx_i
rosenbrock_prime, y_i += -step * dy_i
rosenbrock_hessian, if np.abs(all_f_i[-1]) < 1e-16:
LoggingFunction, break
CountingFunction, return all_x_i, all_y_i, all_f_i
)

x_min, x_max = -1, 2 def gradient_descent_adaptative(x0, f, f_prime, hessian=None):


y_min, y_max = 2.25 / 3 * x_min - 0.2, 2.25 / 3 * x_max - 0.2 return gradient_descent(x0, f, f_prime, adaptative=True)

A formatter to print values on contours


def conjugate_gradient(x0, f, f_prime, hessian=None):
def super_fmt(value):
all_x_i = [x0[0]]
if value > 1:
all_y_i = [x0[1]]
if np.abs(int(value) - value) < 0.1:
all_f_i = [f(x0)]
out = f"$10^{{{ int(value): d}}} $"
else:
def store(X):
out = f"$10^{{{ value: .1f}}} $"
x, y = X
else:
all_x_i.append(x)
value = np.exp(value - 0.01)
all_y_i.append(y)
if value > 0.1:
all_f_i.append(f(X))
out = f"{ value: 1.1f} "
elif value > 0.01:
sp.optimize.minimize(
out = f"{ value: .2f} "
f, x0, jac=f_prime, method="CG", callback=store, options={"gtol": 1e-12}
else:
)
out = f"{ value: .2e} "
return all_x_i, all_y_i, all_f_i
return out

A gradient descent algorithm do not use: its a toy, use scipy’s optimize.fmin_cg def newton_cg(x0, f, f_prime, hessian):
def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False): all_x_i = [x0[0]]
x_i, y_i = x0 all_y_i = [x0[1]]
all_x_i = [] all_f_i = [f(x0)]
all_y_i = []
all_f_i = [] def store(X):
x, y = X
for i in range(1, 100): all_x_i.append(x)
all_x_i.append(x_i) all_y_i.append(y)
all_y_i.append(y_i) all_f_i.append(f(X))
(continues on next page) (continues on next page)

13.4. Examples for the mathematical optimization chapter 464 13.4. Examples for the mathematical optimization chapter 465
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


all_f_i.append(f(X))
sp.optimize.minimize(
f, sp.optimize.minimize(
x0, f, x0, method="Nelder-Mead", callback=store, options={"ftol": 1e-12}
method="Newton-CG", )
jac=f_prime, return all_x_i, all_y_i, all_f_i
hess=hessian,
callback=store, Run different optimizers on these problems
options={"xtol": 1e-12},
) levels = {}
return all_x_i, all_y_i, all_f_i
for index, ((f, f_prime, hessian), optimizer) in enumerate(
(
def bfgs(x0, f, f_prime, hessian=None): (mk_quad(0.7), gradient_descent),
all_x_i = [x0[0]] (mk_quad(0.7), gradient_descent_adaptative),
all_y_i = [x0[1]] (mk_quad(0.02), gradient_descent),
all_f_i = [f(x0)] (mk_quad(0.02), gradient_descent_adaptative),
(mk_gauss(0.02), gradient_descent_adaptative),
def store(X): (
x, y = X (rosenbrock, rosenbrock_prime, rosenbrock_hessian),
all_x_i.append(x) gradient_descent_adaptative,
all_y_i.append(y) ),
all_f_i.append(f(X)) (mk_gauss(0.02), conjugate_gradient),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), conjugate_gradient),
sp.optimize.minimize( (mk_quad(0.02), newton_cg),
f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-12} (mk_gauss(0.02), newton_cg),
) ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), newton_cg),
return all_x_i, all_y_i, all_f_i (mk_quad(0.02), bfgs),
(mk_gauss(0.02), bfgs),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), bfgs),
def powell(x0, f, f_prime, hessian=None): (mk_quad(0.02), powell),
all_x_i = [x0[0]] (mk_gauss(0.02), powell),
all_y_i = [x0[1]] ((rosenbrock, rosenbrock_prime, rosenbrock_hessian), powell),
all_f_i = [f(x0)] (mk_gauss(0.02), nelder_mead),
((rosenbrock, rosenbrock_prime, rosenbrock_hessian), nelder_mead),
def store(X): )
x, y = X ):
all_x_i.append(x) # Compute a gradient-descent
all_y_i.append(y) x_i, y_i = 1.6, 1.1
all_f_i.append(f(X)) counting_f_prime = CountingFunction(f_prime)
counting_hessian = CountingFunction(hessian)
sp.optimize.minimize( logging_f = LoggingFunction(f, counter=counting_f_prime.counter)
f, x0, method="Powell", callback=store, options={"ftol": 1e-12} all_x_i, all_y_i, all_f_i = optimizer(
) np.array([x_i, y_i]), logging_f, counting_f_prime, hessian=counting_hessian
return all_x_i, all_y_i, all_f_i )

# Plot the contour plot


def nelder_mead(x0, f, f_prime, hessian=None): if not max(all_y_i) < y_max:
all_x_i = [x0[0]] x_min *= 1.2
all_y_i = [x0[1]] x_max *= 1.2
all_f_i = [f(x0)] y_min *= 1.2
y_max *= 1.2
def store(X): x, y = np.mgrid[x_min:x_max:100j, y_min:y_max:100j]
x, y = X x = x.T
all_x_i.append(x) y = y.T
all_y_i.append(y)
(continues on next page) (continues on next page)

13.4. Examples for the mathematical optimization chapter 466 13.4. Examples for the mathematical optimization chapter 467
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


plt.figure(index, figsize=(3, 2.5)) )
plt.clf() plt.tight_layout()
plt.axes([0, 0, 1, 1]) plt.draw()

X = np.concatenate((x[np.newaxis, ...], y[np.newaxis, ...]), axis=0)


z = np.apply_along_axis(f, 0, X)
log_z = np.log(z + 0.01)
plt.imshow(
log_z,
extent=[x_min, x_max, y_min, y_max],
cmap=plt.cm.gray_r,
origin="lower",
vmax=log_z.min() + 1.5 * log_z.ptp(),
)
contours = plt.contour(
log_z,
levels=levels.get(f),
extent=[x_min, x_max, y_min, y_max],
cmap=plt.cm.gnuplot, •
origin="lower",
)
levels[f] = contours.levels
plt.clabel(contours, inline=1, fmt=super_fmt, fontsize=14)

plt.plot(all_x_i, all_y_i, "b-", linewidth=2)


plt.plot(all_x_i, all_y_i, "k+")

plt.plot(logging_f.all_x_i, logging_f.all_y_i, "k.", markersize=2)

plt.plot([0], [0], "rx", markersize=12)

plt.xticks(())
plt.yticks(())
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max) •
plt.draw()

plt.figure(index + 100, figsize=(4, 3))


plt.clf()
plt.semilogy(np.maximum(np.abs(all_f_i), 1e-30), linewidth=2, label="# iterations
˓→")

plt.ylabel("Error on f(x)")
plt.semilogy(
logging_f.counts,
np.maximum(np.abs(logging_f.all_f_i), 1e-30),
linewidth=2,
color="g",
label="# function calls",
)
plt.legend(

loc="upper right",
frameon=True,
prop={"size": 11},
borderaxespad=0,
handlelength=1.5,
handletextpad=0.5,
(continues on next page)

13.4. Examples for the mathematical optimization chapter 468 13.4. Examples for the mathematical optimization chapter 469
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

• •

• •

13.4. Examples for the mathematical optimization chapter 470 13.4. Examples for the mathematical optimization chapter 471
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

• •

• •

13.4. Examples for the mathematical optimization chapter 472 13.4. Examples for the mathematical optimization chapter 473
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

13.4. Examples for the mathematical optimization chapter 474 13.4. Examples for the mathematical optimization chapter 475
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

• •

• •

13.4. Examples for the mathematical optimization chapter 476 13.4. Examples for the mathematical optimization chapter 477
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

• •

• •

13.4. Examples for the mathematical optimization chapter 478 13.4. Examples for the mathematical optimization chapter 479
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

• •

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/scipy/optimize/_
˓→linesearch.py:313: LineSearchWarning: The line search algorithm did not converge

alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2(


/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
˓→mathematical_optimization/examples/plot_gradient_descent.py:69: LineSearchWarning:␣

˓→The line search algorithm did not converge

step = sp.optimize.line_search(
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
˓→mathematical_optimization/examples/plot_gradient_descent.py:233: RuntimeWarning:␣

˓→More than 20 figures have been opened. Figures created through the pyplot interface␣

˓→(`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume␣

˓→too much memory. (To control this warning, see the rcParam `figure.max_open_

˓→warning`). Consider using `matplotlib.pyplot.close()`.

plt.figure(index, figsize=(3, 2.5))


/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
˓→mathematical_optimization/examples/plot_gradient_descent.py:178: OptimizeWarning:␣

˓→Unknown solver options: ftol

• sp.optimize.minimize(

Total running time of the script: (0 minutes 7.792 seconds)

13.4. Examples for the mathematical optimization chapter 480 13.4. Examples for the mathematical optimization chapter 481
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


hess_inv: [[ 9.999e-01 2.000e+00]
[ 2.000e+00 4.499e+00]]
nfev: 10
njev: 10

L-BFGS: Limited-memory BFGS Sits between BFGS and conjugate gradient: in very high dimensions
(> 250) the Hessian matrix is too costly to compute and invert. L-BFGS keeps a low-rank version. In
addition, box bounds are also supported by L-BFGS-B:

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
An ill-conditioned
>>> def jacobian(x):
quadratic function:
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
On a exactly quadratic function,
˓→x[0]**2)))
BFGS is not as fast as Newton’s
>>> sp.optimize.minimize(f, [2, 2], method="L-BFGS-B", jac=jacobian)
method, but still very fast.
message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL
success: True
status: 0
fun: 1.4417677473...e-15
x: [ 1.000e+00 1.000e+00]
nit: 16
jac: [ 1.023e-07 -2.593e-08]
nfev: 17
njev: 17
An ill-conditioned non- hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
quadratic function:
Here BFGS does better than
Newton, as its empirical esti- 13.4.12 Gradient-less methods
mate of the curvature is better
than that given by the Hessian. A shooting method: the Powell algorithm

Almost a gradient approach

An ill-conditioned very non-


quadratic function:

>>> def f(x): # The rosenbrock function


... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def jacobian(x):
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))

>>> sp.optimize.minimize(f, [2, -1], method="BFGS", jac=jacobian)


message: Optimization terminated successfully.
success: True
status: 0
fun: 2.630637192365927e-16
x: [ 1.000e+00 1.000e+00]
nit: 8
jac: [ 6.709e-08 -3.222e-08]
(continues on next page)

13.4. Examples for the mathematical optimization chapter 482 13.4. Examples for the mathematical optimization chapter 483
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

An ill-conditioned An ill-conditioned non-


quadratic function: quadratic function:
Powell’s method isn’t too sensi-
tive to local ill-conditionning in
low dimensions

An ill-conditioned very non-


quadratic function:

An ill-conditioned very non-


Using the Nelder-Mead solver in scipy.optimize.minimize():
quadratic function:
>>> def f(x): # The rosenbrock function
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
Simplex method: the Nelder-Mead >>> sp.optimize.minimize(f, [2, -1], method="Nelder-Mead")
message: Optimization terminated successfully.
The Nelder-Mead algorithms is a generalization of dichotomy approaches to high-dimensional spaces. The success: True
algorithm works by refining a simplex, the generalization of intervals and triangles to high-dimensional status: 0
spaces, to bracket the minimum. fun: 1.11527915993744e-10
x: [ 1.000e+00 1.000e+00]
Strong points: it is robust to noise, as it does not rely on computing gradients. Thus it can work
nit: 58
on functions that are not locally smooth such as experimental data points, as long as they display a
nfev: 111
large-scale bell-shape behavior. However it is slower than gradient-based methods on smooth, non-noisy
final_simplex: (array([[ 1.000e+00, 1.000e+00],
functions.
[ 1.000e+00, 1.000e+00],
[ 1.000e+00, 1.000e+00]]), array([ 1.115e-10, 1.537e-10, 4.
˓→988e-10]))

13.4.13 Global optimizers

If your problem does not admit a unique local minimum (which can be hard to test unless the function
is convex), and you do not have prior information to initialize the optimization close to the solution, you
may need a global optimizer.

13.4. Examples for the mathematical optimization chapter 484 13.4. Examples for the mathematical optimization chapter 485
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Brute force: a grid search 13.5.2 Making your optimizer faster

scipy.optimize.brute() evaluates the function on a given grid of parameters and returns the param- • Choose the right method (see above), do compute analytically the gradient and Hessian, if you
eters corresponding to the minimum value. The parameters are specified with ranges given to numpy. can.
mgrid. By default, 20 steps are taken in each direction:
• Use preconditionning when possible.
>>> def f(x): # The rosenbrock function • Choose your initialization points wisely. For instance, if you are running many similar optimiza-
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 tions, warm-restart one with the results of another.
>>> sp.optimize.brute(f, ((-1, 2), (-1, 2)))
array([1.0000..., 1.0000...]) • Relax the tolerance if you don’t need precision using the parameter tol.

13.5.3 Computing gradients


13.5 Practical guide to optimization with SciPy
Computing gradients, and even more Hessians, is very tedious but worth the effort. Symbolic computa-
tion with Sympy may come in handy.
13.5.1 Choosing a method

All methods are exposed as the method argument of scipy.optimize.minimize(). Warning: A very common source of optimization not converging well is human error in the com-
putation of the gradient. You can use scipy.optimize.check_grad() to check that your gradient
is correct. It returns the norm of the different between the gradient given, and a gradient computed
numerically:
>>> sp.optimize.check_grad(f, jacobian, [2, -1])
2.384185791015625e-07

See also scipy.optimize.approx_fprime() to find your errors.

13.5.4 Synthetic exercices

Without knowledge of the gradient


• In general, prefer BFGS or L-BFGS, even if you have to approximate numerically
gradients. These are also the default if you omit the parameter method - depending
if the problem has constraints or bounds
• On well-conditioned problems, Powell and Nelder-Mead, both gradient-free
methods, work well in high dimension, but they collapse for ill-conditioned problems.
With knowledge of the gradient
Exercice: A simple (?) quadratic function
• BFGS or L-BFGS.
• Computational overhead of BFGS is larger than that L-BFGS, itself larger than Optimize the following function, using K[0] as a starting point:
that of conjugate gradient. On the other side, BFGS usually needs less function rng = np.random.default_rng(27446968)
evaluations than CG. Thus conjugate gradient method is better than BFGS at K = rng.normal(size=(100, 100))
optimizing computationally cheap functions.
With the Hessian def f(x):
return np.sum((K @ (x - 1))**2) + np.sum(x**2)**2
• If you can compute the Hessian, prefer the Newton method (Newton-CG or TCG).
Time your approach. Find the fastest approach. Why is BFGS not working well?
If you have noisy measurements
• Use Nelder-Mead or Powell.
Exercice: A locally flat minimum

13.5. Practical guide to optimization with SciPy 486 13.5. Practical guide to optimization with SciPy 487
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Consider the function exp(-1/(.1*x**2 + y**2). This function admits a minimum in (0, 0). Starting (continued from previous page)
from an initialization at (1, 1), try to get within 1e-8 of this minimum point. >>> result.fun
2.6940...e-11

BFGS needs more function calls, and gives a less precise result.

Note: leastsq is interesting compared to BFGS only if the dimensionality of the output vector is large,
and larger than the number of parameters to optimize.

Warning: If the function is linear, this is a linear-algebra problem, and should be solved with
scipy.linalg.lstsq().

13.6.2 Curve fitting

Least square problems occur often when fitting a non-linear to data. While it is possible to construct our
13.6 Special case: non-linear least-squares optimization problem ourselves, SciPy provides a helper function for this purpose: scipy.optimize.
curve_fit():
13.6.1 Minimizing the norm of a vector function >>> def f(t, omega, phi):
... return np.cos(omega * t + phi)
Least square problems, minimizing the norm of a vector function, have a specific structure that can be
used in the Levenberg–Marquardt algorithm implemented in scipy.optimize.leastsq(). >>> x = np.linspace(0, 3, 50)
>>> rng = np.random.default_rng(27446968)
Lets try to minimize the norm of the following vectorial function:
>>> y = f(x, 1.5, 1) + .1*rng.normal(size=50)
>>> def f(x):
... return np.arctan(x) - np.arctan(np.linspace(0, 1, len(x))) >>> sp.optimize.curve_fit(f, x, y)
(array([1.4812..., 0.9999...]), array([[ 0.0003..., -0.0004...],
>>> x0 = np.zeros(10) [-0.0004..., 0.0010...]]))
>>> sp.optimize.leastsq(f, x0)
(array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ]), 2) Exercise

This took 67 function evaluations (check it with ‘full_output=1’). What if we compute the norm Do the same with omega = 3. What is the difficulty?
ourselves and use a good generic optimizer (BFGS):

>>> def g(x):


... return np.sum(f(x)**2)
>>> result = sp.optimize.minimize(g, x0, method="BFGS")
(continues on next page)

13.6. Special case: non-linear least-squares 488 13.6. Special case: non-linear least-squares 489
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

13.7 Optimization with constraints (continued from previous page)

>>> def constraint(x):


13.7.1 Box bounds ... return np.atleast_1d(1.5 - np.sum(np.abs(x)))

Box bounds correspond to limiting each of the individual parameters of the optimization. Note that >>> x0 = np.array([0, 0])
some problems that are not originally written as box bounds can be rewritten as such via change of vari- >>> sp.optimize.minimize(f, x0, constraints={"fun": constraint, "type": "ineq"})
ables. Both scipy.optimize.minimize_scalar() and scipy.optimize.minimize() support bound message: Optimization terminated successfully
constraints with the parameter bounds: success: True
status: 0
>>> def f(x):
fun: 2.47487373504...
... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2)
x: [ 1.250e+00 2.500e-01]
>>> sp.optimize.minimize(f, np.array([0, 0]), bounds=((-1.5, 1.5), (-1.5, 1.5)))
nit: 5
message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL
jac: [-7.071e-01 -7.071e-01]
success: True
nfev: 15
status: 0
njev: 5
fun: 1.5811388300841898
x: [ 1.500e+00 1.500e+00]
nit: 2
jac: [-9.487e-01 -3.162e-01] Warning: The above problem is known as the Lasso problem in statistics, and there exist very
nfev: 9 efficient solvers for it (for instance in scikit-learn). In general do not use generic solvers when specific
njev: 3 ones exist.
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>

Lagrange multipliers

If you are ready to do a bit of math, many constrained optimization problems can be converted to
non-constrained optimization problems using a mathematical trick known as Lagrange multipliers.

13.8 Full code examples

13.9 Examples for the mathematical optimization chapter

See also:
13.7.2 General constraints
Other Software
Equality and inequality constraints specified as functions: 𝑓 (𝑥) = 0 and 𝑔(𝑥) < 0. SciPy tries to include the best well-established, general-use, and permissively-licensed optimization al-
gorithms available. However, even better options for a given task may be available in other libraries;
• scipy.optimize.fmin_slsqp() Sequential least square programming: equality and inequality con-
please also see IPOPT and PyGMO.
straints:

>>> def f(x):


... return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2)
(continues on next page)

13.7. Optimization with constraints 490 13.8. Full code examples 491
Scientific Python Lectures, Edition 2024.2rc0.dev0

14.1 Introduction

This chapter covers the following techniques:


• Python-C-Api
• Ctypes
• SWIG (Simplified Wrapper and Interface Generator)

CHAPTER 14 • Cython
These four techniques are perhaps the most well known ones, of which Cython is probably the most
advanced one and the one you should consider using first. The others are also important, if you want to
understand the wrapping problem from different angles. Having said that, there are other alternatives
out there, but having understood the basics of the ones above, you will be in a position to evaluate the
technique of your choice to see if it fits your needs.
The following criteria may be useful when evaluating a technology:
• Are additional libraries required?
• Is the code autogenerated?
• Does it need to be compiled?
Interfacing with C • Is there good support for interacting with NumPy arrays?
• Does it support C++?
Before you set out, you should consider your use case. When interfacing with native code, there are
usually two use-cases that come up:
• Existing code in C/C++ that needs to be leveraged, either because it already exists, or because it
is faster.
Author: Valentin Haenel
• Python code too slow, push inner loops to native code
This chapter contains an introduction to the many different routes for making your native code (primarily
C/C++) available from Python, a process commonly referred to wrapping. The goal of this chapter is to Each technology is demonstrated by wrapping the cos function from math.h. While this is a mostly a
give you a flavour of what technologies exist and what their respective merits and shortcomings are, so trivial example, it should serve us well to demonstrate the basics of the wrapping solution. Since each
that you can select the appropriate one for your specific needs. In any case, once you do start wrapping, technique also includes some form of NumPy support, this is also demonstrated using an example where
you almost certainly will want to consult the respective documentation for your selected technique. the cosine is computed on some kind of array.
Last but not least, two small warnings:
Chapters contents • All of these techniques may crash (segmentation fault) the Python interpreter, which is (usually)
due to bugs in the C code.
• Introduction
• All the examples have been done on Linux, they should be possible on other operating systems.
• Python-C-Api
• You will need a C compiler for most of the examples.
• Ctypes
• SWIG
• Cython
14.2 Python-C-Api
• Summary
The Python-C-API is the backbone of the standard Python interpreter (a.k.a CPython). Using this API
• Further Reading and References it is possible to write Python extension module in C and C++. Obviously, these extension modules can,
by virtue of language compatibility, call any function written in C or C++.
• Exercises
When using the Python-C-API, one usually writes much boilerplate code, first to parse the arguments
that were given to a function, and later to construct the return type.
Advantages
• Requires no additional libraries
• Lots of low-level control
• Entirely usable from C++

492 14.1. Introduction 493


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Disadvantages (continued from previous page)

• May require a substantial amount of effort {NULL, NULL, 0, NULL}


};
• Much overhead in the code
• Must be compiled # if PY_MAJOR_VERSION >= 3
/* module initialization */
• High maintenance cost /* Python version 3*/
• No forward compatibility across Python versions as C-API changes static struct PyModuleDef cModPyDem =
{
• Reference count bugs are easy to create and very hard to track down. PyModuleDef_HEAD_INIT,
"cos_module", "Some documentation",
Note: The Python-C-Api example here serves mainly for didactic reasons. Many of the other techniques -1,
actually depend on this, so it is good to have a high-level understanding of how it works. In 99% of the CosMethods
use-cases you will be better off, using an alternative technique. };

PyMODINIT_FUNC
PyInit_cos_module(void)
Note: Since reference counting bugs are easy to create and hard to track down, anyone really needing {
to use the Python C-API should read the section about objects, types and reference counts from the return PyModule_Create(&cModPyDem);
official python documentation. Additionally, there is a tool by the name of cpychecker which can help }
discover common errors with reference counting.
# else

/* module initialization */
14.2.1 Example /* Python version 2 */
PyMODINIT_FUNC
The following C-extension module, make the cos function from the standard math library available to initcos_module(void)
Python: {
/* Example of wrapping cos function from math.h with the Python-C-API. */ (void) Py_InitModule("cos_module", CosMethods);
}
# include <Python.h>
# include <math.h> # endif

/* wrapped cosine function */ As you can see, there is much boilerplate, both to «massage» the arguments and return types into
static PyObject* cos_func(PyObject* self, PyObject* args) place and for the module initialisation. Although some of this is amortised, as the extension grows, the
{ boilerplate required for each function(s) remains.
double value; The standard python build system distutils supports compiling C-extensions from a setup.py, which
double answer; is rather convenient:

/* parse the input, from python float to c double */ from distutils.core import setup, Extension
if (!PyArg_ParseTuple(args, "d", &value))
return NULL; # define the extension module
/* if the above function returns -1, an appropriate Python exception will cos_module = Extension("cos_module", sources=["cos_module.c"])
* have been set, and the function simply returns NULL
*/ # run the setup
setup(ext_modules=[cos_module])
/* call cos from libm */
answer = cos(value); This can be compiled:

/* construct the output from cos, from c double to python float */ $ cd advanced/interfacing_with_c/python_c_api
return Py_BuildValue("f", answer);
} $ ls
cos_module.c setup.py
/* define functions in module */
static PyMethodDef CosMethods[] = $ python setup.py build_ext --inplace
{ running build_ext
{"cos_func", cos_func, METH_VARARGS, "evaluate the cosine"}, building 'cos_module' extension
(continues on next page) (continues on next page)

14.2. Python-C-Api 494 14.2. Python-C-Api 495


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 14.2.2 NumPy Support


creating build
creating build/temp.linux-x86_64-2.7 Analog to the Python-C-API, NumPy, which is itself implemented as a C-extension, comes with the
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict- NumPy-C-API. This API can be used to create and manipulate NumPy arrays from C, when writing a
˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/ custom C-extension. See also: Advanced NumPy.
˓→temp.linux-x86_64-2.7/cos_module.o

gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/ Note: If you do ever need to use the NumPy C-API refer to the documentation about Arrays and
˓→lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/
Iterators.
˓→interfacing_with_c/python_c_api/cos_module.so

$ ls The following example shows how to pass NumPy arrays as arguments to functions and how to iterate
build/ cos_module.c cos_module.so setup.py over NumPy arrays using the (old) NumPy-C-API. It simply takes an array as argument applies the
cosine function from the math.h and returns a resulting new array.
• build_ext is to build extension modules
/* Example of wrapping the cos function from math.h using the NumPy-C-API. */
• --inplace will output the compiled extension module into the current directory
# include <Python.h>
The file cos_module.so contains the compiled extension, which we can now load in the IPython inter-
# include <numpy/arrayobject.h>
preter:
# include <math.h>

Note: In Python 3, the filename for compiled modules includes metadata on the Python interpreter
(see PEP 3149) and is thus longer. The import statement is not affected by this. /* wrapped cosine function */
static PyObject* cos_func_np(PyObject* self, PyObject* args)
{
In [1]: import cos_module PyArrayObject *arrays[2]; /* holds input and output array */
PyObject *ret;
In [2]: cos_module? NpyIter *iter;
Type: module npy_uint32 op_flags[2];
String Form:<module 'cos_module' from 'cos_module.so'> npy_uint32 iterator_flags;
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_ PyArray_Descr *op_dtypes[2];
˓→with_c/python_c_api/cos_module.so

Docstring: <no docstring> NpyIter_IterNextFunc *iternext;

In [3]: dir(cos_module) /* parse single NumPy array argument */


Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func'] if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &arrays[0])) {
return NULL;
In [4]: cos_module.cos_func(1.0) }
Out[4]: 0.5403023058681398
arrays[1] = NULL; /* The result will be allocated by the iterator */
In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0 /* Set up and create the iterator */
iterator_flags = (NPY_ITER_ZEROSIZE_OK |
In [6]: cos_module.cos_func(3.14159265359) /*
Out[6]: -1.0 * Enable buffering in case the input is not behaved
* (native byte order or not aligned),
Now let’s see how robust this is: * disabling may speed up some cases when it is known to
* be unnecessary.
In [7]: cos_module.cos_func('foo')
*/
---------------------------------------------------------------------------
NPY_ITER_BUFFERED |
TypeError Traceback (most recent call last)
/* Manually handle innermost iteration for speed: */
<ipython-input-10-11bee483665d> in <module>()
NPY_ITER_EXTERNAL_LOOP |
----> 1 cos_module.cos_func('foo')
NPY_ITER_GROWINNER);
TypeError: a float is required
op_flags[0] = (NPY_ITER_READONLY |
/*
* Required that the arrays are well behaved, since the cos
* call below requires this.
(continues on next page)

14.2. Python-C-Api 496 14.2. Python-C-Api 497


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


*/ double *out = (double *)dataptr[1];
NPY_ITER_NBO | char *in = dataptr[0];
NPY_ITER_ALIGNED);
/* The output is allocated and guaranteed contiguous (out++ works): */
/* Ask the iterator to allocate an array to write the output to */ assert(strideptr[1] == sizeof(double));
op_flags[1] = NPY_ITER_WRITEONLY | NPY_ITER_ALLOCATE;
/*
/* * For optimization it can make sense to add a check for
* Ensure the iteration has the correct type, could be checked * stride == sizeof(double) to allow the compiler to optimize for that.
* specifically here. */
*/ while (count--) {
op_dtypes[0] = PyArray_DescrFromType(NPY_DOUBLE); *out = cos(*(double *)in);
op_dtypes[1] = op_dtypes[0]; out++;
in += stride;
/* Create the NumPy iterator object: */ }
iter = NpyIter_MultiNew(2, arrays, iterator_flags, } while (iternext(iter));
/* Use input order for output and iteration */
NPY_KEEPORDER, /* Clean up and return the result */
/* Allow only byte-swapping of input */ NpyIter_Deallocate(iter);
NPY_EQUIV_CASTING, op_flags, op_dtypes); return ret;
Py_DECREF(op_dtypes[0]); /* The second one is identical. */ }

if (iter == NULL)
return NULL; /* define functions in module */
static PyMethodDef CosMethods[] =
iternext = NpyIter_GetIterNext(iter, NULL); {
if (iternext == NULL) { {"cos_func_np", cos_func_np, METH_VARARGS,
NpyIter_Deallocate(iter); "evaluate the cosine on a NumPy array"},
return NULL; {NULL, NULL, 0, NULL}
} };

/* Fetch the output array which was allocated by the iterator: */


ret = (PyObject *)NpyIter_GetOperandArray(iter)[1]; # if PY_MAJOR_VERSION >= 3
Py_INCREF(ret); /* module initialization */
/* Python version 3*/
if (NpyIter_GetIterSize(iter) == 0) { static struct PyModuleDef cModPyDem = {
/* PyModuleDef_HEAD_INIT,
* If there are no elements, the loop cannot be iterated. "cos_module", "Some documentation",
* This check is necessary with NPY_ITER_ZEROSIZE_OK. -1,
*/ CosMethods
NpyIter_Deallocate(iter); };
return ret; PyMODINIT_FUNC PyInit_cos_module_np(void) {
} PyObject *module;
module = PyModule_Create(&cModPyDem);
/* The location of the data pointer which the iterator may update */ if(module==NULL) return NULL;
char **dataptr = NpyIter_GetDataPtrArray(iter); /* IMPORTANT: this must be called */
/* The location of the stride which the iterator may update */ import_array();
npy_intp *strideptr = NpyIter_GetInnerStrideArray(iter); if (PyErr_Occurred()) return NULL;
/* The location of the inner loop size which the iterator may update */ return module;
npy_intp *innersizeptr = NpyIter_GetInnerLoopSizePtr(iter); }

/* iterate over the arrays */ # else


do { /* module initialization */
npy_intp stride = strideptr[0]; /* Python version 2 */
npy_intp count = *innersizeptr; PyMODINIT_FUNC initcos_module_np(void) {
/* out is always contiguous, so use double */ PyObject *module;
(continues on next page) (continues on next page)

14.2. Python-C-Api 498 14.2. Python-C-Api 499


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


module = Py_InitModule("cos_module_np", CosMethods); # The function fails if the data type is incorrect:
if(module==NULL) return; x_incorrect_dtype = x.astype(np.float32)
/* IMPORTANT: this must be called */ try:
import_array(); cos_module_np.cos_func_np(x_incorrect_dtype)
return; assert 0, "This cannot be reached."
} except TypeError:
# A TypeError will be raised, this can be changed by changing the
# endif # casting rule.
pass
To compile this we can use distutils again. However we need to be sure to include the NumPy headers
by using numpy.get_include(). And this should result in the following figure:

from distutils.core import setup, Extension


import numpy

# define the extension module


cos_module_np = Extension(
"cos_module_np", sources=["cos_module_np.c"], include_dirs=[numpy.get_include()]
)

# run the setup


setup(ext_modules=[cos_module_np])

To convince ourselves if this does actually works, we run the following test script:

import cos_module_np
import numpy as np 14.3 Ctypes
import matplotlib.pyplot as plt
Ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling
x = np.arange(0, 2 * np.pi, 0.1) functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
y = cos_module_np.cos_func_np(x)
plt.plot(x, y) Advantages
plt.show() • Part of the Python standard library
• Does not need to be compiled
# Below are more specific tests for less common usage • Wrapping code entirely in Python
# ---------------------------------------------------
Disadvantages
# The function is OK with `x` not having any elements: • Requires code to be wrapped to be available as a shared library (roughly speaking *.dll in Windows
x_empty = np.array([], dtype=np.float64) *.so in Linux and *.dylib in Mac OSX.)
y_empty = cos_module_np.cos_func_np(x_empty)
assert np.array_equal(y_empty, np.array([], dtype=np.float64)) • No good support for C++

# The function can handle arbitrary dimensions and non-contiguous data.


14.3.1 Example
# `x_2d` contains the same values, but has a different shape.
# Note: `x_2d.flags` shows it is not contiguous and `x2.ravel() == x`
As advertised, the wrapper code is in pure Python.
x_2d = x.repeat(2)[::2].reshape(-1, 3)
y_2d = cos_module_np.cos_func_np(x_2d) """Example of wrapping cos function from math.h using ctypes."""
# When reshaped back, the same result is given:
assert np.array_equal(y_2d.ravel(), y) import ctypes

# The function handles incorrect byte-order fine: # find and load the library
x_not_native_byteorder = x.astype(x.dtype.newbyteorder())
y_not_native_byteorder = cos_module_np.cos_func_np(x_not_native_byteorder) # OSX or linux
assert np.array_equal(y_not_native_byteorder, y) from ctypes.util import find_library

(continues on next page) (continues on next page)

14.2. Python-C-Api 500 14.3. Ctypes 501


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


In [14]: cos_module.cos_func('foo')
libm = ctypes.cdll.LoadLibrary(find_library("m")) ---------------------------------------------------------------------------
ArgumentError Traceback (most recent call last)
# Windows <ipython-input-7-11bee483665d> in <module>()
# from ctypes import windll ----> 1 cos_module.cos_func('foo')
# libm = cdll.msvcrt /home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/ctypes/
˓→cos_module.py in cos_func(arg)

12 def cos_func(arg):
# set the argument type 13 ''' Wrapper for cos from math.h '''
libm.cos.argtypes = [ctypes.c_double] ---> 14 return libm.cos(arg)
# set the return type ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type
libm.cos.restype = ctypes.c_double

def cos_func(arg): 14.3.2 NumPy Support


"""Wrapper for cos from math.h"""
return libm.cos(arg) NumPy contains some support for interfacing with ctypes. In particular there is support for exporting
certain attributes of a NumPy array as ctypes data-types and there are functions to convert from C
• Finding and loading the library may vary depending on your operating system, check the docu- arrays to NumPy arrays and back.
mentation for details For more information, consult the corresponding section in the NumPy Cookbook and the API docu-
• This may be somewhat deceptive, since the math library exists in compiled form on the system mentation for numpy.ndarray.ctypes and numpy.ctypeslib.
already. If you were to wrap a in-house library, you would have to compile it first, which may or For the following example, let’s consider a C function in a library that takes an input and an output
may not require some additional effort. array, computes the cosine of the input array and stores the result in the output array.
We may now use this, as before: The library consists of the following header file (although this is not strictly needed for this example, we
list it for completeness):
In [8]: import cos_module
void cos_doubles(double * in_array, double * out_array, int size);
In [9]: cos_module?
Type: module The function implementation resides in the following C source file:
String Form:<module 'cos_module' from 'cos_module.py'>
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_ # include <math.h>
˓→with_c/ctypes/cos_module.py

Docstring: <no docstring> /* Compute the cosine of each element in in_array, storing the result in
* out_array. */
In [10]: dir(cos_module) void cos_doubles(double * in_array, double * out_array, int size){
Out[10]: int i;
['__builtins__', for(i=0;i<size;i++){
'__doc__', out_array[i] = cos(in_array[i]);
'__file__', }
'__name__', }
'__package__',
'cos_func', And since the library is pure C, we can’t use distutils to compile it, but must use a combination of
'ctypes', make and gcc:
'find_library',
'libm'] m.PHONY : clean

In [11]: cos_module.cos_func(1.0) libcos_doubles.so : cos_doubles.o


Out[11]: 0.5403023058681398 gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o

In [12]: cos_module.cos_func(0.0) cos_doubles.o : cos_doubles.c


Out[12]: 1.0 gcc -c -fPIC cos_doubles.c -o cos_doubles.o

In [13]: cos_module.cos_func(3.14159265359) clean :


Out[13]: -1.0 -rm -vf libcos_doubles.so cos_doubles.o cos_doubles.pyc

As with the previous example, this code is somewhat robust, although the error message is not quite as We can then compile this (on Linux) into the shared library libcos_doubles.so:
helpful, since it does not tell us what the type should be.

14.3. Ctypes 502 14.3. Ctypes 503


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

$ ls
cos_doubles.c cos_doubles.h cos_doubles.py makefile test_cos_doubles.py
$ make
gcc -c -fPIC cos_doubles.c -o cos_doubles.o
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o
$ ls
cos_doubles.c cos_doubles.o libcos_doubles.so* test_cos_doubles.py
cos_doubles.h cos_doubles.py makefile

Now we can proceed to wrap this library via ctypes with direct support for (certain kinds of) NumPy
arrays:

"""Example of wrapping a C library function that accepts a C double array as


input using the numpy.ctypeslib.""" 14.4 SWIG
import numpy as np
import numpy.ctypeslib as npct SWIG, the Simplified Wrapper Interface Generator, is a software development tool that connects pro-
from ctypes import c_int grams written in C and C++ with a variety of high-level programming languages, including Python.
The important thing with SWIG is, that it can autogenerate the wrapper code for you. While this is an
# input type for the cos_doubles function advantage in terms of development time, it can also be a burden. The generated file tend to be quite
# must be a double array, with single dimension that is contiguous large and may not be too human readable and the multiple levels of indirection which are a result of the
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags="CONTIGUOUS") wrapping process, may be a bit tricky to understand.

# load the library, using NumPy mechanisms Note: The autogenerated C code uses the Python-C-Api.
libcd = npct.load_library("libcos_doubles", ".")

# setup the return types and argument types Advantages


libcd.cos_doubles.restype = None • Can automatically wrap entire libraries given the headers
libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int]
• Works nicely with C++
Disadvantages
def cos_doubles_func(in_array, out_array):
return libcd.cos_doubles(in_array, out_array, len(in_array)) • Autogenerates enormous files
• Hard to debug if something goes wrong
• Note the inherent limitation of contiguous single dimensional NumPy arrays, since the C functions
requires this kind of buffer. • Steep learning curve

• Also note that the output array must be preallocated, for example with numpy.zeros() and the
function will write into it’s buffer. 14.4.1 Example
• Although the original signature of the cos_doubles function is ARRAY, ARRAY, int the final
cos_doubles_func takes only two NumPy arrays as arguments. Let’s imagine that our cos function lives in a cos_module which has been written in c and consists of
the source file cos_module.c:
And, as before, we convince ourselves that it worked:
# include <math.h>
import numpy as np
import matplotlib.pyplot as plt double cos_func(double arg){
import cos_doubles return cos(arg);
}
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x) and the header file cos_module.h:

cos_doubles.cos_doubles_func(x, y) double cos_func(double arg);


plt.plot(x, y)
plt.show() And our goal is to expose the cos_func to Python. To achieve this with SWIG, we must write an
interface file which contains the instructions for SWIG.

14.3. Ctypes 504 14.4. SWIG 505


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

/* Example of wrapping cos function from math.h using SWIG. */ In [15]: import cos_module

%module cos_module In [16]: cos_module?


%{ Type: module
/* the resulting C file should be built as a python extension */ String Form:<module 'cos_module' from 'cos_module.py'>
# define SWIG_FILE_WITH_INIT File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_
/* Includes the header in the wrapper code */ ˓→with_c/swig/cos_module.py

# include "cos_module.h" Docstring: <no docstring>


%}
/* Parse the header file to generate wrappers */ In [17]: dir(cos_module)
%include "cos_module.h" Out[17]:
['__builtins__',
As you can see, not too much code is needed here. For this simple example it is enough to simply include '__doc__',
the header file in the interface file, to expose the function to Python. However, SWIG does allow for '__file__',
more fine grained inclusion/exclusion of functions found in header files, check the documentation for '__name__',
details. '__package__',
'_cos_module',
Generating the compiled wrappers is a two stage process: '_newclass',
1. Run the swig executable on the interface file to generate the files cos_module_wrap.c, which '_object',
is the source file for the autogenerated Python C-extension and cos_module.py, which is the '_swig_getattr',
autogenerated pure python module. '_swig_property',
'_swig_repr',
2. Compile the cos_module_wrap.c into the _cos_module.so. Luckily, distutils knows how to '_swig_setattr',
handle SWIG interface files, so that our setup.py is simply: '_swig_setattr_nondynamic',
from distutils.core import setup, Extension 'cos_func']

setup(ext_modules=[Extension("_cos_module", sources=["cos_module.c", "cos_module.i In [18]: cos_module.cos_func(1.0)


˓→"])])
Out[18]: 0.5403023058681398

In [19]: cos_module.cos_func(0.0)
$ cd advanced/interfacing_with_c/swig Out[19]: 1.0
$ ls In [20]: cos_module.cos_func(3.14159265359)
cos_module.c cos_module.h cos_module.i setup.py Out[20]: -1.0
$ python setup.py build_ext --inplace
Again we test for robustness, and we see that we get a better error message (although, strictly speaking
running build_ext
in Python there is no double type):
building '_cos_module' extension
swigging cos_module.i to cos_module_wrap.c In [21]: cos_module.cos_func('foo')
swig -python -o cos_module_wrap.c cos_module.i ---------------------------------------------------------------------------
creating build TypeError Traceback (most recent call last)
creating build/temp.linux-x86_64-2.7 <ipython-input-7-11bee483665d> in <module>()
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict- ----> 1 cos_module.cos_func('foo')
˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/ TypeError: in method 'cos_func', argument 1 of type 'double'
˓→temp.linux-x86_64-2.7/cos_module.o

gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-


˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module_wrap.c -o␣

˓→build/temp.linux-x86_64-2.7/cos_module_wrap.o
14.4.2 NumPy Support
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o build/temp.linux-x86_64-
˓→2.7/cos_module_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/
NumPy provides support for SWIG with the numpy.i file. This interface file defines various so-called
˓→scientific-python-lectures/advanced/interfacing_with_c/swig/_cos_module.so
typemaps which support conversion between NumPy arrays and C-Arrays. In the following example we
will take a quick look at how such typemaps work in practice.
$ ls We have the same cos_doubles function as in the ctypes example:
build/ cos_module.c cos_module.h cos_module.i cos_module.py _cos_module.so* cos_
˓→module_wrap.c setup.py void cos_doubles(double * in_array, double * out_array, int size);

We can now load and execute the cos_module as we have done in the previous examples:

14.4. SWIG 506 14.4. SWIG 507


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

# include <math.h> from distutils.core import setup, Extension


import numpy
/* Compute the cosine of each element in in_array, storing the result in
* out_array. */ setup(
void cos_doubles(double * in_array, double * out_array, int size){ ext_modules=[
int i; Extension(
for(i=0;i<size;i++){ "_cos_doubles",
out_array[i] = cos(in_array[i]); sources=["cos_doubles.c", "cos_doubles.i"],
} include_dirs=[numpy.get_include()],
} )
]
This is wrapped as cos_doubles_func using the following SWIG interface file: )

/* Example of wrapping a C function that takes a C double array as input using As previously, we need to use include_dirs to specify the location.
* NumPy typemaps for SWIG. */
$ ls
%module cos_doubles cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py
%{ $ python setup.py build_ext -i
/* the resulting C file should be built as a python extension */ running build_ext
# define SWIG_FILE_WITH_INIT building '_cos_doubles' extension
/* Includes the header in the wrapper code */ swigging cos_doubles.i to cos_doubles_wrap.c
# include "cos_doubles.h" swig -python -o cos_doubles_wrap.c cos_doubles.i
%} cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
/* include the NumPy typemaps */ cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
%include "numpy.i" creating build
/* need this for correct module initialization */ creating build/temp.linux-x86_64-2.7
%init %{ gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
import_array(); ˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

%} ˓→include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-

˓→x86_64-2.7/cos_doubles.o

/* typemaps for the two arrays, the second will be modified in-place */ gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)} ˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)} ˓→include -I/home/esc/anaconda/include/python2.7 -c cos_doubles_wrap.c -o build/temp.

˓→linux-x86_64-2.7/cos_doubles_wrap.o

/* Wrapper for cos_doubles that massages the types */ In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
%inline %{ ˓→include/numpy/ndarraytypes.h:1722,

/* takes as input two NumPy arrays */ from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/


void cos_doubles_func(double * in_array, int size_in, double * out_array, int␣ ˓→include/numpy/ndarrayobject.h:17,

˓→size_out) { from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/


/* calls the original function, providing only the size of the first */ ˓→include/numpy/arrayobject.h:15,

cos_doubles(in_array, out_array, size_in); from cos_doubles_wrap.c:2706:


} /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_
%} ˓→deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by

˓→#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"

• To use the NumPy typemaps, we need include the numpy.i file. gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_doubles.o build/temp.linux-x86_
˓→64-2.7/cos_doubles_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-
• Observe the call to import_array() which we encountered already in the NumPy-C-API example. ˓→working/scientific-python-lectures/advanced/interfacing_with_c/swig_numpy/_cos_

• Since the type maps only support the signature ARRAY, SIZE we need to wrap the cos_doubles ˓→doubles.so

as cos_doubles_func which takes two arrays including sizes as input. $ ls


build/ cos_doubles.h cos_doubles.py cos_doubles_wrap.c setup.py
• As opposed to the simple SWIG example, we don’t include the cos_doubles.h header, There cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i test_cos_doubles.
is nothing there that we wish to expose to Python since we expose the functionality through ˓→py
cos_doubles_func.
And, as before we can use distutils to wrap this: And, as before, we convince ourselves that it worked:

import numpy as np
(continues on next page)

14.4. SWIG 508 14.4. SWIG 509


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 14.5.1 Example


import matplotlib.pyplot as plt
import cos_doubles The main Cython code for our cos_module is contained in the file cos_module.pyx:
""" Example of wrapping cos function from math.h using Cython. """
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x)
cdef extern from "math.h":
double cos(double arg)
cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y)
def cos_func(arg):
plt.show()
return cos(arg)

Note the additional keywords such as cdef and extern. Also the cos_func is then pure Python.
Again we can use the standard distutils module, but this time we need some additional pieces from
the Cython.Distutils:
from distutils.core import setup, Extension
from Cython.Distutils import build_ext

setup(
cmdclass={"build_ext": build_ext},
ext_modules=[Extension("cos_module", ["cos_module.pyx"])],
)

Compiling this:
14.5 Cython
$ cd advanced/interfacing_with_c/cython
$ ls
Cython is both a Python-like language for writing C-extensions and an advanced compiler for this cos_module.pyx setup.py
language. The Cython language is a superset of Python, which comes with additional constructs that $ python setup.py build_ext --inplace
allow you call C functions and annotate variables and class attributes with c types. In this sense one running build_ext
could also call it a Python with types. cythoning cos_module.pyx to cos_module.c
In addition to the basic use case of wrapping native code, Cython supports an additional use-case, building 'cos_module' extension
namely interactive optimization. Basically, one starts out with a pure-Python script and incrementally creating build
adds Cython types to the bottleneck code to optimize only those code paths that really matter. creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
In this sense it is quite similar to SWIG, since the code can be autogenerated but in a sense it also quite ˓→prototypes -fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/
similar to ctypes since the wrapping code can (almost) be written in Python. ˓→temp.linux-x86_64-2.7/cos_module.o

While others solutions that autogenerate code can be quite difficult to debug (for example SWIG) Cython gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/
comes with an extension to the GNU debugger that helps debug Python, Cython and C code. ˓→lib -lpython2.7 -o /home/esc/git-working/scientific-python-lectures/advanced/

˓→interfacing_with_c/cython/cos_module.so

$ ls
Note: The autogenerated C code uses the Python-C-Api. build/ cos_module.c cos_module.pyx cos_module.so* setup.py

Advantages And running it:


• Python like language for writing C-extensions In [22]: import cos_module
• Autogenerated code
In [23]: cos_module?
• Supports incremental optimization Type: module
• Includes a GNU debugger extension String Form:<module 'cos_module' from 'cos_module.so'>
File: /home/esc/git-working/scientific-python-lectures/advanced/interfacing_
• Support for C++ (Since version 0.13) ˓→with_c/cython/cos_module.so

Disadvantages Docstring: <no docstring>

• Must be compiled In [24]: dir(cos_module)


• Requires an additional library ( but only at build time, at this problem can be overcome by shipping Out[24]:
the generated C files) ['__builtins__',
(continues on next page)

14.5. Cython 510 14.5. Cython 511


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


'__doc__', void cos_doubles(double * in_array, double * out_array, int size){
'__file__', int i;
'__name__', for(i=0;i<size;i++){
'__package__', out_array[i] = cos(in_array[i]);
'__test__', }
'cos_func'] }

In [25]: cos_module.cos_func(1.0) This is wrapped as cos_doubles_func using the following Cython code:
Out[25]: 0.5403023058681398
""" Example of wrapping a C function that takes C double arrays as input using
In [26]: cos_module.cos_func(0.0) the NumPy declarations from Cython """
Out[26]: 1.0
# cimport the Cython declarations for NumPy
In [27]: cos_module.cos_func(3.14159265359) cimport numpy as np
Out[27]: -1.0
# if you want to use the NumPy-C-API from Cython
And, testing a little for robustness, we can see that we get good error messages: # (not strictly necessary for this example, but good practice)
np.import_array()
In [28]: cos_module.cos_func('foo')
--------------------------------------------------------------------------- # cdefine the signature of our c function
TypeError Traceback (most recent call last) cdef extern from "cos_doubles.h":
<ipython-input-7-11bee483665d> in <module>() void cos_doubles (double * in_array, double * out_array, int size)
----> 1 cos_module.cos_func('foo')
/home/esc/git-working/scientific-python-lectures/advanced/interfacing_with_c/cython/ # create the wrapper code, with NumPy type annotations
˓→cos_module.so in cos_module.cos_func (cos_module.c:506)() def cos_doubles_func(np.ndarray[double, ndim=1, mode="c"] in_array not None,
TypeError: a float is required np.ndarray[double, ndim=1, mode="c"] out_array not None):
cos_doubles(<double*> np.PyArray_DATA(in_array),
Additionally, it is worth noting that Cython ships with complete declarations for the C math library, <double*> np.PyArray_DATA(out_array),
which simplifies the code above to become: in_array.shape[0])

""" Simpler example of wrapping cos function from math.h using Cython. """ And can be compiled using distutils:

from libc.math cimport cos from distutils.core import setup, Extension


import numpy
def cos_func(arg): from Cython.Distutils import build_ext
return cos(arg)
setup(
In this case the cimport statement is used to import the cos function. cmdclass={"build_ext": build_ext},
ext_modules=[
Extension(
14.5.2 NumPy Support "cos_doubles",
sources=["_cos_doubles.pyx", "cos_doubles.c"],
Cython has support for NumPy via the numpy.pyx file which allows you to add the NumPy array type include_dirs=[numpy.get_include()],
to your Cython code. I.e. like specifying that variable i is of type int, you can specify that variable a )
is of type numpy.ndarray with a given dtype. Also, certain optimizations such as bounds checking are ],
supported. Look at the corresponding section in the Cython documentation. In case you want to pass )
NumPy arrays as C arrays to your Cython wrapped C functions, there is a section about this in the
Cython documentation. • As with the previous compiled NumPy examples, we need the include_dirs option.
In the following example, we will show how to wrap the familiar cos_doubles function using Cython. $ ls
cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py
void cos_doubles(double * in_array, double * out_array, int size);
$ python setup.py build_ext -i
running build_ext
# include <math.h> cythoning _cos_doubles.pyx to _cos_doubles.c
building 'cos_doubles' extension
/* Compute the cosine of each element in in_array, storing the result in creating build
* out_array. */ creating build/temp.linux-x86_64-2.7
(continues on next page) (continues on next page)

14.5. Cython 512 14.5. Cython 513


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 14.6 Summary


gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
In this section four different techniques for interfacing with native code have been presented. The table
˓→include -I/home/esc/anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.
below roughly summarizes some of the aspects of the techniques.
˓→linux-x86_64-2.7/_cos_doubles.o

In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/


˓→include/numpy/ndarraytypes.h:1722, x Part of CPython Compiled Autogenerated NumPy Support
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/ Python-C-API True True False True
˓→include/numpy/ndarrayobject.h:17,
Ctypes True False False True
from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/ Swig False True True True
˓→include/numpy/arrayobject.h:15,
Cython False True True True
from _cos_doubles.c:253:
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/npy_
˓→deprecated_api.h:11:2: warning: #warning "Using deprecated NumPy API, disable it by Of all three presented techniques, Cython is the most modern and advanced. In particular, the ability
˓→#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" to optimize code incrementally by adding types to your Python code is unique.
/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.
˓→h:236: warning: ‘_import_umath’ defined but not used

gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict- 14.7 Further Reading and References
˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/

˓→include -I/home/esc/anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-


• Gaël Varoquaux’s blog post about avoiding data copies provides some insight on how to handle
˓→x86_64-2.7/cos_doubles.o
memory management cleverly. If you ever run into issues with large datasets, this is a reference to
gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_
come back to for some inspiration.
˓→64-2.7/cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/

˓→scientific-python-lectures/advanced/interfacing_with_c/cython_numpy/cos_doubles.so

$ ls
build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles. 14.8 Exercises
˓→so* setup.py test_cos_doubles.py
Since this is a brand new section, the exercises are considered more as pointers as to what to look at
And, as before, we convince ourselves that it worked: next, so pick the ones that you find more interesting. If you have good ideas for exercises, please let us
know!
import numpy as np
import matplotlib.pyplot as plt 1. Download the source code for each example and compile and run them on your machine.
import cos_doubles
2. Make trivial changes to each example and convince yourself that this works. ( E.g. change cos for
sin.)
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x) 3. Most of the examples, especially the ones involving NumPy may still be fragile and respond badly
to input errors. Look for ways to crash the examples, figure what the problem is and devise a
cos_doubles.cos_doubles_func(x, y) potential solution. Here are some ideas:
plt.plot(x, y)
1. Numerical overflow.
plt.show()
2. Input and output arrays that have different lengths.
3. Multidimensional array.
4. Empty array
5. Arrays with non-double types
4. Use the %timeit IPython magic to measure the execution time of the various solutions

14.5. Cython 514 14.6. Summary 515


Scientific Python Lectures, Edition 2024.2rc0.dev0

14.8.1 Python-C-API

1. Modify the NumPy example such that the function takes two input arguments, where the second
is the preallocated output array, making it similar to the other NumPy examples.
2. Modify the example such that the function only takes a single input array and modifies this in
place.
3. Try to fix the example to use the new NumPy iterator protocol. If you manage to obtain a working
solution, please submit a pull-request on github.
4. You may have noticed, that the NumPy-C-API example is the only NumPy example that does not
wrap cos_doubles but instead applies the cos function directly to the elements of the NumPy
array. Does this have any advantages over the other techniques.
5. Can you wrap cos_doubles using only the NumPy-C-API. You may need to ensure that the arrays
have the correct type, are one dimensional and contiguous in memory.

14.8.2 Ctypes

1. Modify the NumPy example such that cos_doubles_func handles the preallocation for you, thus
making it more like the NumPy-C-API example.
Part III
14.8.3 SWIG

1. Look at the code that SWIG autogenerates, how much of it do you understand?
Packages and applications
2. Modify the NumPy example such that cos_doubles_func handles the preallocation for you, thus
making it more like the NumPy-C-API example.
3. Modify the cos_doubles C function so that it returns an allocated array. Can you wrap this using
SWIG typemaps? If not, why not? Is there a workaround for this specific situation? (Hint: you
know the size of the output array, so it may be possible to construct a NumPy array from the
returned double *.)

14.8.4 Cython

1. Look at the code that Cython autogenerates. Take a closer look at some of the comments that
Cython inserts. What do you see?
2. Look at the section Working with NumPy from the Cython documentation to learn how to incre-
mentally optimize a pure python script that uses NumPy.
3. Modify the NumPy example such that cos_doubles_func handles the preallocation for you, thus
making it more like the NumPy-C-API example.

14.8. Exercises 516 517


Scientific Python Lectures, Edition 2024.2rc0.dev0

This part of the Scientific Python Lectures is dedicated to various scientific packages useful for extended
needs.

CHAPTER 15
Statistics in Python

Author: Gaël Varoquaux

Requirements

• Standard scientific Python environment (NumPy, SciPy, matplotlib)


• Pandas
• Statsmodels
• Seaborn
To install Python and these dependencies, we recommend that you download Anaconda Python or,
preferably, use the package manager if you are under Ubuntu or other linux.

See also:
• Bayesian statistics in Python: This chapter does not cover tools for Bayesian statistics. Of
particular interest for Bayesian modelling is PyMC, which implements a probabilistic programming
language in Python.
• Read a statistics book: The Think stats book is available as free PDF or in print and is a great
introduction to statistics.

Tip: Why Python for statistics?

518 519
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

R is a language dedicated to statistics. Python is a general-purpose language with statistics modules. R


"";"Gender";"FSIQ";"VIQ";"PIQ";"Weight";"Height";"MRI_Count"
has more statistical analysis features than Python, and specialized syntaxes. However, when it comes to
"1";"Female";133;132;124;"118";"64.5";816932
building complex analysis pipelines that mix statistics with e.g. image analysis, text mining, or control
"2";"Male";140;150;124;".";"72.5";1001121
of a physical experiment, the richness of Python is an invaluable asset.
"3";"Male";139;123;150;"143";"73.3";1038437
"4";"Male";133;129;128;"172";"68.8";965353
"5";"Female";137;132;134;"147";"65.0";951545
Contents

• Data representation and interaction 15.1.2 The pandas data-frame


– Data as a table
– The pandas data-frame Tip: We will store and manipulate this data in a pandas.DataFrame, from the pandas module. It is
• Hypothesis testing: comparing two groups the Python equivalent of the spreadsheet table. It is different from a 2D numpy array as it has named
columns, can contain a mixture of different data types by column, and has elaborate selection and pivotal
– Student’s t-test: the simplest statistical test mechanisms.
– Paired tests: repeated measurements on the same individuals
• Linear models, multiple factors, and analysis of variance
Creating dataframes: reading data files or converting arrays
– “formulas” to specify statistical models in Python
– Multiple Regression: including multiple factors
– Post-hoc hypothesis testing: analysis of variance (ANOVA) Separator

• More visualization: seaborn for statistical exploration It is a CSV file, but the separator is “;”
– Pairplot: scatter matrices
– lmplot: plotting a univariate regression Reading from a CSV file: Using the above CSV file that gives observations of brain size and weight
and IQ (Willerman et al. 1991), the data are a mixture of numerical and categorical values:
• Testing for interactions
>>> import pandas
• Full code for the figures >>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".")
• Solutions to this chapter’s exercises >>> data
Unnamed: 0 Gender FSIQ VIQ PIQ Weight Height MRI_Count
0 1 Female 133 132 124 118.0 64.5 816932
1 2 Male 140 150 124 NaN 72.5 1001121
Tip: In this document, the Python inputs are represented with the sign “>>>”. 2 3 Male 139 123 150 143.0 73.3 1038437
3 4 Male 133 129 128 172.0 68.8 965353
4 5 Female 137 132 134 147.0 65.0 951545
...

Disclaimer: Gender questions


Warning: Missing values
Some of the examples of this tutorial are chosen around gender questions. The reason is that on such
questions controlling the truth of a claim actually matters to many people. The weight of the second individual is missing in the CSV file. If we don’t specify the missing value
(NA = not available) marker, we will not be able to do statistical analysis.

15.1 Data representation and interaction

15.1.1 Data as a table


Creating from arrays: A pandas.DataFrame can also be seen as a dictionary of 1D ‘series’, eg arrays
or lists. If we have 3 numpy arrays:
The setting that we consider for statistical analysis is that of multiple observations or samples described
by a set of different attributes or features. The data can than be seen as a 2D table, or matrix, with >>> import numpy as np
columns giving the different attributes of the data, and rows the observations. For instance, the data >>> t = np.linspace(-6, 6, 20)
contained in examples/brain_size.csv: >>> sin_t = np.sin(t)
>>> cos_t = np.cos(t)

15.1. Data representation and interaction 520 15.1. Data representation and interaction 521
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

We can expose them as a pandas.DataFrame: groupby: splitting a dataframe on values of categorical variables:

>>> pandas.DataFrame({'t': t, 'sin': sin_t, 'cos': cos_t}) >>> groupby_gender = data.groupby('Gender')


t sin cos >>> for gender, value in groupby_gender['VIQ']:
0 -6.000000 0.279415 0.960170 ... print((gender, value.mean()))
1 -5.368421 0.792419 0.609977 ('Female', 109.45)
2 -4.736842 0.999701 0.024451 ('Male', 115.25)
3 -4.105263 0.821291 -0.570509
4 -3.473684 0.326021 -0.945363 groupby_gender is a powerful object that exposes many operations on the resulting group of dataframes:
5 -2.842105 -0.295030 -0.955488
6 -2.210526 -0.802257 -0.596979 >>> groupby_gender.mean()
7 -1.578947 -0.999967 -0.008151 Unnamed: 0 FSIQ VIQ PIQ Weight Height MRI_Count
8 -0.947368 -0.811882 0.583822 Gender
... Female 19.65 111.9 109.45 110.45 137.200000 65.765000 862654.6
Male 21.35 115.0 115.25 111.60 166.444444 71.431579 954855.4

Tip: Use tab-completion on groupby_gender to find more. Other common grouping functions are
median, count (useful for checking to see the amount of missing values in different subsets) or sum.
Groupby evaluation is lazy, no work is done until an aggregation function is applied.
Other inputs: pandas can input data from SQL, excel files, or other formats. See the pandas docu-
mentation.

Manipulating data

data is a pandas.DataFrame, that resembles R’s dataframe:

>>> data.shape # 40 rows and 8 columns


(40, 8)

>>> data.columns # It has columns


Index(['Unnamed: 0', 'Gender', 'FSIQ', 'VIQ', 'PIQ', 'Weight', 'Height',
'MRI_Count'],
dtype='object')

>>> print(data['Gender']) # Columns can be addressed by name


0 Female Exercise
1 Male
2 Male • What is the mean value for VIQ for the full population?
3 Male
4 Female • How many males/females were included in this study?
... Hint use ‘tab completion’ to find out the methods that can be called, instead of ‘mean’ in the
above example.
>>> # Simpler selector
>>> data[data['Gender'] == 'Female']['VIQ'].mean() • What is the average value of MRI counts expressed in log units, for males and females?
109.45

Note: groupby_gender.boxplot is used for the plots above (see this example).
Note: For a quick view on a large dataframe, use its describe method: pandas.DataFrame.describe().

15.1. Data representation and interaction 522 15.1. Data representation and interaction 523
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Plotting data

Pandas comes with some plotting tools (pandas.plotting, using matplotlib behind the scene) to display
statistics of the data in dataframes:
Scatter matrices:

>>> from pandas import plotting


>>> plotting.scatter_matrix(data[['Weight', 'Height', 'MRI_Count']])
array([[<Axes: xlabel='Weight', ylabel='Weight'>,
<Axes: xlabel='Height', ylabel='Weight'>,
<Axes: xlabel='MRI_Count', ylabel='Weight'>],
[<Axes: xlabel='Weight', ylabel='Height'>,
<Axes: xlabel='Height', ylabel='Height'>,
<Axes: xlabel='MRI_Count', ylabel='Height'>],
[<Axes: xlabel='Weight', ylabel='MRI_Count'>,
<Axes: xlabel='Height', ylabel='MRI_Count'>,
<Axes: xlabel='MRI_Count', ylabel='MRI_Count'>]], dtype=object)

Exercise

Plot the scatter matrix for males only, and for females only. Do you think that the 2 sub-populations
correspond to gender?

15.2 Hypothesis testing: comparing two groups

For simple statistical tests, we will use the scipy.stats sub-module of SciPy:

>>> import scipy as sp

See also:
SciPy is a vast library. For a quick summary to the whole library, see the scipy chapter.

>>> plotting.scatter_matrix(data[['PIQ', 'VIQ', 'FSIQ']]) 15.2.1 Student’s t-test: the simplest statistical test
array([[<Axes: xlabel='PIQ', ylabel='PIQ'>,
<Axes: xlabel='VIQ', ylabel='PIQ'>,
<Axes: xlabel='FSIQ', ylabel='PIQ'>],
[<Axes: xlabel='PIQ', ylabel='VIQ'>,
<Axes: xlabel='VIQ', ylabel='VIQ'>,
<Axes: xlabel='FSIQ', ylabel='VIQ'>],
[<Axes: xlabel='PIQ', ylabel='FSIQ'>,
<Axes: xlabel='VIQ', ylabel='FSIQ'>,
<Axes: xlabel='FSIQ', ylabel='FSIQ'>]], dtype=object)

Two populations

The IQ metrics are bimodal, as if there are 2 sub-populations.

15.1. Data representation and interaction 524 15.2. Hypothesis testing: comparing two groups 525
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

One-sample tests: testing the value of a population mean 15.2.2 Paired tests: repeated measurements on the same individuals

PIQ, VIQ, and FSIQ give three measures of IQ. Let us test whether FISQ and PIQ are significantly
different. We can use an “independent sample” test:

>>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ'])


TtestResult(statistic=0.46563759638..., pvalue=0.64277250..., df=78.0)

scipy.stats.ttest_1samp() tests the null hypothesis that the mean of the population underlying the The problem with this approach is that it ignores an important relationship between observations: FSIQ
data is equal to a given value. It returns the T statistic, and the p-value (see the function’s help): and PIQ are measured on the same individuals. Thus, the variance due to inter-subject variability is
confounding, reducing the power of the test. This variability can be removed using a “paired test” or
>>> sp.stats.ttest_1samp(data['VIQ'], 0) “repeated measures test”:
TtestResult(statistic=30.088099970..., pvalue=1.32891964...e-28, df=39)
>>> sp.stats.ttest_rel(data['FSIQ'], data['PIQ'])
The p-value of 10− 28 indicates that such an extreme value of the statistic is unlikely to be observed TtestResult(statistic=1.784201940..., pvalue=0.082172638183..., df=39)
under the null hypothesis. This may be taken as evidence that the null hypothesis is false and that the
population mean IQ (VIQ measure) is not 0.
Technically, the p-value of the t-test is derived under the assumption that the means of samples drawn
from the population are normally distributed. This condition is exactly satisfied when the population
itself is normally distributed; however, due to the central limit theorem, the condition is nearly true for
reasonably large samples drawn from populations that follow a variety of non-normal distributions.
Nonetheless, if we are concerned that violation of the normality assumptions will affect the conclusions
of the test, we can use a Wilcoxon signed-rank test, which relaxes this assumption at the expense of test
power:

>>> sp.stats.wilcoxon(data['VIQ'])
WilcoxonResult(statistic=0.0, pvalue=1.8189894...e-12)
This is equivalent to a one-sample test on the differences between paired observations:

>>> sp.stats.ttest_1samp(data['FSIQ'] - data['PIQ'], 0)


Two-sample t-test: testing for difference across populations TtestResult(statistic=1.784201940..., pvalue=0.082172638..., df=39)

We have seen above that the mean VIQ in the male and female samples were different. To test whether Accordingly, we can perform a nonparametric version of the test with wilcoxon.
this difference is significant (and suggests that there is a difference in population means), we perform a
two-sample t-test using scipy.stats.ttest_ind(): >>> sp.stats.wilcoxon(data['FSIQ'], data['PIQ'], method="approx")
WilcoxonResult(statistic=274.5, pvalue=0.106594927135...)
>>> female_viq = data[data['Gender'] == 'Female']['VIQ']
>>> male_viq = data[data['Gender'] == 'Male']['VIQ']
>>> sp.stats.ttest_ind(female_viq, male_viq) Exercise
TtestResult(statistic=-0.77261617232..., pvalue=0.4445287677858..., df=38.0)
• Test the difference between weights in males and females.
The corresponding non-parametric test is the Mann–Whitney U test, scipy.stats.mannwhitneyu().
• Use non parametric statistics to test the difference between VIQ in males and females.
>>> sp.stats.mannwhitneyu(female_viq, male_viq)
MannwhitneyuResult(statistic=164.5, pvalue=0.34228868687...)

15.2. Hypothesis testing: comparing two groups 526 15.2. Hypothesis testing: comparing two groups 527
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Conclusion: we find that the data does not support the hypothesis that males and females have
different VIQ.

Then we specify an OLS model and fit it:

>>> from statsmodels.formula.api import ols


>>> model = ols("y ~ x", data).fit()

We can inspect the various statistics derived from the fit:


15.3 Linear models, multiple factors, and analysis of variance
>>> print(model.summary())
OLS Regression Results
15.3.1 “formulas” to specify statistical models in Python ==============================================================================
Dep. Variable: y R-squared: 0.901
A simple linear regression Model: OLS Adj. R-squared: 0.896
Method: Least Squares F-statistic: 164.5
Date: ... Prob (F-statistic): 1.72e-10
Time: ... Log-Likelihood: -51.758
No. Observations: 20 AIC: 107.5
Df Residuals: 18 BIC: 109.5
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -4.2948 0.759 -5.661 0.000 -5.889 -2.701
x 3.2060 0.250 12.825 0.000 2.681 3.731
==============================================================================
Omnibus: 1.218 Durbin-Watson: 1.796
Prob(Omnibus): 0.544 Jarque-Bera (JB): 0.999
Skew: 0.503 Prob(JB): 0.607
Given two set of observations, x and y, we want to test the hypothesis that y is a linear function of x. Kurtosis: 2.568 Cond. No. 3.03
In other terms: ==============================================================================

𝑦 = 𝑥 * coef + intercept + 𝑒 Notes:


where e is observation noise. We will use the statsmodels module to: [1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.
1. Fit a linear model. We will use the simplest strategy, ordinary least squares (OLS).
2. Test that coef is non zero.
Terminology:

Statsmodels uses a statistical terminology: the y variable in statsmodels is called ‘endogenous’ while
the x variable is called exogenous. This is discussed in more detail here.
To simplify, y (endogenous) is the value you are trying to predict, while x (exogenous) represents the
First, we generate simulated data according to the model: features you are using to make the prediction.
>>> import numpy as np
>>> x = np.linspace(-5, 5, 20)
>>> rng = np.random.default_rng(27446968) Exercise
>>> # normal distributed noise
>>> y = -5 + 3*x + 4 * rng.normal(size=x.shape) Retrieve the estimated parameters from the model above. Hint: use tab-completion to find the
>>> # Create a data frame containing all the relevant variables relevant attribute.
>>> data = pandas.DataFrame({'x': x, 'y': y})

“formulas” for statistics in Python

See the statsmodels documentation

15.3. Linear models, multiple factors, and analysis of variance 528 15.3. Linear models, multiple factors, and analysis of variance 529
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Categorical variables: comparing groups or multiple categories


Link to t-tests between different FSIQ and PIQ
Let us go back the data on brain size:
To compare different types of IQ, we need to create a “long-form” table, listing IQs, where the type
>>> data = pandas.read_csv('examples/brain_size.csv', sep=';', na_values=".") of IQ is indicated by a categorical variable:

We can write a comparison between IQ of male and female using a linear model: >>>data_fisq = pandas.DataFrame({'iq': data['FSIQ'], 'type': 'fsiq'})
>>>data_piq = pandas.DataFrame({'iq': data['PIQ'], 'type': 'piq'})
>>> model = ols("VIQ ~ Gender + 1", data).fit() >>>data_long = pandas.concat((data_fisq, data_piq))
>>> print(model.summary()) >>>print(data_long)
OLS Regression Results iq type
============================================================================== 0 133 fsiq
Dep. Variable: VIQ R-squared: 0.015 1 140 fsiq
Model: OLS Adj. R-squared: -0.010 2 139 fsiq
Method: Least Squares F-statistic: 0.5969 3 133 fsiq
Date: ... Prob (F-statistic): 0.445 4 137 fsiq
Time: ... Log-Likelihood: -182.42 ... ... ...
No. Observations: 40 AIC: 368.8 35 128 piq
Df Residuals: 38 BIC: 372.2 36 124 piq
Df Model: 1 37 94 piq
Covariance Type: nonrobust 38 74 piq
================================================================================== 39 89 piq
coef std err t P>|t| [0.025 0.975]
---------------------------------------------------------------------------------- [80 rows x 2 columns]
Intercept 109.4500 5.308 20.619 0.000 98.704 120.196
Gender[T.Male] 5.8000 7.507 0.773 0.445 -9.397 20.997 >>> model = ols("iq ~ type", data_long).fit()
============================================================================== >>> print(model.summary())
Omnibus: 26.188 Durbin-Watson: 1.709 OLS Regression Results
Prob(Omnibus): 0.000 Jarque-Bera (JB): 3.703 ...
Skew: 0.010 Prob(JB): 0.157 ==========================...
Kurtosis: 1.510 Cond. No. 2.62 coef std err t P>|t| [0.025 0.975]
============================================================================== ------------------------------------------...
Intercept 113.4500 3.683 30.807 0.000 106.119 120.781
Notes: type[T.piq] -2.4250 5.208 -0.466 0.643 -12.793 7.943
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣ ...
˓→specified.
We can see that we retrieve the same values for t-test and corresponding p-values for the effect of the
type of iq than the previous t-test:
Tips on specifying model >>> sp.stats.ttest_ind(data['FSIQ'], data['PIQ'])
TtestResult(statistic=0.46563759638..., pvalue=0.64277250..., df=78.0)
Forcing categorical: the ‘Gender’ is automatically detected as a categorical variable, and thus each
of its different values are treated as different entities.
An integer column can be forced to be treated as categorical using:
15.3.2 Multiple Regression: including multiple factors
>>> model = ols('VIQ ~ C(Gender)', data).fit()

Intercept: We can remove the intercept using - 1 in the formula, or force the use of an intercept
using + 1.

Tip: By default, statsmodels treats a categorical variable with K possible values as K-1 ‘dummy’
boolean variables (the last level being absorbed into the intercept term). This is almost always a
good default choice - however, it is possible to specify different encodings for categorical variables
(https://www.statsmodels.org/devel/contrasts.html).

15.3. Linear models, multiple factors, and analysis of variance 530 15.3. Linear models, multiple factors, and analysis of variance 531
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


==========================...
coef std err t P>|t| [0.025 0.975]
Consider a linear model explaining a variable z (the dependent variable) with 2 variables x and y: ------------------------------------------...
𝑧 = 𝑥 𝑐1 + 𝑦 𝑐2 + 𝑖 + 𝑒 Intercept 2.9813 0.099 29.989 0.000 2.785 3.178
name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124
Such a model can be seen in 3D as fitting a plane to a cloud of (x, y, z) points. name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158
petal_length 0.2983 0.061 4.920 0.000 0.178 0.418
==========================...
Omnibus: 2.868 Durbin-Watson: 1.753
Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885
Skew: -0.082 Prob(JB): 0.236
Kurtosis: 3.659 Cond. No. 54.0
Example: the iris data (examples/iris.csv) ==========================...

Notes:
Tip: Sepal and petal size tend to be related: bigger flowers are bigger! But is there in addition a
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
systematic effect of species?
˓→specified.

15.3.3 Post-hoc hypothesis testing: analysis of variance (ANOVA)

In the above iris example, we wish to test if the petal length is different between versicolor and virginica,
after removing the effect of sepal width. This can be formulated as testing the difference between the
coefficient associated to versicolor and virginica in the linear model estimated above (it is an Analysis of
Variance, ANOVA). For this, we write a vector of ‘contrast’ on the parameters estimated: we want
to test "name[T.versicolor] - name[T.virginica]", with an F-test:

>>> print(model.f_test([0, 1, -1, 0]))


<F test: F=3.24533535..., p=0.07369..., df_denom=146, df_num=1>

Is this difference significant?

Exercise

>>> data = pandas.read_csv('examples/iris.csv') Going back to the brain size + IQ data, test if the VIQ of male and female are different after removing
>>> model = ols('sepal_width ~ name + petal_length', data).fit() the effect of brain size, height and weight.
>>> print(model.summary())
OLS Regression Results
==========================...
Dep. Variable: sepal_width R-squared: 0.478
Model: OLS Adj. R-squared: 0.468
Method: Least Squares F-statistic: 44.63
Date: ... Prob (F-statistic): 1.58e-20
Time: ... Log-Likelihood: -38.185
No. Observations: 150 AIC: 84.37
Df Residuals: 146 BIC: 96.41
Df Model: 3
Covariance Type: nonrobust
(continues on next page)

15.3. Linear models, multiple factors, and analysis of variance 532 15.3. Linear models, multiple factors, and analysis of variance 533
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

15.4 More visualization: seaborn for statistical exploration >>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'],
... kind='reg', hue='SEX')
Seaborn combines simple statistical fits with plotting on pandas dataframes.
Let us consider a data giving wages and many other personal information on 500 individuals (Berndt,
ER. The Practice of Econometrics. 1991. NY: Addison-Wesley).

Tip: The full code loading and plotting of the wages data is found in corresponding example.

>>> print(data)
EDUCATION SOUTH SEX EXPERIENCE UNION WAGE AGE RACE \
0 8 0 1 21 0 0.707570 35 2
1 9 0 1 42 0 0.694605 57 3
2 12 0 0 1 0 0.824126 19 3
3 12 0 0 4 0 0.602060 22 3
...

15.4.1 Pairplot: scatter matrices

We can easily have an intuition on the interactions between continuous variables using seaborn.
pairplot() to display a scatter matrix:

>>> import seaborn


>>> seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'],
... kind='reg')

Look and feel and matplotlib settings

Seaborn changes the default of matplotlib figures to achieve a more “modern”, “excel-like” look. It
does that upon import. You can reset the default using:
>>> import matplotlib.pyplot as plt
>>> plt.rcdefaults()

Tip: To switch back to seaborn settings, or understand better styling in seaborn, see the relevant
section of the seaborn documentation.

Categorical variables can be plotted as the hue:

15.4. More visualization: seaborn for statistical exploration 534 15.4. More visualization: seaborn for statistical exploration 535
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

15.4.2 lmplot: plotting a univariate regression 15.5 Testing for interactions

A regression capturing the relation between one variable and another, eg wage and eduction, can be
plotted using seaborn.lmplot():

>>> seaborn.lmplot(y='WAGE', x='EDUCATION', data=data)


Do wages increase more with education for males than females?

Robust regression Tip: The plot above is made of two different fits. We need to formulate a single model that tests for a
variance of slope across the two populations. This is done via an “interaction”.

Tip: Given that, in the above plot, there seems to be a couple of data points that are outside of the
main cloud to the right, they might be outliers, not representative of the population, but driving the >>> result = sm.ols(formula='wage ~ education + gender + education * gender',
regression. ... data=data).fit()
>>> print(result.summary())
...
To compute a regression that is less sensitive to outliers, one must use a robust model. This is done
coef std err t P>|t| [0.025 0.975]
in seaborn using robust=True in the plotting functions, or in statsmodels by replacing the use of the
------------------------------------------------------------------------------
OLS by a “Robust Linear Model”, statsmodels.formula.api.rlm().
Intercept 0.2998 0.072 4.173 0.000 0.159 0.441
gender[T.male] 0.2750 0.093 2.972 0.003 0.093 0.457
education 0.0415 0.005 7.647 0.000 0.031 0.052
education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 0.000
==========================...
...

Can we conclude that education benefits males more than females?

Take home messages

• Hypothesis testing and p-values give you the significance of an effect / difference.
• Formulas (with categorical variables) enable you to express rich links in your data.
• Visualizing your data and fitting simple models give insight into the data.

15.4. More visualization: seaborn for statistical exploration 536 15.5. Testing for interactions 537
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Conditionning (adding factors that can explain all or part of the variation) is an important import pandas
modeling aspect that changes the interpretation.
import matplotlib.pyplot as plt

data = pandas.read_csv("brain_size.csv", sep=";", na_values=".")

# Box plot of FSIQ and PIQ (different measures od IQ)


plt.figure(figsize=(4, 3))
15.6 Full code for the figures data.boxplot(column=["FSIQ", "PIQ"])

# Boxplot of the difference


Code examples for the statistics chapter. plt.figure(figsize=(4, 3))
plt.boxplot(data["FSIQ"] - data["PIQ"])
plt.xticks((1,), ("FSIQ - PIQ",))
15.6.1 Boxplots and paired differences
plt.show()
Plot boxplots for FSIQ, PIQ, and the paired difference between the two: while the spread (error bars)
for FSIQ and PIQ are very large, there is a systematic (common) effect due to the subjects. This effect
Total running time of the script: (0 minutes 0.069 seconds)
is cancelled out in the difference and the spread of the difference (“paired” by subject) is much smaller
than the spread of the individual measures.

15.6.2 Plotting simple quantities of a pandas dataframe

This example loads from a CSV file data with mixed numerical and categorical entries, and plots a few
quantities, separately for females and males, thanks to the pandas integrated plotting tool (that uses
matplotlib behind the scene).
See http://pandas.pydata.org/pandas-docs/stable/visualization.html


15.6. Full code for the figures 538 15.6. Full code for the figures 539
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


data = pandas.read_csv("brain_size.csv", sep=";", na_values=".")

# Box plots of different columns for each gender


groupby_gender = data.groupby("Gender")
groupby_gender.boxplot(column=["FSIQ", "VIQ", "PIQ"])

from pandas import plotting

# Scatter matrices for different columns


plotting.scatter_matrix(data[["Weight", "Height", "MRI_Count"]])
plotting.scatter_matrix(data[["PIQ", "VIQ", "FSIQ"]])

import matplotlib.pyplot as plt

plt.show()

Total running time of the script: (0 minutes 0.579 seconds)

15.6.3 Analysis of Iris petal and sepal sizes

Illustrate an analysis on a real dataset:


• Visualizing the data to formulate intuitions

• Fitting of a linear model
• Hypothesis test of the effect of a categorical variable in the presence of a continuous confound

import matplotlib.pyplot as plt

import pandas
from pandas import plotting

from statsmodels.formula.api import ols

# Load the data


data = pandas.read_csv("iris.csv")

Plot a scatter matrix

# Express the names as categories


categories = pandas.Categorical(data["name"])

# The parameter 'c' is passed to plt.scatter and will control the color
plotting.scatter_matrix(data, c=categories.codes, marker="o")

fig = plt.gcf()
fig.suptitle("blue: setosa, green: versicolor, red: virginica", size=13)

import pandas

(continues on next page)

15.6. Full code for the figures 540 15.6. Full code for the figures 541
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


======================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------
Intercept 2.9813 0.099 29.989 0.000 2.785 3.178
name[T.versicolor] -1.4821 0.181 -8.190 0.000 -1.840 -1.124
name[T.virginica] -1.6635 0.256 -6.502 0.000 -2.169 -1.158
petal_length 0.2983 0.061 4.920 0.000 0.178 0.418
==============================================================================
Omnibus: 2.868 Durbin-Watson: 1.753
Prob(Omnibus): 0.238 Jarque-Bera (JB): 2.885
Skew: -0.082 Prob(JB): 0.236
Kurtosis: 3.659 Cond. No. 54.0
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

Testing the difference between effect of versicolor and virginica


<F test: F=3.245335346574177, p=0.07369058781701142, df_denom=146, df_num=1>

Total running time of the script: (0 minutes 0.405 seconds)

15.6.4 Simple Regression

Fit a simple linear regression using ‘statsmodels’, compute corresponding p-values.


Text(0.5, 0.98, 'blue: setosa, green: versicolor, red: virginica') # Original author: Thomas Haslwanter

Statistical analysis import numpy as np


import matplotlib.pyplot as plt
# Let us try to explain the sepal length as a function of the petal import pandas
# width and the category of iris
# For statistics. Requires statsmodels 5.0 or more
model = ols("sepal_width ~ name + petal_length", data).fit() from statsmodels.formula.api import ols
print(model.summary())
# Analysis of Variance (ANOVA) on linear models
# Now formulate a "contrast", to test if the offset for versicolor and from statsmodels.stats.anova import anova_lm
# virginica are identical
Generate and show the data
print("Testing the difference between effect of versicolor and virginica")
print(model.f_test([0, 1, -1, 0])) x = np.linspace(-5, 5, 20)
plt.show()
# To get reproducible values, provide a seed value
OLS Regression Results rng = np.random.default_rng(27446968)
==============================================================================
Dep. Variable: sepal_width R-squared: 0.478 y = -5 + 3 * x + 4 * np.random.normal(size=x.shape)
Model: OLS Adj. R-squared: 0.468
Method: Least Squares F-statistic: 44.63 # Plot the data
Date: Tue, 04 Jun 2024 Prob (F-statistic): 1.58e-20 plt.figure(figsize=(5, 4))
Time: 22:38:38 Log-Likelihood: -38.185 plt.plot(x, y, "o")
No. Observations: 150 AIC: 84.37
Df Residuals: 146 BIC: 96.41
Df Model: 3
Covariance Type: nonrobust
(continues on next page)

15.6. Full code for the figures 542 15.6. Full code for the figures 543
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept -4.1877 0.830 -5.044 0.000 -5.932 -2.444
x 2.7046 0.274 9.887 0.000 2.130 3.279
==============================================================================
Omnibus: 1.871 Durbin-Watson: 1.930
Prob(Omnibus): 0.392 Jarque-Bera (JB): 0.597
Skew: 0.337 Prob(JB): 0.742
Kurtosis: 3.512 Cond. No. 3.03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

ANOVA results
df sum_sq mean_sq F PR(>F)
x 1.0 1347.476043 1347.476043 97.760281 1.062847e-08
Residual 18.0 248.102486 13.783471 NaN NaN

Plot the fitted model

# Retrieve the parameter estimates


offset, coef = model._results.params
[<matplotlib.lines.Line2D object at 0x7f494c235310>] plt.plot(x, x * coef + offset)
plt.xlabel("x")
Multilinear regression model, calculating fit, P-values, confidence intervals etc. plt.ylabel("y")

# Convert the data into a Pandas DataFrame to use the formulas framework plt.show()
# in statsmodels
data = pandas.DataFrame({"x": x, "y": y})

# Fit the model


model = ols("y ~ x", data).fit()

# Print the summary


print(model.summary())

# Perform analysis of variance on fitted linear model


anova_results = anova_lm(model)

print("\nANOVA results")
print(anova_results)

OLS Regression Results


==============================================================================
Dep. Variable: y R-squared: 0.845
Model: OLS Adj. R-squared: 0.836
Method: Least Squares F-statistic: 97.76
Date: Tue, 04 Jun 2024 Prob (F-statistic): 1.06e-08
Time: 22:38:38 Log-Likelihood: -53.560
No. Observations: 20 AIC: 111.1
Df Residuals: 18 BIC: 113.1
Df Model: 1
Covariance Type: nonrobust
==============================================================================
(continues on next page)

15.6. Full code for the figures 544 15.6. Full code for the figures 545
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


skiprows=27,
skipfooter=6,
sep=None,
header=None,
names=["education", "gender", "wage"],
usecols=[0, 2, 5],
)

# Convert genders to strings (this is particularly useful so that the


# statsmodels formulas detects that gender is a categorical variable)
import numpy as np

data["gender"] = np.choose(data.gender, ["male", "female"])

# Log-transform the wages, because they typically are increased with


# multiplicative factors
data["wage"] = np.log10(data["wage"])

/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/plot_wage_education_gender.py:30: ParserWarning: Falling back␣

˓→to the 'python' engine because the 'c' engine does not support skipfooter; you can␣

˓→avoid this warning by specifying engine='python'.

data = pandas.read_csv(

simple plotting

import seaborn
Total running time of the script: (0 minutes 0.100 seconds) # Plot 2 linear fits for male and female.
seaborn.lmplot(y="wage", x="education", hue="gender", data=data)

15.6.5 Test for an education/gender interaction in wages

Wages depend mostly on education. Here we investigate how this dependence is related to gender: not
only does gender create an offset in wages, it also seems that wages increase more with education for
males than females.
Does our data support this last hypothesis? We will test this using statsmodels’ formulas (http://
statsmodels.sourceforge.net/stable/example_formulas.html).
Load and massage the data

import pandas

import urllib
import os

if not os.path.exists("wages.txt"):
# Download the file if it is not present
urllib.urlretrieve("http://lib.stat.cmu.edu/datasets/CPS_85_Wages", "wages.txt")

# EDUCATION: Number of years of education


# SEX: 1=Female, 0=Male
# WAGE: Wage (dollars per hour)
data = pandas.read_csv(
"wages.txt",
(continues on next page)

15.6. Full code for the figures 546 15.6. Full code for the figures 547
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Intercept 0.4053 0.046 8.732 0.000 0.314 0.496
gender[T.male] 0.1008 0.018 5.625 0.000 0.066 0.136
education 0.0334 0.003 9.768 0.000 0.027 0.040
==============================================================================
Omnibus: 4.675 Durbin-Watson: 1.792
Prob(Omnibus): 0.097 Jarque-Bera (JB): 4.876
Skew: -0.147 Prob(JB): 0.0873
Kurtosis: 3.365 Cond. No. 69.7
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

The plots above highlight that there is not only a different offset in wage but also a different slope
We need to model this using an interaction

result = sm.ols(
formula="wage ~ education + gender + education * gender", data=data
).fit()
print(result.summary())

OLS Regression Results


==============================================================================
Dep. Variable: wage R-squared: 0.198
Model: OLS Adj. R-squared: 0.194
Method: Least Squares F-statistic: 43.72
Date: Tue, 04 Jun 2024 Prob (F-statistic): 2.94e-25
Time: 22:38:39 Log-Likelihood: 88.503
<seaborn.axisgrid.FacetGrid object at 0x7f494bfba790> No. Observations: 534 AIC: -169.0
Df Residuals: 530 BIC: -151.9
statistical analysis Df Model: 3
Covariance Type: nonrobust
import statsmodels.formula.api as sm ============================================================================================
coef std err t P>|t| [0.025 ␣
# Note that this model is not the plot displayed above: it is one ˓→0.975]

# joined model for male and female, not separate models for male and --------------------------------------------------------------------------------------
# female. The reason is that a single model enables statistical testing ˓→------

result = sm.ols(formula="wage ~ education + gender", data=data).fit() Intercept 0.2998 0.072 4.173 0.000 0.159 ␣
print(result.summary()) ˓→ 0.441

gender[T.male] 0.2750 0.093 2.972 0.003 0.093 ␣


˓→ 0.457
OLS Regression Results
============================================================================== education 0.0415 0.005 7.647 0.000 0.031 ␣
˓→ 0.052
Dep. Variable: wage R-squared: 0.193
Model: OLS Adj. R-squared: 0.190 education:gender[T.male] -0.0134 0.007 -1.919 0.056 -0.027 ␣
˓→ 0.000
Method: Least Squares F-statistic: 63.42
Date: Tue, 04 Jun 2024 Prob (F-statistic): 2.01e-25 ==============================================================================
Time: 22:38:39 Log-Likelihood: 86.654 Omnibus: 4.838 Durbin-Watson: 1.825
No. Observations: 534 AIC: -167.3 Prob(Omnibus): 0.089 Jarque-Bera (JB): 5.000
Df Residuals: 531 BIC: -154.5 Skew: -0.156 Prob(JB): 0.0821
Df Model: 2 Kurtosis: 3.356 Cond. No. 194.
Covariance Type: nonrobust ==============================================================================
==================================================================================
coef std err t P>|t| [0.025 0.975] Notes:
---------------------------------------------------------------------------------- [1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.
(continues on next page)

15.6. Full code for the figures 548 15.6. Full code for the figures 549
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Looking at the p-value of the interaction of gender and education, the data does not support the hy-
pothesis that education benefits males more than female (p-value > 0.05).

import matplotlib.pyplot as plt

plt.show()

Total running time of the script: (0 minutes 0.506 seconds)

15.6.6 Multiple Regression

Calculate using ‘statsmodels’ just the best fit, or all the corresponding statistical parameters.
Also shows how to make 3d plots.

# Original author: Thomas Haslwanter

import numpy as np
import matplotlib.pyplot as plt
import pandas

# For 3d plots. This import is necessary to have 3D plotting below


from mpl_toolkits.mplot3d import Axes3D

# For statistics. Requires statsmodels 5.0 or more


from statsmodels.formula.api import ols

# Analysis of Variance (ANOVA) on linear models


from statsmodels.stats.anova import anova_lm Text(-0.10764513121260137, 0.009865032686848034, 'Z')

Generate and show the data Multilinear regression model, calculating fit, P-values, confidence intervals etc.

x = np.linspace(-5, 5, 21) # Convert the data into a Pandas DataFrame to use the formulas framework
# We generate a 2D grid # in statsmodels
X, Y = np.meshgrid(x, x)
# First we need to flatten the data: it's 2D layout is not relevant.
# To get reproducible values, provide a seed value X = X.flatten()
rng = np.random.default_rng(27446968) Y = Y.flatten()
Z = Z.flatten()
# Z is the elevation of this 2D grid
Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape) data = pandas.DataFrame({"x": X, "y": Y, "z": Z})

# Plot the data # Fit the model


ax = plt.figure().add_subplot(projection="3d") model = ols("z ~ x + y", data).fit()
surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, rstride=1, cstride=1)
ax.view_init(20, -120) # Print the summary
ax.set_xlabel("X") print(model.summary())
ax.set_ylabel("Y")
ax.set_zlabel("Z") print("\nRetrieving manually the parameter estimates:")
print(model._results.params)
# should be array([-4.99754526, 3.00250049, -0.50514907])

# Perform analysis of variance on fitted linear model


anova_results = anova_lm(model)

print("\nANOVA results")
(continues on next page)

15.6. Full code for the figures 550 15.6. Full code for the figures 551
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Standard library imports
print(anova_results) import os

plt.show() import matplotlib.pyplot as plt

OLS Regression Results Load the data


==============================================================================
Dep. Variable: z R-squared: 0.579 import pandas
Model: OLS Adj. R-squared: 0.577 import requests
Method: Least Squares F-statistic: 300.7
Date: Tue, 04 Jun 2024 Prob (F-statistic): 6.43e-83 if not os.path.exists("wages.txt"):
Time: 22:38:39 Log-Likelihood: -1552.0 # Download the file if it is not present
No. Observations: 441 AIC: 3110. r = requests.get("http://lib.stat.cmu.edu/datasets/CPS_85_Wages")
Df Residuals: 438 BIC: 3122. with open("wages.txt", "wb") as f:
Df Model: 2 f.write(r.content)
Covariance Type: nonrobust
============================================================================== # Give names to the columns
coef std err t P>|t| [0.025 0.975] names = [
------------------------------------------------------------------------------ "EDUCATION: Number of years of education",
Intercept -4.4332 0.390 -11.358 0.000 -5.200 -3.666 "SOUTH: 1=Person lives in South, 0=Person lives elsewhere",
x 3.0861 0.129 23.940 0.000 2.833 3.340 "SEX: 1=Female, 0=Male",
y -0.6856 0.129 -5.318 0.000 -0.939 -0.432 "EXPERIENCE: Number of years of work experience",
============================================================================== "UNION: 1=Union member, 0=Not union member",
Omnibus: 0.560 Durbin-Watson: 1.967 "WAGE: Wage (dollars per hour)",
Prob(Omnibus): 0.756 Jarque-Bera (JB): 0.651 "AGE: years",
Skew: -0.077 Prob(JB): 0.722 "RACE: 1=Other, 2=Hispanic, 3=White",
Kurtosis: 2.893 Cond. No. 3.03 "OCCUPATION: 1=Management, 2=Sales, 3=Clerical, 4=Service, 5=Professional, 6=Other
˓→",
==============================================================================
"SECTOR: 0=Other, 1=Manufacturing, 2=Construction",
Notes: "MARR: 0=Unmarried, 1=Married",
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣ ]
˓→specified.
short_names = [n.split(":")[0] for n in names]
Retrieving manually the parameter estimates:
[-4.43322435 3.08614608 -0.68556194] data = pandas.read_csv(
"wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python"
ANOVA results )
df sum_sq mean_sq F PR(>F) data.columns = short_names
x 1.0 38501.973182 38501.973182 573.111646 1.365553e-81
y 1.0 1899.955512 1899.955512 28.281320 1.676135e-07 # Log-transform the wages, because they typically are increased with
Residual 438.0 29425.094352 67.180581 NaN NaN # multiplicative factors
import numpy as np
Total running time of the script: (0 minutes 0.119 seconds)
data["WAGE"] = np.log10(data["WAGE"])

Plot scatter matrices highlighting different aspects


15.6.7 Visualizing factors influencing wages import seaborn

This example uses seaborn to quickly plot various factors relating wages, experience and eduction. seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg")
Seaborn (https://seaborn.pydata.org) is a library that combines visualization and statistical fits to show
trends in data. seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="SEX")
plt.suptitle("Effect of gender: 1=Female, 0=Male")
Note that importing seaborn changes the matplotlib style to have an “excel-like” feeling. This changes
affect other matplotlib figures. To restore defaults once this example is run, we would need to call seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="RACE")
plt.rcdefaults(). plt.suptitle("Effect of race: 1=Other, 2=Hispanic, 3=White")

(continues on next page)

15.6. Full code for the figures 552 15.6. Full code for the figures 553
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


seaborn.pairplot(data, vars=["WAGE", "AGE", "EDUCATION"], kind="reg", hue="UNION")
plt.suptitle("Effect of union: 1=Union member, 0=Not union member")

15.6. Full code for the figures 554 15.6. Full code for the figures 555
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •

Text(0.5, 0.98, 'Effect of union: 1=Union member, 0=Not union member')

Plot a simple regression

seaborn.lmplot(y="WAGE", x="EDUCATION", data=data)

plt.show()

15.6. Full code for the figures 556 15.6. Full code for the figures 557
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# is not yet distributed
)
with open("airfares.txt", "wb") as f:
f.write(r.content)

# As a separator, ' +' is a regular expression that means 'one of more


# space'
data = pandas.read_csv(
"airfares.txt",
delim_whitespace=True,
header=0,
names=[
"city1",
"city2",
"pop1",
"pop2",
"dist",
"fare_2000",
"nb_passengers_2000",
"fare_2001",
"nb_passengers_2001",
],
)

# we log-transform the number of passengers


import numpy as np

data["nb_passengers_2000"] = np.log10(data["nb_passengers_2000"])
data["nb_passengers_2001"] = np.log10(data["nb_passengers_2001"])
Total running time of the script: (0 minutes 8.984 seconds)
/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/plot_airfare.py:38: FutureWarning: The 'delim_whitespace'␣

˓→keyword in pd.read_csv is deprecated and will be removed in a future version. Use␣

˓→``sep='\s+'`` instead
15.6.8 Air fares before and after 9/11 data = pandas.read_csv(
This is a business-intelligence (BI) like application.
Make a dataframe with the year as an attribute, instead of separate columns
What is interesting here is that we may want to study fares as a function of the year, paired accordingly
to the trips, or forgetting the year, only as a function of the trip endpoints. # This involves a small danse in which we separate the dataframes in 2,
# one for year 2000, and one for 2001, before concatenating again.
Using statsmodels’ linear models, we find that both with an OLS (ordinary least square) and a robust
fit, the intercept and the slope are significantly non-zero: the air fares have decreased between 2000 and # Make an index of each flight
2001, and their dependence on distance travelled has also decreased data_flat = data.reset_index()
# Standard library imports
data_2000 = data_flat[
import os
["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"]
]
Load the data
# Rename the columns
import pandas data_2000.columns = ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers
import requests ˓→"]

# Add a column with the year


if not os.path.exists("airfares.txt"): data_2000.insert(0, "year", 2000)
# Download the file if it is not present
r = requests.get( data_2001 = data_flat[
"https://users.stat.ufl.edu/~winner/data/airq4.dat", ["city1", "city2", "pop1", "pop2", "dist", "fare_2001", "nb_passengers_2001"]
verify=False, # Wouldn't normally do this, but this site's certificate ]
(continues on next page) (continues on next page)

15.6. Full code for the figures 558 15.6. Full code for the figures 559
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


# Rename the columns
data_2001.columns = ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers
˓→"]

# Add a column with the year


data_2001.insert(0, "year", 2001)

data_flat = pandas.concat([data_2000, data_2001])

Plot scatter matrices highlighting different aspects

import seaborn

seaborn.pairplot(
data_flat, vars=["fare", "dist", "nb_passengers"], kind="reg", markers="."
)

# A second plot, to show the effect of the year (ie the 9/11 effect)
seaborn.pairplot(
data_flat,
vars=["fare", "dist", "nb_passengers"],
kind="reg",
hue="year",
markers=".",
)

15.6. Full code for the figures 560 15.6. Full code for the figures 561
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0


Statistical testing: dependence of fare on distance and number of passengers

import statsmodels.formula.api as sm

result = sm.ols(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit()


print(result.summary())

# Using a robust fit
<seaborn.axisgrid.PairGrid object at 0x7f4955859510> result = sm.rlm(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit()
print(result.summary())
Plot the difference in fare
OLS Regression Results
import matplotlib.pyplot as plt
==============================================================================
Dep. Variable: fare R-squared: 0.275
plt.figure(figsize=(5, 2))
Model: OLS Adj. R-squared: 0.275
seaborn.boxplot(data.fare_2001 - data.fare_2000)
Method: Least Squares F-statistic: 1585.
plt.title("Fare: 2001 - 2000")
Date: Tue, 04 Jun 2024 Prob (F-statistic): 0.00
plt.subplots_adjust()
Time: 22:38:56 Log-Likelihood: -45532.
No. Observations: 8352 AIC: 9.107e+04
plt.figure(figsize=(5, 2))
Df Residuals: 8349 BIC: 9.109e+04
seaborn.boxplot(data.nb_passengers_2001 - data.nb_passengers_2000)
Df Model: 2
plt.title("NB passengers: 2001 - 2000")
Covariance Type: nonrobust
plt.subplots_adjust()
=================================================================================
coef std err t P>|t| [0.025 0.975]
---------------------------------------------------------------------------------
Intercept 211.2428 2.466 85.669 0.000 206.409 216.076
dist 0.0484 0.001 48.149 0.000 0.046 0.050
nb_passengers -32.8925 1.127 -29.191 0.000 -35.101 -30.684
==============================================================================
Omnibus: 604.051 Durbin-Watson: 1.446
Prob(Omnibus): 0.000 Jarque-Bera (JB): 740.733
Skew: 0.710 Prob(JB): 1.42e-161
(continues on next page)

15.6. Full code for the figures 562 15.6. Full code for the figures 563
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


Kurtosis: 3.338 Cond. No. 5.23e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

[2] The condition number is large, 5.23e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
Robust linear Model Regression Results
==============================================================================
Dep. Variable: fare No. Observations: 8352
Model: RLM Df Residuals: 8349
Method: IRLS Df Model: 2
Norm: HuberT
Scale Est.: mad
Cov Type: H1
Date: Tue, 04 Jun 2024
Time: 22:38:56
No. Iterations: 12
=================================================================================
coef std err z P>|z| [0.025 0.975]
---------------------------------------------------------------------------------
Intercept 215.0848 2.448 87.856 0.000 210.287 219.883
dist 0.0460 0.001 46.166 0.000 0.044 0.048
nb_passengers -35.2686 1.119 -31.526 0.000 -37.461 -33.076
=================================================================================

If the model instance has been used for another fit with different fit parameters,␣
˓→then the fit options might not be the correct ones anymore .

Statistical testing: regression of fare on distance: 2001/2000 difference OLS Regression Results
==============================================================================
result = sm.ols(formula="fare_2001 - fare_2000 ~ 1 + dist", data=data).fit() Dep. Variable: fare_2001 R-squared: 0.159
print(result.summary()) Model: OLS Adj. R-squared: 0.159
Method: Least Squares F-statistic: 791.7
# Plot the corresponding regression Date: Tue, 04 Jun 2024 Prob (F-statistic): 1.20e-159
data["fare_difference"] = data["fare_2001"] - data["fare_2000"] Time: 22:38:56 Log-Likelihood: -22640.
seaborn.lmplot(x="dist", y="fare_difference", data=data) No. Observations: 4176 AIC: 4.528e+04
Df Residuals: 4174 BIC: 4.530e+04
plt.show() Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 148.0279 1.673 88.480 0.000 144.748 151.308
dist 0.0388 0.001 28.136 0.000 0.036 0.041
==============================================================================
Omnibus: 136.558 Durbin-Watson: 1.544
Prob(Omnibus): 0.000 Jarque-Bera (JB): 149.624
Skew: 0.462 Prob(JB): 3.23e-33
Kurtosis: 2.920 Cond. No. 2.40e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

(continues on next page)

15.6. Full code for the figures 564 15.6. Full code for the figures 565
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


[2] The condition number is large, 2.4e+03. This might indicate that there are Kurtosis: 1.823 Cond. No. 2.40e+07
strong multicollinearity or other numerical problems. ==============================================================================

Total running time of the script: (0 minutes 7.845 seconds) Notes:


[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.

[2] The condition number is large, 2.4e+07. This might indicate that there are
strong multicollinearity or other numerical problems.
15.7 Solutions to this chapter’s exercises <F test: F=0.683196084584229, p=0.4140878441244694, df_denom=35, df_num=1>

15.7.1 Solutions to this chapter’s exercises Here we plot a scatter matrix to get intuitions on our results. This goes beyond what was asked in the
exercise
Relating Gender and IQ # This plotting is useful to get an intuitions on the relationships between
# our different variables
Going back to the brain size + IQ data, test if the VIQ of male and female are different after removing
the effect of brain size, height and weight. from pandas import plotting
Notice that here ‘Gender’ is a categorical value. As it is a non-float data type, statsmodels is able to import matplotlib.pyplot as plt
automatically infer this.
# Fill in the missing values for Height for plotting
import pandas data["Height"].fillna(method="pad", inplace=True)
from statsmodels.formula.api import ols
# The parameter 'c' is passed to plt.scatter and will control the color
data = pandas.read_csv("../brain_size.csv", sep=";", na_values=".") # The same holds for parameters 'marker', 'alpha' and 'cmap', that
# control respectively the type of marker used, their transparency and
model = ols("VIQ ~ Gender + MRI_Count + Height", data).fit() # the colormap
print(model.summary()) plotting.scatter_matrix(
data[["VIQ", "MRI_Count", "Height"]],
# Here, we don't need to define a contrast, as we are testing a single c=(data["Gender"] == "Female"),
# coefficient of our model, and not a combination of coefficients. marker="o",
# However, defining a contrast, which would then be a 'unit contrast', alpha=1,
# will give us the same results cmap="winter",
print(model.f_test([0, 1, 0, 0])) )

OLS Regression Results fig = plt.gcf()


============================================================================== fig.suptitle("blue: male, green: female", size=13)
Dep. Variable: VIQ R-squared: 0.246
Model: OLS Adj. R-squared: 0.181 plt.show()
Method: Least Squares F-statistic: 3.809
Date: Tue, 04 Jun 2024 Prob (F-statistic): 0.0184
Time: 22:38:56 Log-Likelihood: -172.34
No. Observations: 39 AIC: 352.7
Df Residuals: 35 BIC: 359.3
Df Model: 3
Covariance Type: nonrobust
==================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------
Intercept 166.6258 88.824 1.876 0.069 -13.696 346.948
Gender[T.Male] 8.8524 10.710 0.827 0.414 -12.890 30.595
MRI_Count 0.0002 6.46e-05 2.615 0.013 3.78e-05 0.000
Height -3.0837 1.276 -2.417 0.021 -5.674 -0.494
==============================================================================
Omnibus: 7.373 Durbin-Watson: 2.109
Prob(Omnibus): 0.025 Jarque-Bera (JB): 2.252
Skew: 0.005 Prob(JB): 0.324
(continues on next page)

15.7. Solutions to this chapter’s exercises 566 15.7. Solutions to this chapter’s exercises 567
Scientific Python Lectures, Edition 2024.2rc0.dev0

CHAPTER 16
Sympy : Symbolic Mathematics in
Python

/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/solutions/plot_brain_size.py:39: FutureWarning: A value is␣

˓→trying to be set on a copy of a DataFrame or Series through chained assignment␣ Author: Fabian Pedregosa
˓→using an inplace method.

The behavior will change in pandas 3.0. This inplace method will never work because␣
˓→the intermediate object on which we are setting values always behaves as a copy.
Objectives

For example, when doing 'df[col].method(value, inplace=True)', try using 'df.method( 1. Evaluate expressions with arbitrary precision.
˓→{col: value}, inplace=True)' or df[col] = df[col].method(value) instead, to perform␣
2. Perform algebraic manipulations on symbolic expressions.
˓→the operation inplace on the original object.
3. Perform basic calculus tasks (limits, differentiation and
integration) with symbolic expressions.
data["Height"].fillna(method="pad", inplace=True) 4. Solve polynomial and transcendental equations.
/home/runner/work/scientific-python-lectures/scientific-python-lectures/packages/
˓→statistics/examples/solutions/plot_brain_size.py:39: FutureWarning: Series.fillna␣
5. Solve some differential equations.
˓→with 'method' is deprecated and will raise in a future version. Use obj.ffill() or␣

˓→obj.bfill() instead. What is SymPy? SymPy is a Python library for symbolic mathematics. It aims to be an alternative to
data["Height"].fillna(method="pad", inplace=True) systems such as Mathematica or Maple while keeping the code as simple as possible and easily extensible.
SymPy is written entirely in Python and does not require any external libraries.
Total running time of the script: (0 minutes 0.253 seconds)
Sympy documentation and packages for installation can be found on https://www.sympy.org/

Chapters contents

• First Steps with SymPy


– Using SymPy as a calculator
– Symbols

15.7. Solutions to this chapter’s exercises 568 569


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Algebraic manipulations (continued from previous page)


>>> sym.oo + 1
– Expand
oo
– Simplify
• Calculus
Exercises
– Limits

– Differentiation 1. Calculate 2 with 100 decimals.

– Series expansion 2. Calculate 1/2 + 1/3 in rational arithmetic.

– Integration
• Equation solving
16.1.2 Symbols
• Linear Algebra
In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables
– Matrices
explicitly:
– Differential Equations
>>> x = sym.Symbol('x')
>>> y = sym.Symbol('y')

16.1 First Steps with SymPy Then you can manipulate them:

>>> x + y + x - y
16.1.1 Using SymPy as a calculator 2*x

SymPy defines three numerical types: Real, Rational and Integer. >>> (x + y) ** 2
(x + y)**2
The Rational class represents a rational number as a pair of two Integers: the numerator and the
denominator, so Rational(1, 2) represents 1/2, Rational(5, 2) 5/2 and so on: Symbols can now be manipulated using some of python operators: +, -, *, ** (arithmetic), &, |, ~, >>,
<< (boolean).
>>> import sympy as sym
>>> a = sym.Rational(1, 2)
Printing
>>> a
1/2 Sympy allows for control of the display of the output. From here we use the following setting for
printing:
>>> a*2
>>> sym.init_printing(use_unicode=False, wrap_line=True)
1

SymPy uses mpmath in the background, which makes it possible to perform computations using
arbitrary-precision arithmetic. That way, some special constants, like 𝑒, 𝑝𝑖, 𝑜𝑜 (Infinity), are treated
as symbols and can be evaluated with arbitrary precision: 16.2 Algebraic manipulations
>>> sym.pi**2
pi**2 SymPy is capable of performing powerful algebraic manipulations. We’ll take a look into some of the
most frequently used: expand and simplify.
>>> sym.pi.evalf()
3.14159265358979
16.2.1 Expand
>>> (sym.pi + sym.exp(1)).evalf()
5.85987448204884 Use this to expand an algebraic expression. It will try to denest powers and multiplications:

>>> sym.expand((x + y) ** 3)
as you see, evalf evaluates the expression to a floating-point number. 3 2 2 3
There is also a class representing mathematical infinity, called oo: x + 3*x *y + 3*x*y + y
>>> 3 * x * y ** 2 + 3 * y * x ** 2 + x ** 3 + y ** 3
>>> sym.oo > 99999 3 2 2 3
True x + 3*x *y + 3*x*y + y
(continues on next page)

16.1. First Steps with SymPy 570 16.2. Algebraic manipulations 571
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Further options can be given in form on keywords: 16.3.2 Differentiation


>>> sym.expand(x + y, complex=True) You can differentiate any SymPy expression using diff(func, var). Examples:
re(x) + re(y) + I*im(x) + I*im(y)
>>> sym.I * sym.im(x) + sym.I * sym.im(y) + sym.re(x) + sym.re(y) >>> sym.diff(sym.sin(x), x)
re(x) + re(y) + I*im(x) + I*im(y) cos(x)
>>> sym.diff(sym.sin(2 * x), x)
>>> sym.expand(sym.cos(x + y), trig=True) 2*cos(2*x)
-sin(x)*sin(y) + cos(x)*cos(y)
>>> sym.cos(x) * sym.cos(y) - sym.sin(x) * sym.sin(y) >>> sym.diff(sym.tan(x), x)
-sin(x)*sin(y) + cos(x)*cos(y) 2
tan (x) + 1

16.2.2 Simplify You can check that it is correct by:

>>> sym.limit((sym.tan(x + y) - sym.tan(x)) / y, y, 0)


Use simplify if you would like to transform an expression into a simpler form: 1
>>> sym.simplify((x + x * y) / x) -------
y + 1 2
cos (x)
Simplification is a somewhat vague term, and more precises alternatives to simplify exists: powsimp
(simplification of exponents), trigsimp (for trigonometric expressions) , logcombine, radsimp, together. Which is equivalent since
1
sec(𝑥) = 𝑎𝑛𝑑 sec2 (𝑥) = tan2 (𝑥) + 1.
Exercises cos(𝑥)
You can check this as well:
1. Calculate the expanded form of (𝑥 + 𝑦)6 .
>>> sym.trigsimp(sym.diff(sym.tan(x), x))
2. Simplify the trigonometric expression sin(𝑥)/ cos(𝑥) 1
-------
2
cos (x)
16.3 Calculus
Higher derivatives can be calculated using the diff(func, var, n) method:
16.3.1 Limits >>> sym.diff(sym.sin(2 * x), x, 1)
2*cos(2*x)
Limits are easy to use in SymPy, they follow the syntax limit(function, variable, point), so to
compute the limit of 𝑓 (𝑥) as 𝑥 → 0, you would issue limit(f, x, 0): >>> sym.diff(sym.sin(2 * x), x, 2)
-4*sin(2*x)
>>> sym.limit(sym.sin(x) / x, x, 0)
1
>>> sym.diff(sym.sin(2 * x), x, 3)
-8*cos(2*x)
you can also calculate the limit at infinity:

>>> sym.limit(x, x, sym.oo)


oo 16.3.3 Series expansion
>>> sym.limit(1 / x, x, sym.oo) SymPy also knows how to compute the Taylor series of an expression at a point. Use series(expr,
0 var):

>>> sym.limit(x ** x, x, 0) >>> sym.series(sym.cos(x), x)


1 2 4
x x / 6\
1 - -- + -- + O\x /
2 24
>>> sym.series(1/sym.cos(x), x)
2 4
x 5*x / 6\
(continues on next page)

16.3. Calculus 572 16.3. Calculus 573


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) 16.4 Equation solving


1 + -- + ---- + O\x /
2 24
SymPy is able to solve algebraic equations, in one and several variables using solveset():

>>> sym.solveset(x ** 4 - 1, x)
Exercises {-1, 1, -I, I}

1. Calculate lim𝑥→0 sin(𝑥)/𝑥 As you can see it takes as first argument an expression that is supposed to be equaled to 0. It also has
2. Calculate the derivative of 𝑙𝑜𝑔(𝑥) for 𝑥. (limited) support for transcendental equations:

>>> sym.solveset(sym.exp(x) + 1, x)
{I*(2*n*pi + pi) | n in Integers}
16.3.4 Integration

SymPy has support for indefinite and definite integration of transcendental elementary and special func- Systems of linear equations
tions via integrate() facility, which uses the powerful extended Risch-Norman algorithm and some
heuristics and pattern matching. You can integrate elementary functions: Sympy is able to solve a large part of polynomial equations, and is also capable of solving multiple
equations with respect to multiple variables giving a tuple as second argument. To do this you use
>>> sym.integrate(6 * x ** 5, x) the solve() command:
6 >>> solution = sym.solve((x + 5 * y - 2, -3 * x + 6 * y - 15), (x, y))
x >>> solution[x], solution[y]
>>> sym.integrate(sym.sin(x), x) (-3, 1)
-cos(x)
>>> sym.integrate(sym.log(x), x)
x*log(x) - x Another alternative in the case of polynomial equations is factor. factor returns the polynomial factorized
>>> sym.integrate(2 * x + sym.sinh(x), x) into irreducible terms, and is capable of computing the factorization over various domains:
2
x + cosh(x) >>> f = x ** 4 - 3 * x ** 2 + 1
>>> sym.factor(f)
Also special functions are handled easily: / 2 \ / 2 \
\x - x - 1/*\x + x - 1/
>>> sym.integrate(sym.exp(-x ** 2) * sym.erf(x), x)
____ 2 >>> sym.factor(f, modulus=5)
\/ pi *erf (x) 2 2
-------------- (x - 2) *(x + 2)
4
SymPy is also able to solve boolean equations, that is, to decide if a certain boolean expression is
It is possible to compute definite integral: satisfiable or not. For this, we use the function satisfiable:
>>> sym.integrate(x**3, (x, -1, 1)) >>> sym.satisfiable(x & y)
0 {x: True, y: True}
>>> sym.integrate(sym.sin(x), (x, 0, sym.pi / 2))
1 This tells us that (x & y) is True whenever x and y are both True. If an expression cannot be true, i.e.
>>> sym.integrate(sym.cos(x), (x, -sym.pi / 2, sym.pi / 2)) no values of its arguments can make the expression True, it will return False:
2
>>> sym.satisfiable(x & ~x)
Also improper integrals are supported as well: False

>>> sym.integrate(sym.exp(-x), (x, 0, sym.oo))


1 Exercises
>>> sym.integrate(sym.exp(-x ** 2), (x, -sym.oo, sym.oo))
____ 1. Solve the system of equations 𝑥 + 𝑦 = 2, 2 · 𝑥 + 𝑦 = 0
\/ pi
2. Are there boolean values x, y that make (~x | y) & (~y | x) true?

16.3. Calculus 574 16.4. Equation solving 575


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

16.5 Linear Algebra


Exercises

16.5.1 Matrices 1. Solve the Bernoulli differential equation

Matrices are created as instances from the Matrix class:


𝑑𝑓 (𝑥)
>>> sym.Matrix([[1, 0], [0, 1]]) 𝑥 + 𝑓 (𝑥) − 𝑓 (𝑥)2 = 0
𝑥
[1 0]
[ ] 2. Solve the same equation using hint='Bernoulli'. What do you observe ?
[0 1]

unlike a NumPy array, you can also put Symbols in it:

>>> x, y = sym.symbols('x, y')


>>> A = sym.Matrix([[1, x], [y, 1]])
>>> A
[1 x]
[ ]
[y 1]

>>> A**2
[x*y + 1 2*x ]
[ ]
[ 2*y x*y + 1]

16.5.2 Differential Equations

SymPy is capable of solving (some) Ordinary Differential. To solve differential equations, use dsolve.
First, create an undefined function by passing cls=Function to the symbols function:

>>> f, g = sym.symbols('f g', cls=sym.Function)

f and g are now undefined functions. We can call f(x), and it will represent an unknown function:

>>> f(x)
f(x)

>>> f(x).diff(x, x) + f(x)


2
d
f(x) + ---(f(x))
2
dx

>>> sym.dsolve(f(x).diff(x, x) + f(x), f(x))


f(x) = C1*sin(x) + C2*cos(x)

Keyword arguments can be given to this function in order to help if find the best possible resolution sys-
tem. For example, if you know that it is a separable equations, you can use keyword hint='separable'
to force dsolve to resolve it as a separable equation:

>>> sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x),


˓→ f(x), hint='separable')

/ C1 \ / C1 \
[f(x) = - acos|------| + 2*pi, f(x) = acos|------|]
\cos(x)/ \cos(x)/

16.5. Linear Algebra 576 16.5. Linear Algebra 577


Scientific Python Lectures, Edition 2024.2rc0.dev0

– Local filters
– Non-local filters
– Mathematical morphology
• Image segmentation
– Binary segmentation: foreground + background

17
– Marker based methods
• Measuring regions’ properties
• Data visualization and interaction
CHAPTER
• Feature extraction for computer vision
• Full code examples
• Examples for the scikit-image chapter

17.1 Introduction and concepts


scikit-image: image processing Images are NumPy’s arrays np.ndarray
image
np.ndarray
pixels
array values: a[2, 3]
channels
Author: Emmanuelle Gouillart array dimensions
scikit-image is a Python package dedicated to image processing, using NumPy arrays as image objects. image encoding
This chapter describes how to use scikit-image for various image processing tasks, and how it relates dtype (np.uint8, np.uint16, np.float)
to other scientific Python modules such as NumPy and SciPy.
filters
See also: functions (numpy, skimage, scipy)
For basic image manipulation, such as image cropping or simple filtering, a large number of simple
operations can be realized with NumPy and SciPy only. See Image manipulation and processing using >>> import numpy as np
NumPy and SciPy. >>> check = np.zeros((8, 8))
>>> check[::2, 1::2] = 1
Note that you should be familiar with the content of the previous chapter before reading the current >>> check[1::2, ::2] = 1
one, as basic operations such as masking and labeling are a prerequisite. >>> import matplotlib.pyplot as plt
>>> plt.imshow(check, cmap='gray', interpolation='nearest')
Chapters contents <matplotlib.image.AxesImage object at ...>

• Introduction and concepts


– scikit-image and the scientific Python ecosystem
– What is included in scikit-image
• Importing
• Example data
• Input/output, data types and colorspaces
– Data types
– Colorspaces
• Image preprocessing / enhancement

578 17.1. Introduction and concepts 579


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

exposure
Image intensity adjustment, e.g., histogram equalization, etc.
feature
Feature detection and extraction, e.g., texture analysis corners, etc.
filters
Sharpening, edge finding, rank filters, thresholding, etc.
graph
Graph-theoretic operations, e.g., shortest paths.
io
Reading, saving, and displaying images and video.
measure
Measurement of image properties, e.g., region properties and contours.
metrics
Metrics corresponding to images, e.g. distance metrics, similarity, etc.
morphology
Morphological operations, e.g., opening or skeletonization.
17.1.1 scikit-image and the scientific Python ecosystem
restoration
scikit-image is packaged in both pip and conda-based Python installations, as well as in most Linux Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.
distributions. Other Python packages for image processing & visualization that operate on NumPy segmentation
arrays include: Partitioning an image into multiple regions.
scipy.ndimage transform
For N-dimensional arrays. Basic filtering, mathematical morphology, regions properties Geometric and other transforms, e.g., rotation or the Radon transform.
Mahotas util
With a focus on high-speed implementations. Generic utilities.
Napari
A fast, interactive, multi-dimensional image viewer built in Qt.
17.2 Importing
Some powerful C++ image processing libraries also have Python bindings:
OpenCV We import scikit-image using the convention:
A highly optimized computer vision library with a focus on real-time applications.
>>> import skimage as ski
ITK
The Insight ToolKit, especially useful for registration and working with 3D images.
Most functionality lives in subpackages, e.g.:
To varying degrees, these tend to be less Pythonic and NumPy-friendly.
>>> image = ski.data.cat()

17.1.2 What is included in scikit-image You can list all submodules with:

>>> for m in dir(ski): print(m)


• Website: https://scikit-image.org/
__version__
• Gallery of examples: https://scikit-image.org/docs/stable/auto_examples/ color
data
The library contains predominantly image processing algorithms, but also utility functions to ease data
draw
handling and processing. It contains the following submodules:
exposure
color feature
Color space conversion. filters
future
data
graph
Test images and example data.
io
draw measure
Drawing primitives (lines, text, etc.) that operate on NumPy arrays. metrics
morphology
(continues on next page)

17.1. Introduction and concepts 580 17.2. Importing 581


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


registration
restoration
segmentation
transform
util

Most scikit-image functions take NumPy ndarrays as arguments

>>> camera = ski.data.camera()


>>> camera.dtype
dtype('uint8')
>>> camera.shape
(512, 512)
>>> filtered_camera = ski.filters.gaussian(camera, sigma=1)
>>> type(filtered_camera)
<class 'numpy.ndarray'>

17.3 Example data This works with many data formats supported by the ImageIO library.
Loading also works with URLs:
To start off, we need example images to work with. The library ships with a few of these:
>>> logo = ski.io.imread('https://scikit-image.org/_static/img/logo.png')
skimage.data

>>> image = ski.data.cat()


>>> image.shape 17.4.1 Data types
(300, 451, 3)

17.4 Input/output, data types and colorspaces

I/O: skimage.io
Save an image to disk: skimage.io.imsave()

>>> ski.io.imsave("cat.png", image)


Image ndarrays can be represented either by integers (signed or unsigned) or floats.
Reading from files: skimage.io.imread()
Careful with overflows with integer data types
>>> cat = ski.io.imread("cat.png")
>>> camera = ski.data.camera()
>>> camera.dtype
dtype('uint8')
>>> camera_multiply = 3 * camera

Different integer sizes are possible: 8-, 16- or 32-bytes, signed or unsigned.

Warning: An important (if questionable) skimage convention: float images are supposed to lie
in [-1, 1] (in order to have comparable contrast for all float images)
>>> camera_float = ski.util.img_as_float(camera)
>>> camera.max(), camera_float.max()
(255, 1.0)

17.3. Example data 582 17.4. Input/output, data types and colorspaces 583
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Some image processing routines need to work with float arrays, and may hence output an array with a
different type and the data range from the input array

>>> camera_sobel = ski.filters.sobel(camera)


>>> camera_sobel.max()
0.644...

Utility functions are provided in skimage to convert both the dtype and the data range, following
skimage’s conventions: util.img_as_float, util.img_as_ubyte, etc.
See the user guide for more details.
Example : horizontal Sobel filter
17.4.2 Colorspaces >>> text = ski.data.text()
>>> hsobel_text = ski.filters.sobel_h(text)
Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel encodes transparency)
Uses the following linear kernel for computing horizontal gradients:
>>> face = sp.datasets.face()
>>> face.shape 1 2 1
(768, 1024, 3) 0 0 0
-1 -2 -1
Routines converting between different colorspaces (RGB, HSV, LAB etc.) are available in skimage.
color : color.rgb2hsv, color.lab2rgb, etc. Check the docstring for the expected dtype (and data
range) of input images.

3D images

Most functions of skimage can take 3D images as input arguments. Check the docstring to know if a
function can be used on 3D images (for example MRI or CT images).

17.5.2 Non-local filters


Exercise
Non-local filters use a large region of the image (or all the image) to transform the value of one pixel:
Open a color image on your disk as a NumPy array. >>> camera = ski.data.camera()
Find a skimage function computing the histogram of an image and plot the histogram of >>> camera_equalized = ski.exposure.equalize_hist(camera)
each color channel
Enhances contrast in large almost uniform regions.
Convert the image to grayscale and plot its histogram.

17.5 Image preprocessing / enhancement

Goals: denoising, feature (edges) extraction, . . .

17.5.1 Local filters

Local filters replace the value of pixels by a function of the values of neighboring pixels. The function
can be linear or non-linear.
Neighbourhood: square (choose size), disk, or more complicated structuring element.

17.5. Image preprocessing / enhancement 584 17.5. Image preprocessing / enhancement 585
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

17.5.3 Mathematical morphology (continued from previous page)


[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
See wikipedia for an introduction on mathematical morphology.
Probe an image with a simple shape (a structuring element), and modify this image according to how Dilation: maximum filter:
the shape locally fits or misses the image.
>>> a = np.zeros((5, 5))
Default structuring element: 4-connectivity of a pixel >>> a[2, 2] = 1
>>> a
>>> # Import structuring elements to make them more easily accessible array([[0., 0., 0., 0., 0.],
>>> from skimage.morphology import disk, diamond [0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
>>> diamond(1) [0., 0., 0., 0., 0.],
array([[0, 1, 0], [0., 0., 0., 0., 0.]])
[1, 1, 1], >>> ski.morphology.binary_dilation(a, diamond(1)).astype(np.uint8)
[0, 1, 0]], dtype=uint8) array([[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)

Opening: erosion + dilation:

>>> a = np.zeros((5,5), dtype=int)


>>> a[1:4, 1:4] = 1; a[4, 4] = 1
>>> a
array([[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0],
Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring [0, 0, 0, 0, 1]])
element.: >>> ski.morphology.binary_opening(a, diamond(1)).astype(np.uint8)
>>> a = np.zeros((7,7), dtype=np.uint8) array([[0, 0, 0, 0, 0],
>>> a[1:6, 2:5] = 1 [0, 0, 1, 0, 0],
>>> a [0, 1, 1, 1, 0],
array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=uint8)
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0], Opening removes small objects and smoothes corners.
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0], Grayscale mathematical morphology
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> ski.morphology.binary_erosion(a, diamond(1)).astype(np.uint8) Mathematical morphology operations are also available for (non-binary) grayscale images (int or float
array([[0, 0, 0, 0, 0, 0, 0], type). Erosion and dilation correspond to minimum (resp. maximum) filters.
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0], Higher-level mathematical morphology are available: tophat, skeletonization, etc.
[0, 0, 0, 1, 0, 0, 0], See also:
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], dtype=uint8) Basic mathematical morphology is also implemented in scipy.ndimage.morphology. The scipy.
>>> #Erosion removes objects smaller than the structure ndimage implementation works on arbitrary-dimensional arrays.
>>> ski.morphology.binary_erosion(a, diamond(2)).astype(np.uint8)
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
Example of filters comparison: image denoising
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0], >>> coins = ski.data.coins()
[0, 0, 0, 0, 0, 0, 0], >>> coins_zoom = coins[10:80, 300:370]
[0, 0, 0, 0, 0, 0, 0], >>> median_coins = ski.filters.median(
(continues on next page)

17.5. Image preprocessing / enhancement 586 17.5. Image preprocessing / enhancement 587
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

... coins_zoom, disk(1) Labeling connected components of a discrete image


... )
>>> tv_coins = ski.restoration.denoise_tv_chambolle(
... coins_zoom, weight=0.1 Tip: Once you have separated foreground objects, it is use to separate them from each other. For this,
... ) we can assign a different integer labels to each one.
>>> gaussian_coins = ski.filters.gaussian(coins, sigma=2)
Synthetic data:

>>> n = 20
>>> l = 256
>>> im = np.zeros((l, l))
>>> rng = np.random.default_rng()
>>> points = l * rng.random((2, n ** 2))
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1
>>> im = ski.filters.gaussian(im, sigma=l / (4. * n))
>>> blobs = im > im.mean()

Label all connected components:

17.6 Image segmentation >>> all_labels = ski.measure.label(blobs)

Label only foreground connected components:


Image segmentation is the attribution of different labels to different regions of the image, for example in
order to extract the pixels of an object of interest. >>> blobs_labels = ski.measure.label(blobs, background=0)

17.6.1 Binary segmentation: foreground + background

Histogram-based method: Otsu thresholding

Tip: The Otsu method is a simple heuristic to find a threshold to separate the foreground from the
background.

Earlier scikit-image versions

skimage.filters is called skimage.filter in earlier versions of scikit-image


See also:
camera = ski.data.camera() scipy.ndimage.find_objects() is useful to return slices on object in an image.
val = ski.filters.threshold_otsu(camera)
mask = camera < val

17.6. Image segmentation 588 17.6. Image segmentation 589


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

17.6.2 Marker based methods skimage.segmentation.clear_border(), skimage.segmentation.relabel_from_one(), skimage.


morphology.remove_small_objects(), etc.
If you have markers inside a set of regions, you can use these to segment the regions.

Watershed segmentation Exercise

The Watershed (skimage.segmentation.watershed()) is a region-growing approach that fills “basins” • Load the coins image from the data submodule.
in the image
• Separate the coins from the background by testing several segmentation methods: Otsu thresh-
>>> # Generate an initial image with two overlapping circles olding, adaptive thresholding, and watershed or random walker segmentation.
>>> x, y = np.indices((80, 80)) • If necessary, use a postprocessing function to improve the coins / background segmentation.
>>> x1, y1, x2, y2 = 28, 28, 44, 52
>>> r1, r2 = 16, 20
>>> mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2
>>> mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2
>>> image = np.logical_or(mask_circle1, mask_circle2) 17.7 Measuring regions’ properties
>>> # Now we want to separate the two objects in image
>>> # Generate the markers as local maxima of the distance Example: compute the size and perimeter of the two segmented regions:
>>> # to the background
>>> import scipy as sp >>> properties = ski.measure.regionprops(labels_rw)
>>> distance = sp.ndimage.distance_transform_edt(image) >>> [float(prop.area) for prop in properties]
>>> peak_idx = ski.feature.peak_local_max( [770.0, 1168.0]
... distance, footprint=np.ones((3, 3)), labels=image >>> [prop.perimeter for prop in properties]
... ) [100.91..., 126.81...]
>>> peak_mask = np.zeros_like(distance, dtype=bool)
>>> peak_mask[tuple(peak_idx.T)] = True See also:
>>> markers = ski.morphology.label(peak_mask) for some properties, functions are available as well in scipy.ndimage.measurements with a different
>>> labels_ws = ski.segmentation.watershed( API (a list is returned).
... -distance, markers, mask=image
... )
Exercise (continued)

Random walker segmentation • Use the binary image of the coins and background from the previous exercise.
• Compute an image of labels for the different coins.
The random walker algorithm (skimage.segmentation.random_walker()) is similar to the Watershed,
but with a more “probabilistic” approach. It is based on the idea of the diffusion of labels in the image: • Compute the size and eccentricity of all coins.

>>> # Transform markers image so that 0-valued pixels are to


>>> # be labelled, and -1-valued pixels represent background
>>> markers[~image] = -1 17.8 Data visualization and interaction
>>> labels_rw = ski.segmentation.random_walker(image, markers)
Meaningful visualizations are useful when testing a given processing pipeline.
Some image processing operations:

>>> coins = ski.data.coins()


>>> mask = coins > ski.filters.threshold_otsu(coins)
>>> clean_border = ski.segmentation.clear_border(mask)

Visualize binary result:

>>> plt.figure()
<Figure size ... with 0 Axes>
>>> plt.imshow(clean_border, cmap='gray')
Postprocessing label images <matplotlib.image.AxesImage object at 0x...>

skimage provides several utility functions that can be used on label images (ie images where Visualize contour
different discrete values identify different regions). Functions names are often self-explaining:

17.6. Image segmentation 590 17.7. Measuring regions’ properties 591


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> plt.figure()
<Figure size ... with 0 Axes>
>>> plt.imshow(coins, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
>>> plt.contour(clean_border, [0.5])
<matplotlib.contour.QuadContourSet ...>

Use skimage dedicated utility function:

>>> coins_edges = ski.segmentation.mark_boundaries(


... coins, clean_border.astype(int)
... )

(this example is taken from the plot_corner example in scikit-image)


Points of interest such as corners can then be used to match objects in different images, as described in
the plot_matching example of scikit-image.

17.9 Feature extraction for computer vision


17.10 Full code examples
Geometric or textural descriptor can be extracted from images in order to
• classify parts of the image (e.g. sky vs. buildings) 17.11 Examples for the scikit-image chapter
• match parts of different images (e.g. for object detection)
• and many other applications of Computer Vision 17.11.1 Creating an image
Example: detecting corners using Harris detector
How to create an image with basic NumPy commands : np.zeros, slicing. . .
tform = ski.transform.AffineTransform( This examples show how to create a simple checkerboard.
scale=(1.3, 1.1), rotation=1, shear=0.7,
translation=(210, 50)
)
image = ski.transform.warp(
data.checkerboard(), tform.inverse, output_shape=(350, 350)
)

coords = ski.feature.corner_peaks(
ski.feature.corner_harris(image), min_distance=5
)
coords_subpix = ski.feature.corner_subpix(
image, coords, window_size=13
)

17.9. Feature extraction for computer vision 592 17.10. Full code examples 593
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

import matplotlib.pyplot as plt


from skimage import data

camera = data.camera()

import numpy as np
import matplotlib.pyplot as plt plt.figure(figsize=(4, 4))
plt.imshow(camera, cmap="gray", interpolation="nearest")
check = np.zeros((8, 8)) plt.axis("off")
check[::2, 1::2] = 1
check[1::2, ::2] = 1 plt.tight_layout()
plt.matshow(check, cmap="gray") plt.show()
plt.show()
Total running time of the script: (0 minutes 0.082 seconds)
Total running time of the script: (0 minutes 0.069 seconds)

17.11.3 Integers can overflow


17.11.2 Displaying a simple image
An illustration of overflow problem arising when working with integers
Load and display an image

17.11. Examples for the scikit-image chapter 594 17.11. Examples for the scikit-image chapter 595
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

from skimage import data, exposure


import matplotlib.pyplot as plt

import matplotlib.pyplot as plt camera = data.camera()


from skimage import data camera_equalized = exposure.equalize_hist(camera)

camera = data.camera() plt.figure(figsize=(7, 3))


camera_multiply = 3 * camera
plt.subplot(121)
plt.figure(figsize=(8, 4)) plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.subplot(121) plt.axis("off")
plt.imshow(camera, cmap="gray", interpolation="nearest") plt.subplot(122)
plt.axis("off") plt.imshow(camera_equalized, cmap="gray", interpolation="nearest")
plt.subplot(122) plt.axis("off")
plt.imshow(camera_multiply, cmap="gray", interpolation="nearest") plt.tight_layout()
plt.axis("off") plt.show()

plt.tight_layout() Total running time of the script: (0 minutes 0.100 seconds)


plt.show()

Total running time of the script: (0 minutes 0.135 seconds)


17.11.5 Computing horizontal gradients with the Sobel filter

This example illustrates the use of the horizontal Sobel filter, to compute horizontal gradients.
17.11.4 Equalizing the histogram of an image

Histogram equalizing makes images have a uniform histogram.

from skimage import data


from skimage import filters
import matplotlib.pyplot as plt

text = data.text()
(continues on next page)

17.11. Examples for the scikit-image chapter 596 17.11. Examples for the scikit-image chapter 597
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


hsobel_text = filters.sobel_h(text)
plt.tight_layout()
plt.figure(figsize=(12, 3)) plt.show()

plt.subplot(121) Total running time of the script: (0 minutes 0.119 seconds)


plt.imshow(text, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(hsobel_text, cmap="nipy_spectral", interpolation="nearest") 17.11.7 Otsu thresholding
plt.axis("off")
plt.tight_layout()
This example illustrates automatic Otsu thresholding.
plt.show()

Total running time of the script: (0 minutes 0.118 seconds)

17.11.6 Segmentation contours

Visualize segmentation contours on original grayscale image.

import matplotlib.pyplot as plt


from skimage import data
from skimage import filters
from skimage import exposure

camera = data.camera()
val = filters.threshold_otsu(camera)

hist, bins_center = exposure.histogram(camera)


from skimage import data, segmentation
from skimage import filters plt.figure(figsize=(9, 4))
import matplotlib.pyplot as plt plt.subplot(131)
import numpy as np plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.axis("off")
coins = data.coins() plt.subplot(132)
mask = coins > filters.threshold_otsu(coins) plt.imshow(camera < val, cmap="gray", interpolation="nearest")
clean_border = segmentation.clear_border(mask).astype(int) plt.axis("off")
plt.subplot(133)
coins_edges = segmentation.mark_boundaries(coins, clean_border) plt.plot(bins_center, hist, lw=2)
plt.axvline(val, color="k", ls="--")
plt.figure(figsize=(8, 3.5))
plt.subplot(121) plt.tight_layout()
plt.imshow(clean_border, cmap="gray") plt.show()
plt.axis("off")
plt.subplot(122)
Total running time of the script: (0 minutes 0.138 seconds)
plt.imshow(coins_edges)
plt.axis("off")
(continues on next page)

17.11. Examples for the scikit-image chapter 598 17.11. Examples for the scikit-image chapter 599
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

17.11.8 Affine transform 17.11.9 Labelling connected components of an image

Warping and affine transforms of images. This example shows how to label connected components of a binary image, using the dedicated skim-
age.measure.label function.

from skimage import measure


from skimage import filters
import matplotlib.pyplot as plt
import numpy as np

n = 12
l = 256
rng = np.random.default_rng(27446968)
im = np.zeros((l, l))
points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
im = filters.gaussian(im, sigma=l / (4.0 * n))
blobs = im > 0.7 * im.mean()
import matplotlib.pyplot as plt
all_labels = measure.label(blobs)
from skimage import data blobs_labels = measure.label(blobs, background=0)
from skimage.feature import corner_harris, corner_subpix, corner_peaks
from skimage.transform import warp, AffineTransform plt.figure(figsize=(9, 3.5))
plt.subplot(131)
plt.imshow(blobs, cmap="gray")
tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210,␣ plt.axis("off")
˓→50))
plt.subplot(132)
image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350)) plt.imshow(all_labels, cmap="nipy_spectral")
plt.axis("off")
coords = corner_peaks(corner_harris(image), min_distance=5) plt.subplot(133)
coords_subpix = corner_subpix(image, coords, window_size=13) plt.imshow(blobs_labels, cmap="nipy_spectral")
plt.axis("off")
plt.gray()
plt.imshow(image, interpolation="nearest") plt.tight_layout()
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5) plt.show()
plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7)
plt.axis("off")
Total running time of the script: (0 minutes 0.096 seconds)
plt.show()

Total running time of the script: (0 minutes 5.360 seconds)

17.11. Examples for the scikit-image chapter 600 17.11. Examples for the scikit-image chapter 601
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

17.11.10 Various denoising filters 17.11.11 Watershed and random walker for segmentation

This example compares several denoising filters available in scikit-image: a Gaussian filter, a median This example compares two segmentation methods in order to separate two connected disks: the water-
filter, and total variation denoising. shed algorithm, and the random walker algorithm.
Both segmentation methods require seeds, that are pixels belonging unambigusouly to a reagion. Here,
local maxima of the distance map to the background are used as seeds.

import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import filters
from skimage import restoration import numpy as np
from skimage.segmentation import watershed
coins = data.coins() from skimage.feature import peak_local_max
gaussian_filter_coins = filters.gaussian(coins, sigma=2) from skimage import measure
med_filter_coins = filters.median(coins, np.ones((3, 3))) from skimage.segmentation import random_walker
tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1) import matplotlib.pyplot as plt
import scipy as sp
plt.figure(figsize=(16, 4))
plt.subplot(141) # Generate an initial image with two overlapping circles
plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest") x, y = np.indices((80, 80))
plt.axis("off") x1, y1, x2, y2 = 28, 28, 44, 52
plt.title("Image") r1, r2 = 16, 20
plt.subplot(142) mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2
˓→") image = np.logical_or(mask_circle1, mask_circle2)
plt.axis("off") # Now we want to separate the two objects in image
plt.title("Gaussian filter") # Generate the markers as local maxima of the distance
plt.subplot(143) # to the background
plt.imshow(med_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") distance = sp.ndimage.distance_transform_edt(image)
plt.axis("off") peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)
plt.title("Median filter") peak_mask = np.zeros_like(distance, dtype=bool)
plt.subplot(144) peak_mask[tuple(peak_idx.T)] = True
plt.imshow(tv_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest") markers = measure.label(peak_mask)
plt.axis("off") labels_ws = watershed(-distance, markers, mask=image)
plt.title("TV filter")
plt.show() markers[~image] = -1
labels_rw = random_walker(image, markers)
Total running time of the script: (0 minutes 0.175 seconds)
plt.figure(figsize=(12, 3.5))
plt.subplot(141)
plt.imshow(image, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.title("image")
plt.subplot(142)
plt.imshow(-distance, interpolation="nearest")
plt.axis("off")
plt.title("distance map")
plt.subplot(143)
(continues on next page)

17.11. Examples for the scikit-image chapter 602 17.11. Examples for the scikit-image chapter 603
Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.imshow(labels_ws, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.title("watershed segmentation")
plt.subplot(144)
plt.imshow(labels_rw, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.title("random walker segmentation")

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.182 seconds)


CHAPTER 18
scikit-learn: machine learning in Python

Authors: Gael Varoquaux

Prerequisites

• numpy
• scipy
• matplotlib (optional)
• ipython (the enhancements come handy)

Acknowledgements

This chapter is adapted from a tutorial given by Gaël Varoquaux, Jake Vanderplas, Olivier Grisel.

See also:
Data science in Python
• The Statistics in Python chapter may also be of interest for readers looking into machine learning.
• The documentation of scikit-learn is very complete and didactic.

17.11. Examples for the scikit-image chapter 604 605


Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Chapters contents

• Introduction: problem settings


• Basic principles of machine learning with scikit-learn
• Supervised Learning: Classification of Handwritten Digits
• Supervised Learning: Regression of Housing Data
• Measuring prediction performance
• Unsupervised Learning: Dimensionality Reduction and Visualization
• Parameter selection, Validation, and Testing
• Examples for the scikit-learn chapter

18.1 Introduction: problem settings Fig. 2: A regression problem

18.1.1 What is machine learning?

Tip: Machine Learning is about building programs with tunable parameters that are adjusted
automatically so as to improve their behavior by adapting to previously seen data.
Machine Learning can be considered a subfield of Artificial Intelligence since those algorithms can be The next simple task we’ll look at is a regression task: a simple best-fit line to a set of data.
seen as building blocks to make computers learn to behave more intelligently by somehow generalizing
rather that just storing and retrieving data items like a database system would do. Again, this is an example of fitting a model to data, but our focus here is that the model can make
generalizations about new data. The model has been learned from the training data, and can be used
to predict the result of test data: here, we might be given an x-value, and the model would allow us to
predict the y value.

18.1.2 Data in scikit-learn

The data matrix

Machine learning algorithms implemented in scikit-learn expect data to be stored in a two-dimensional


array or matrix. The arrays can be either numpy arrays, or in some cases scipy.sparse matrices. The
size of the array is expected to be [n_samples, n_features]
• n_samples: The number of samples: each sample is an item to process (e.g. classify). A sample
can be a document, a picture, a sound, a video, an astronomical object, a row in database or CSV
file, or whatever you can describe with a fixed set of quantitative traits.
• n_features: The number of features or distinct traits that can be used to describe each item in
a quantitative manner. Features are generally real-valued, but may be boolean or discrete-valued
in some cases.
Fig. 1: A classification problem
Tip: The number of features must be fixed in advance. However it can be very high dimensional (e.g.
millions of features) with most of them being zeros for a given sample. This is a case where scipy.sparse
We’ll take a look at two very simple machine learning tasks here. The first is a classification task: matrices can be useful, in that they are much more memory-efficient than NumPy arrays.
the figure shows a collection of two-dimensional data, colored according to two different class labels. A
classification algorithm may be used to draw a dividing boundary between the two clusters of points:
By drawing this separating line, we have learned a model which can generalize to new data: if you were
to drop another point onto the plane which is unlabeled, this algorithm could now predict whether it’s
a blue or a red point.

18.1. Introduction: problem settings 606 18.1. Introduction: problem settings 607
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

A Simple Example: the Iris Dataset


Note: Import sklearn Note that scikit-learn is imported as sklearn
The application problem
The features of each sample flower are stored in the data attribute of the dataset:
As an example of a simple dataset, let us a look at the iris data stored by scikit-learn. Suppose we want
to recognize species of irises. The data consists of measurements of three different species of irises: >>> print(iris.data.shape)
(150, 4)
>>> n_samples, n_features = iris.data.shape
>>> print(n_samples)
150
>>> print(n_features)
4
>>> print(iris.data[0])
[5.1 3.5 1.4 0.2]

The information about the class of each sample is stored in the target attribute of the dataset:

>>> print(iris.target.shape)
(150,)
Setosa Iris Versicolor Iris Virginica Iris >>> print(iris.target)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Quick Question: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
If we want to design an algorithm to recognize iris species, what might the 2 2]
data be?
The names of the classes are stored in the last attribute, namely target_names:
Remember: we need a 2D array of size [n_samples x n_features].
• What would the n_samples refer to? >>> print(iris.target_names)
['setosa' 'versicolor' 'virginica']
• What might the n_features refer to?
This data is four-dimensional, but we can visualize two of the dimensions at a time using a scatter plot:
Remember that there must be a fixed number of features for each sample, and feature number i must
be a similar kind of quantity for each sample.

Loading the Iris Data with Scikit-learn

Scikit-learn has a very straightforward set of data on these iris species. The data consist of the following:
• Features in the Iris dataset:
– sepal length (cm)
– sepal width (cm)
– petal length (cm)
– petal width (cm)
• Target classes to predict:
– Setosa
– Versicolour
– Virginica
scikit-learn embeds a copy of the iris CSV file along with a function to load it into NumPy arrays:

>>> from sklearn.datasets import load_iris


>>> iris = load_iris()

18.1. Introduction: problem settings 608 18.1. Introduction: problem settings 609
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Exercise: 18.2.2 Supervised Learning: Classification and regression

Can you choose 2 features to find a plot where it is easier to separate the different classes of irises? In Supervised Learning, we have a dataset consisting of both features and labels. The task is to
construct an estimator which is able to predict the label of an object given the set of features. A
Hint: click on the figure above to see the code that generates it, and modify this code. relatively simple example is predicting the species of iris given a set of measurements of its flower. This
is a relatively simple task. Some more complicated examples are:
• given a multicolor image of an object through a telescope, determine whether that object is a star,
18.2 Basic principles of machine learning with scikit-learn a quasar, or a galaxy.
• given a photograph of a person, identify the person in the photo.
18.2.1 Introducing the scikit-learn estimator object • given a list of movies a person has watched and their personal rating of the movie, recommend a
list of movies they would like (So-called recommender systems: a famous example is the Netflix
Every algorithm is exposed in scikit-learn via an ‘’Estimator” object. For instance a linear regression is: Prize).
sklearn.linear_model.LinearRegression

>>> from sklearn.linear_model import LinearRegression Tip: What these tasks have in common is that there is one or more unknown quantities associated
with the object which needs to be determined from other observed quantities.
Estimator parameters: All the parameters of an estimator can be set when it is instantiated:
Supervised learning is further broken down into two categories, classification and regression. In
>>> model = LinearRegression(n_jobs=1) classification, the label is discrete, while in regression, the label is continuous. For example, in astronomy,
>>> print(model) the task of determining whether an object is a star, a galaxy, or a quasar is a classification problem: the
LinearRegression(n_jobs=1) label is from three distinct categories. On the other hand, we might wish to estimate the age of an object
based on such observations: this would be a regression problem, because the label (age) is a continuous
quantity.
Fitting on data
Classification: K nearest neighbors (kNN) is one of the simplest learning strategies: given a new,
Let’s create some simple data with numpy: unknown observation, look up in your reference database which ones have the closest features and assign
the predominant class. Let’s try it out on our iris classification problem:
>>> import numpy as np
>>> x = np.array([0, 1, 2]) from sklearn import neighbors, datasets
>>> y = np.array([0, 1, 2]) iris = datasets.load_iris()
X, y = iris.data, iris.target
>>> X = x[:, np.newaxis] # The input data for sklearn is 2D: (samples == 3 x features␣ knn = neighbors.KNeighborsClassifier(n_neighbors=1)
˓→== 1)
knn.fit(X, y)
>>> X # What kind of iris has 3cm x 5cm sepal and 4cm x 2cm petal?
array([[0], print(iris.target_names[knn.predict([[3, 5, 4, 2]])])
[1],
[2]]) Regression: The simplest possible regression setting is the linear regression one:

from sklearn.linear_model import LinearRegression


>>> model.fit(X, y)
LinearRegression(n_jobs=1) # x from 0 to 30
rng = np.random.default_rng()
Estimated parameters: When data is fitted with an estimator, parameters are estimated from the data x = 30 * rng.random((20, 1))
at hand. All the estimated parameters are attributes of the estimator object ending by an underscore:

>>> model.coef_ # y = a*x + b with noise


array([1.]) y = 0.5 * x + 1.0 + rng.normal(size=x.shape)

# create a linear regression model


model = LinearRegression()
model.fit(x, y)

# predict y from the data


x_new = np.linspace(0, 30, 100)
y_new = model.predict(x_new[:, np.newaxis])

18.2. Basic principles of machine learning with scikit-learn 610 18.2. Basic principles of machine learning with scikit-learn 611
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.2.3 A recap on Scikit-learn’s estimator interface

Scikit-learn strives to have a uniform interface across all methods, and we’ll see examples of these below.
Given a scikit-learn estimator object named model, the following methods are available:
In all Estimators
• model.fit() : fit training data. For supervised learning applications, this accepts
two arguments: the data X and the labels y (e.g. model.fit(X, y)). For unsu-
pervised learning applications, this accepts only a single argument, the data X (e.g.
model.fit(X)).
In supervised estimators
• model.predict() : given a trained model, predict the label of a new set of
data. This method accepts one argument, the new data X_new (e.g. model.
predict(X_new)), and returns the learned label for each object in the array.
• model.predict_proba() : For classification problems, some estimators also pro-
vide this method, which returns the probability that a new observation has each
categorical label. In this case, the label with the highest probability is returned by
model.predict().
• model.score() : for classification or regression problems, most (all?) estimators
implement a score method. Scores are between 0 and 1, with a larger score indicating
a better fit.
In unsupervised estimators
• model.transform() : given an unsupervised model, transform new data into the
new basis. This also accepts one argument X_new, and returns the new representa-
tion of the data based on the unsupervised model.
• model.fit_transform() : some estimators implement this method, which more
efficiently performs a fit and a transform on the same input data.
Fig. 3: A plot of the sepal space and the prediction of the KNN
18.2.4 Regularization: what it is and why it is necessary

Preferring simpler models

Train errors Suppose you are using a 1-nearest neighbor estimator. How many errors do you expect
on your train set?
• Train set error is not a good measurement of prediction performance. You need to leave out a test
set.
• In general, we should accept errors on the train set.
An example of regularization The core idea behind regularization is that we are going to prefer
models that are simpler, for a certain definition of ‘’simpler”, even if they lead to more errors on the
train set.
As an example, let’s generate with a 9th order polynomial, with noise:
And now, let’s fit a 4th order and a 9th order polynomial to the data.
With your naked eyes, which model do you prefer, the 4th order one, or the 9th order one?
Let’s look at the ground truth:

Tip: Regularization is ubiquitous in machine learning. Most scikit-learn estimators have a parameter
to tune the amount of regularization. For instance, with k-NN, it is ‘k’, the number of nearest neighbors
Fig. 4: A plot of a simple linear regression. used to make the decision. k=1 amounts to no regularization: 0 error on the training set, whereas large
k will push toward smoother decision boundaries in the feature space.

18.2. Basic principles of machine learning with scikit-learn 612 18.2. Basic principles of machine learning with scikit-learn 613
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Simple versus complex models for classification

A linear separation A non-linear separation

Tip: For classification models, the decision boundary, that separates the class expresses the complexity
of the model. For instance, a linear model, that makes a decision based on a linear combination of
features, is more complex than a non-linear one.

18.2. Basic principles of machine learning with scikit-learn 614 18.2. Basic principles of machine learning with scikit-learn 615
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.3 Supervised Learning: Classification of Handwritten Digits (continued from previous page)
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest')
18.3.1 The nature of the data

Code and notebook 18.3.2 Visualizing the Data on its principal components

Python code and Jupyter notebook for this section are found here A good first-step for many problems is to visualize the data using a Dimensionality Reduction technique.
We’ll start with the most straightforward one, Principal Component Analysis (PCA).

In this section we’ll apply scikit-learn to the classification of handwritten digits. This will go a bit beyond PCA seeks orthogonal linear combinations of the features which show the greatest variance, and as such,
the iris classification we saw before: we’ll discuss some of the metrics which can be used in evaluating can help give you a good idea of the structure of the data set.
the effectiveness of a classification model.
>>> from sklearn.decomposition import PCA
>>> from sklearn.datasets import load_digits >>> pca = PCA(n_components=2)
>>> digits = load_digits() >>> proj = pca.fit_transform(digits.data)
>>> plt.scatter(proj[:, 0], proj[:, 1], c=digits.target)
<matplotlib.collections.PathCollection object at ...>
>>> plt.colorbar()
<matplotlib.colorbar.Colorbar object at ...>

Question

Given these projections of the data, which numbers do you think a classifier might have trouble
Let us visualize the data and remind us what we’re looking at (click on the figure for the full code): distinguishing?
# plot the digits: each image is 8x8 pixels
for i in range(64):
(continues on next page)

18.3. Supervised Learning: Classification of Handwritten Digits 616 18.3. Supervised Learning: Classification of Handwritten Digits 617
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.3.3 Gaussian Naive Bayes Classification

For most classification problems, it’s nice to have a simple, fast method to provide a quick baseline
classification. If the simple and fast method is sufficient, then we don’t have to waste CPU cycles on
more complex models. If not, we can use the results of the simple method to give us clues about our
data.
One good method to keep in mind is Gaussian Naive Bayes (sklearn.naive_bayes.GaussianNB).

Old scikit-learn versions

train_test_split() is imported from sklearn.cross_validation

Tip: Gaussian Naive Bayes fits a Gaussian distribution to each training label independently on each
feature, and uses this to quickly give a rough classification. It is generally not sufficiently accurate for
real-world data, but can perform surprisingly well, for instance on text data.

>>> from sklearn.naive_bayes import GaussianNB


>>> from sklearn.model_selection import train_test_split

>>> # split the data into training and validation sets


>>> X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)

>>> # train the model


>>> clf = GaussianNB()
>>> clf.fit(X_train, y_train)
GaussianNB()

>>> # use the model to predict the labels of the test data
>>> predicted = clf.predict(X_test)
>>> expected = y_test
>>> print(predicted)
[5 1 7 2 8 9 4 3 9 3 6 2 3 2 6 7 4 3 5 7 5 7 0 1 2 5 9 8 1 8...]
>>> print(expected)
[5 8 7 2 8 9 4 3 7 3 6 2 3 2 6 7 4 3 5 7 5 7 0 1 2 5 3 3 1 8...]
Question
As above, we plot the digits with the predicted labels to get an idea of how well the classification is
working.
Why did we split the data into training and validation sets?

18.3.4 Quantitative Measurement of Performance

We’d like to measure the performance of our estimator without having to resort to plotting examples. A
simple method might be to simply compare the number of matches:

>>> matches = (predicted == expected)


>>> print(matches.sum())
371
>>> print(len(matches))
450
>>> matches.sum() / float(len(matches))
0.82444...

We see that more than 80% of the 450 predictions match the input. But there are other more sophisticated

18.3. Supervised Learning: Classification of Handwritten Digits 618 18.3. Supervised Learning: Classification of Handwritten Digits 619
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

metrics that can be used to judge the performance of a classifier: several are available in the sklearn.
>>> from sklearn.datasets import fetch_california_housing
metrics submodule.
>>> data = fetch_california_housing(as_frame=True)
One of the most useful metrics is the classification_report, which combines several measures and >>> print(data.data.shape)
prints a table with the results: (20640, 8)
>>> print(data.target.shape)
>>> from sklearn import metrics (20640,)
>>> print(metrics.classification_report(expected, predicted))
precision recall f1-score support We can see that there are just over 20000 data points.
0 1.00 0.98 0.99 45 The DESCR variable has a long description of the dataset:
1 0.91 0.66 0.76 44
>>> print(data.DESCR)
2 0.91 0.56 0.69 36
.. _california_housing_dataset:
3 0.89 0.67 0.77 49
4 0.95 0.83 0.88 46
California Housing dataset
5 0.93 0.93 0.93 45
--------------------------
6 0.92 0.98 0.95 47
7 0.75 0.96 0.84 50
**Data Set Characteristics:**
8 0.49 0.97 0.66 39
9 0.85 0.67 0.75 49
:Number of Instances: 20640
accuracy 0.82 450
:Number of Attributes: 8 numeric, predictive attributes and the target
macro avg 0.86 0.82 0.82 450
weighted avg 0.86 0.82 0.83 450
:Attribute Information:
- MedInc median income in block group
Another enlightening metric for this sort of multi-label classification is a confusion matrix: it helps us
- HouseAge median house age in block group
visualize which labels are being interchanged in the classification errors:
- AveRooms average number of rooms per household
>>> print(metrics.confusion_matrix(expected, predicted)) - AveBedrms average number of bedrooms per household
[[44 0 0 0 0 0 0 0 0 1] - Population block group population
[ 0 29 0 0 0 0 1 6 6 2] - AveOccup average number of household members
[ 0 1 20 1 0 0 0 0 14 0] - Latitude block group latitude
[ 0 0 0 33 0 2 0 1 11 2] - Longitude block group longitude
[ 0 0 0 0 38 1 2 4 1 0]
[ 0 0 0 0 0 42 1 0 2 0] :Missing Attribute Values: None
[ 0 0 0 0 0 0 46 0 1 0]
[ 0 0 0 0 1 0 0 48 0 1] This dataset was obtained from the StatLib repository.
[ 0 1 0 0 0 0 0 0 38 0] https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html
[ 0 1 2 3 1 0 0 5 4 33]]
The target variable is the median house value for California districts,
We see here that in particular, the numbers 1, 2, 3, and 9 are often being labeled 8. expressed in hundreds of thousands of dollars ($100,000).

This dataset was derived from the 1990 U.S. census, using one row per census
block group. A block group is the smallest geographical unit for which the U.S.
18.4 Supervised Learning: Regression of Housing Data Census Bureau publishes sample data (a block group typically has a population
of 600 to 3,000 people).
Here we’ll do a short example of a regression problem: learning a continuous value from a set of features.
A household is a group of people residing within a home. Since the average
number of rooms and bedrooms in this dataset are provided per household, these
18.4.1 A quick look at the data columns may take surprisingly large values for block groups with few households
and many empty houses, such as vacation resorts.

Code and notebook It can be downloaded/loaded using the


:func:`sklearn.datasets.fetch_california_housing` function.
Python code and Jupyter notebook for this section are found here
.. topic:: References
We’ll use the California house prices set, available in scikit-learn. This records measurements of 8
attributes of housing markets in California, as well as the median price. The question is: can you predict - Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions,
the price of a new market given its attributes?: Statistics and Probability Letters, 33 (1997) 291-297

18.4. Supervised Learning: Regression of Housing Data 620 18.4. Supervised Learning: Regression of Housing Data 621
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

It often helps to quickly visualize pieces of the data using histograms, scatter plots, or other plot types.
With matplotlib, let us show a histogram of the target values: the median price in each neighborhood:

>>> plt.hist(data.target)
(array([...

Let’s have a quick look to see if some features are more relevant than others for our problem:

>>> for index, feature_name in enumerate(data.feature_names):


... plt.figure()
... plt.scatter(data.data[feature_name], data.target)
<Figure size...

This is a manual version of a technique called feature selection.

Tip: Sometimes, in Machine Learning it is useful to use feature selection to decide which features are
the most useful for a particular problem. Automated methods exist which quantify this sort of exercise
of choosing the most informative features.

18.4. Supervised Learning: Regression of Housing Data 622 18.4. Supervised Learning: Regression of Housing Data 623
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.4.2 Predicting Home Prices: a Simple Linear Regression Solution The solution is found in the code of this chapter

Now we’ll use scikit-learn to perform a simple linear regression on the housing data. There are many
possibilities of regressors to use. A particularly simple one is LinearRegression: this is basically a
wrapper around an ordinary least squares calculation. 18.5 Measuring prediction performance
>>> from sklearn.model_selection import train_test_split
>>> X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) 18.5.1 A quick test on the K-neighbors classifier
>>> from sklearn.linear_model import LinearRegression
>>> clf = LinearRegression() Here we’ll continue to look at the digits data, but we’ll switch to the K-Neighbors classifier. The K-
>>> clf.fit(X_train, y_train) neighbors classifier is an instance-based classifier. The K-neighbors classifier predicts the label of an
LinearRegression() unknown point based on the labels of the K nearest points in the parameter space.
>>> predicted = clf.predict(X_test)
>>> expected = y_test >>> # Get the data
>>> print("RMS: %s " % np.sqrt(np.mean((predicted - expected) ** 2))) >>> from sklearn.datasets import load_digits
RMS: 0.7... >>> digits = load_digits()
>>> X = digits.data
>>> y = digits.target

>>> # Instantiate and train the classifier


>>> from sklearn.neighbors import KNeighborsClassifier
>>> clf = KNeighborsClassifier(n_neighbors=1)
>>> clf.fit(X, y)
KNeighborsClassifier(...)

>>> # Check the results using metrics


>>> from sklearn import metrics
>>> y_pred = clf.predict(X)

>>> print(metrics.confusion_matrix(y_pred, y))


[[178 0 0 0 0 0 0 0 0 0]
[ 0 182 0 0 0 0 0 0 0 0]
[ 0 0 177 0 0 0 0 0 0 0]
[ 0 0 0 183 0 0 0 0 0 0]
[ 0 0 0 0 181 0 0 0 0 0]
[ 0 0 0 0 0 182 0 0 0 0]
We can plot the error: expected as a function of predicted: [ 0 0 0 0 0 0 181 0 0 0]
>>> plt.scatter(expected, predicted) [ 0 0 0 0 0 0 0 179 0 0]
<matplotlib.collections.PathCollection object at ...> [ 0 0 0 0 0 0 0 0 174 0]
[ 0 0 0 0 0 0 0 0 0 180]]

Tip: The prediction at least correlates with the true price, though there are clearly some biases. We Apparently, we’ve found a perfect classifier! But this is misleading for the reasons we saw before: the
could imagine evaluating the performance of the regressor by, say, computing the RMS residuals between classifier essentially “memorizes” all the samples it has already seen. To really test how well this algorithm
the true and predicted price. There are some subtleties in this, however, which we’ll cover in a later does, we need to try some samples it hasn’t yet seen.
section. This problem also occurs with regression models. In the following we fit an other instance-based model
named “decision tree” to the California Housing price dataset we introduced previously:

>>> from sklearn.datasets import fetch_california_housing


Exercise: Gradient Boosting Tree Regression
>>> from sklearn.tree import DecisionTreeRegressor
There are many other types of regressors available in scikit-learn: we’ll try a more powerful one here.
>>> data = fetch_california_housing(as_frame=True)
Use the GradientBoostingRegressor class to fit the housing data. >>> clf = DecisionTreeRegressor().fit(data.data, data.target)
>>> predicted = clf.predict(data.data)
hint You can copy and paste some of the above code, replacing LinearRegression with
>>> expected = data.target
GradientBoostingRegressor:
from sklearn.ensemble import GradientBoostingRegressor >>> plt.scatter(expected, predicted)
# Instantiate the model, fit the results, and scatter in vs. out <matplotlib.collections.PathCollection object at ...>
(continues on next page)

18.4. Supervised Learning: Regression of Housing Data 624 18.5. Measuring prediction performance 625
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


>>> plt.plot([0, 50], [0, 50], '--k')
[<matplotlib.lines.Line2D object at ...] >>> print(metrics.confusion_matrix(y_test, y_pred))
[[37 0 0 0 0 0 0 0 0 0]
[ 0 43 0 0 0 0 0 0 0 0]
[ 0 0 43 1 0 0 0 0 0 0]
[ 0 0 0 45 0 0 0 0 0 0]
[ 0 0 0 0 38 0 0 0 0 0]
[ 0 0 0 0 0 47 0 0 0 1]
[ 0 0 0 0 0 0 52 0 0 0]
[ 0 0 0 0 0 0 0 48 0 0]
[ 0 0 0 0 0 0 0 0 48 0]
[ 0 0 0 1 0 1 0 0 0 45]]
>>> print(metrics.classification_report(y_test, y_pred))
precision recall f1-score support

0 1.00 1.00 1.00 37


1 1.00 1.00 1.00 43
2 1.00 0.98 0.99 44
3 0.96 1.00 0.98 45
4 1.00 1.00 1.00 38
5 0.98 0.98 0.98 48
6 1.00 1.00 1.00 52
Here again the predictions are seemingly perfect as the model was able to perfectly memorize the training 7 1.00 1.00 1.00 48
set. 8 1.00 1.00 1.00 48
9 0.98 0.96 0.97 47
Warning: Performance on test set
accuracy 0.99 450
Performance on test set does not measure overfit (as described above) macro avg 0.99 0.99 0.99 450
weighted avg 0.99 0.99 0.99 450

18.5.2 A correct approach: Using a validation set The averaged f1-score is often used as a convenient measure of the overall performance of an algorithm.
It appears in the bottom row of the classification report; it can also be accessed directly:
Learning the parameters of a prediction function and testing it on the same data is a methodological >>> metrics.f1_score(y_test, y_pred, average="macro")
mistake: a model that would just repeat the labels of the samples that it has just seen would have a 0.991367...
perfect score but would fail to predict anything useful on yet-unseen data.
To avoid over-fitting, we have to define two different sets: The over-fitting we saw previously can be quantified by computing the f1-score on the training data
itself:
• a training set X_train, y_train which is used for learning the parameters of a predictive model
• a testing set X_test, y_test which is used for evaluating the fitted predictive model >>> metrics.f1_score(y_train, clf.predict(X_train), average="macro")
1.0
In scikit-learn such a random split can be quickly computed with the train_test_split() function:

>>> from sklearn import model_selection


Note: Regression metrics In the case of regression models, we need to use different metrics, such as
>>> X = digits.data
explained variance.
>>> y = digits.target

>>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y,


... test_size=0.25, random_state=0)

>>> print("%r , %r , %r " % (X.shape, X_train.shape, X_test.shape))


(1797, 64), (1347, 64), (450, 64)

Now we train on the training data, and test on the testing data:

>>> clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train)


>>> y_pred = clf.predict(X_test)
(continues on next page)

18.5. Measuring prediction performance 626 18.5. Measuring prediction performance 627
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.5.3 Model Selection via Validation 18.5.4 Cross-validation

Cross-validation consists in repeatedly splitting the data in pairs of train and test sets, called ‘folds’.
Tip: We have applied Gaussian Naives, support vectors machines, and K-nearest neighbors classifiers Scikit-learn comes with a function to automatically compute score on all these folds. Here we do KFold
to the digits dataset. Now that we have these validation tools in place, we can ask quantitatively which with k=5.
of the three estimators works best for this dataset.
>>> clf = KNeighborsClassifier()
>>> from sklearn.model_selection import cross_val_score
• With the default hyper-parameters for each estimator, which gives the best f1 score on the valida- >>> cross_val_score(clf, X, y, cv=5)
tion set? Recall that hyperparameters are the parameters set when you instantiate the classifier: array([0.947..., 0.955..., 0.966..., 0.980..., 0.963... ])
for example, the n_neighbors in clf = KNeighborsClassifier(n_neighbors=1)

>>> from sklearn.naive_bayes import GaussianNB We can use different splitting strategies, such as random splitting:
>>> from sklearn.neighbors import KNeighborsClassifier >>> from sklearn.model_selection import ShuffleSplit
>>> from sklearn.svm import LinearSVC >>> cv = ShuffleSplit(n_splits=5)
>>> cross_val_score(clf, X, y, cv=cv)
>>> X = digits.data array([...])
>>> y = digits.target
>>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y,
... test_size=0.25, random_state=0) Tip: There exists many different cross-validation strategies in scikit-learn. They are often useful to
take in account non iid datasets.
>>> for Model in [GaussianNB(), KNeighborsClassifier(), LinearSVC(dual=False)]:
... clf = Model.fit(X_train, y_train)
... y_pred = clf.predict(X_test)
... print('%s : %s ' % 18.5.5 Hyperparameter optimization with cross-validation
... (Model.__class__.__name__, metrics.f1_score(y_test, y_pred,␣
˓→average="macro")))
Consider regularized linear models, such as Ridge Regression, which uses l2 regularization, and Lasso
GaussianNB: 0.8... Regression, which uses l1 regularization. Choosing their regularization parameter is important.
KNeighborsClassifier: 0.9...
LinearSVC: 0.9... Let us set these parameters on the Diabetes dataset, a simple regression problem. The diabetes data
consists of 10 physiological variables (age, sex, weight, blood pressure) measure on 442 patients, and an
• For each classifier, which value for the hyperparameters gives the best results for the digits data? indication of disease progression after one year:
For LinearSVC, use loss='l2' and loss='l1'. For KNeighborsClassifier we use n_neighbors
>>> from sklearn.datasets import load_diabetes
between 1 and 10. Note that GaussianNB does not have any adjustable hyperparameters.
>>> data = load_diabetes()
LinearSVC(loss='l1'): 0.930570687535 >>> X, y = data.data, data.target
LinearSVC(loss='l2'): 0.933068826918 >>> print(X.shape)
------------------- (442, 10)
KNeighbors(n_neighbors=1): 0.991367521884
KNeighbors(n_neighbors=2): 0.984844206884 With the default hyper-parameters: we compute the cross-validation score:
KNeighbors(n_neighbors=3): 0.986775344954
>>> from sklearn.linear_model import Ridge, Lasso
KNeighbors(n_neighbors=4): 0.980371905382
KNeighbors(n_neighbors=5): 0.980456280495
>>> for Model in [Ridge, Lasso]:
KNeighbors(n_neighbors=6): 0.975792419414
... model = Model()
KNeighbors(n_neighbors=7): 0.978064579214
... print('%s : %s ' % (Model.__name__, cross_val_score(model, X, y).mean()))
KNeighbors(n_neighbors=8): 0.978064579214
Ridge: 0.4...
KNeighbors(n_neighbors=9): 0.978064579214
Lasso: 0.3...
KNeighbors(n_neighbors=10): 0.975555089773

Solution: code source

18.5. Measuring prediction performance 628 18.5. Measuring prediction performance 629
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Basic Hyperparameter Optimization (continued from previous page)


RidgeCV: 0.0621016941892
We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso LassoCV: 0.0126896100317
and Ridge. We choose 20 values of alpha between 0.0001 and 1:
We see that the results match those returned by GridSearchCV
>>> alphas = np.logspace(-3, -1, 30)

>>> for Model in [Lasso, Ridge]: Nested cross-validation


... scores = [cross_val_score(Model(alpha), X, y, cv=3).mean()
... for alpha in alphas] How do we measure the performance of these estimators? We have used data to set the hyperparameters,
... plt.plot(alphas, scores, label=Model.__name__) so we need to test on actually new data. We can do this by running cross_val_score() on our CV
[<matplotlib.lines.Line2D object at ... objects. Here there are 2 cross-validation loops going on, this is called ‘nested cross validation’:

for Model in [RidgeCV, LassoCV]:


scores = cross_val_score(Model(alphas=alphas, cv=3), X, y, cv=3)
print(Model.__name__, np.mean(scores))

Note: Note that these results do not match the best results of our curves above, and LassoCV seems
to under-perform RidgeCV. The reason is that setting the hyper-parameter is harder for Lasso, thus the
estimation error on this hyper-parameter is larger.

18.6 Unsupervised Learning: Dimensionality Reduction and Visual-


ization
Question
Unsupervised learning is applied on X without y: data without labels. A typical use case is to find
Can we trust our results to be actually useful? hidden structure in the data.

18.6.1 Dimensionality Reduction: PCA


Automatically Performing Grid Search
Dimensionality reduction derives a set of new artificial features smaller than the original feature set.
sklearn.grid_search.GridSearchCV is constructed with an estimator, as well as a dictionary of pa- Here we’ll use Principal Component Analysis (PCA), a dimensionality reduction that strives to retain
rameter values to be searched. We can find the optimal parameters this way: most of the variance of the original data. We’ll use sklearn.decomposition.PCA on the iris dataset:
>>> from sklearn.model_selection import GridSearchCV >>> X = iris.data
>>> for Model in [Ridge, Lasso]: >>> y = iris.target
... gscv = GridSearchCV(Model(), dict(alpha=alphas), cv=3).fit(X, y)
... print('%s : %s ' % (Model.__name__, gscv.best_params_))
Ridge: {'alpha': 0.062101694189156162} Tip: PCA computes linear combinations of the original features using a truncated Singular Value
Lasso: {'alpha': 0.01268961003167922} Decomposition of the matrix X, to project the data onto a base of the top singular vectors.

Built-in Hyperparameter Search >>> from sklearn.decomposition import PCA


>>> pca = PCA(n_components=2, whiten=True)
For some models within scikit-learn, cross-validation can be performed more efficiently on large datasets. >>> pca.fit(X)
In this case, a cross-validated version of the particular model is included. The cross-validated versions PCA(n_components=2, whiten=True)
of Ridge and Lasso are RidgeCV and LassoCV, respectively. Parameter search on these estimators can
be performed as follows: Once fitted, PCA exposes the singular vectors in the components_ attribute:

>>> from sklearn.linear_model import RidgeCV, LassoCV >>> pca.components_


>>> for Model in [RidgeCV, LassoCV]: array([[ 0.3..., -0.08..., 0.85..., 0.3...],
... model = Model(alphas=alphas, cv=3).fit(X, y) [ 0.6..., 0.7..., -0.1..., -0.07...]])
... print('%s : %s ' % (Model.__name__, model.alpha_))
(continues on next page) Other attributes are available as well:

18.5. Measuring prediction performance 630 18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 631
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

>>> pca.explained_variance_ratio_
18.6.2 Visualization with a non-linear embedding: tSNE
array([0.92..., 0.053...])
For visualization, more complex embeddings can be useful (for statistical analysis, they are harder to
control). sklearn.manifold.TSNE is such a powerful manifold learning method. We apply it to the digits
Let us project the iris dataset along those first two dimensions::
dataset, as the digits are vectors of dimension 8*8 = 64. Embedding them in 2D enables visualization:
>>> X_pca = pca.transform(X)
>>> # Take the first 500 data points: it's hard to see 1500 points
>>> X_pca.shape
>>> X = digits.data[:500]
(150, 2)
>>> y = digits.target[:500]
PCA normalizes and whitens the data, which means that the data is now centered on both components >>> # Fit and transform with a TSNE
with unit variance: >>> from sklearn.manifold import TSNE
>>> X_pca.mean(axis=0) >>> tsne = TSNE(n_components=2, learning_rate='auto', init='random', random_state=0)
array([...e-15, ...e-15]) >>> X_2d = tsne.fit_transform(X)
>>> X_pca.std(axis=0, ddof=1)
array([1., 1.]) >>> # Visualize the data
>>> plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y)
<matplotlib.collections.PathCollection object at ...>
Furthermore, the samples components do no longer carry any linear correlation:

>>> np.corrcoef(X_pca.T)
array([[1.00000000e+00, 0.0],
[0.0, 1.00000000e+00]])

With a number of retained components 2 or 3, PCA is useful to visualize the dataset:

>>> target_ids = range(len(iris.target_names))


>>> for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names):
... plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1],
... c=c, label=label)
<matplotlib.collections.PathCollection ...

fit_transform

As TSNE cannot be applied to new data, we need to use its fit_transform method.

sklearn.manifold.TSNE separates quite well the different classes of digits even though it had no access
to the class information.

Tip: Note that this projection was determined without any information about the labels (represented
Exercise: Other dimension reduction of digits
by the colors): this is the sense in which the learning is unsupervised. Nevertheless, we see that the
projection gives us insight into the distribution of the different flowers in parameter space: notably, iris
sklearn.manifold has many other non-linear embeddings. Try them out on the digits dataset. Could
setosa is much more distinct than the other two species.

18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 632 18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 633
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

you judge their quality without knowing the labels y?


>>> from sklearn.datasets import load_digits
>>> digits = load_digits()
>>> # ...

18.7 Parameter selection, Validation, and Testing

18.7.1 Hyperparameters, Over-fitting, and Under-fitting

See also:
[<matplotlib.lines.Line2D object at 0x7f494c1f3bd0>]
This section is adapted from Andrew Ng’s excellent Coursera course
The issues associated with validation and cross-validation are some of the most important aspects of the In real life situation, we have noise (e.g. measurement noise) in our data:
practice of machine learning. Selecting the optimal model for your data is vital, and is a piece of the rng = np.random.default_rng(27446968)
problem that is not often appreciated by machine learning practitioners. for _ in range(6):
The central question is: If our estimator is underperforming, how should we move forward? noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
• Use simpler or more complicated model? regr.fit(noisy_X, y)
• Add more features to each observed data point? plt.plot(X_test, regr.predict(X_test))
• Add more training samples?
The answer is often counter-intuitive. In particular, Sometimes using a more complicated model
will give worse results. Also, Sometimes adding training data will not improve your results.
The ability to determine what steps will improve your model is what separates the successful machine
learning practitioners from the unsuccessful.

Bias-variance trade-off: illustration on a simple regression problem

Code and notebook

Python code and Jupyter notebook for this section are found here
As we can see, our linear model captures and amplifies the noise in the data. It displays a lot of variance.
Let us start with a simple 1D regression problem. This will help us to easily visualize the data and the We can use another linear estimator that uses regularization, the Ridge estimator. This estimator
model, and the results generalize easily to higher-dimensional datasets. We’ll explore a simple linear regularizes the coefficients by shrinking them to zero, under the assumption that very high correlations
regression problem, with sklearn.linear_model. are often spurious. The alpha parameter controls the amount of shrinkage used.

X = np.c_[0.5, 1].T regr = linear_model.Ridge(alpha=0.1)


y = [0.5, 1] np.random.seed(0)
X_test = np.c_[0, 2].T for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
Without noise, as linear regression fits the data perfectly plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y)
from sklearn import linear_model plt.plot(X_test, regr.predict(X_test))

regr = linear_model.LinearRegression() plt.show()


regr.fit(X, y)
plt.plot(X, y, "o")
plt.plot(X_test, regr.predict(X_test))

18.7. Parameter selection, Validation, and Testing 634 18.7. Parameter selection, Validation, and Testing 635
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

In the middle, for d = 2, we have found a good mid-point. It fits the data fairly well, and does not suffer
from the bias and variance problems seen in the figures on either side. What we would like is a way to
quantitatively identify bias and variance, and optimize the metaparameters (in this case, the polynomial
degree d) in order to determine the best algorithm.

Polynomial regression with scikit-learn

A polynomial regression is built by pipelining PolynomialFeatures and a LinearRegression:


>>> from sklearn.pipeline import make_pipeline
>>> from sklearn.preprocessing import PolynomialFeatures
>>> from sklearn.linear_model import LinearRegression
As we can see, the estimator displays much less variance. However it systematically under-estimates the >>> model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())
coefficient. It displays a biased behavior.
This is a typical example of bias/variance tradeof : non-regularized estimator are not biased, but they
can display a lot of variance. Highly-regularized models have little variance, but high bias. This bias is
not necessarily a bad thing: what matters is choosing the tradeoff between bias and variance that leads Validation Curves
to the best prediction performance. For a specific dataset there is a sweet spot corresponding to the
highest complexity that the data can support, depending on the amount of noise and of observations Let us create a dataset like in the example above:
available.
>>> def generating_func(x, rng, err=0.5):
... return rng.normal(10 - 1. / (x + 0.1), err)
18.7.2 Visualizing the Bias/Variance Tradeoff
>>> # randomly sample more data
>>> rng = np.random.default_rng(27446968)
Tip: Given a particular dataset and a model (e.g. a polynomial), we’d like to understand whether bias >>> x = rng.random(size=200)
(underfit) or variance limits prediction, and how to tune the hyperparameter (here d, the degree of the >>> y = generating_func(x, err=1., rng=rng)
polynomial) to give the best fit.

On a given data, let us fit a simple polynomial regression model with varying degrees:

Central to quantify bias and variance of a model is to apply it on test data, sampled from the same
distribution as the train, but that will capture independent noise:

>>> xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.4)

Tip: In the above figure, we see fits for three different values of d. For d = 1, the data is under-fit. Validation curve A validation curve consists in varying a model parameter that controls its complexity
This means that the model is too simplistic: no straight line will ever be a good fit to this data. In this (here the degree of the polynomial) and measures both error of the model on training data, and on test
case, we say that the model suffers from high bias. The model itself is biased, and this will be reflected data (eg with cross-validation). The model parameter is then adjusted so that the test error is minimized:
in the fact that the data is poorly fit. At the other extreme, for d = 6 the data is over-fit. This means
that the model has too many free parameters (6 in this case) which can be adjusted to perfectly fit the We use sklearn.model_selection.validation_curve() to compute train and test error, and plot it:
training data. If we add a new point to this plot, though, chances are it will be very far from the curve
>>> from sklearn.model_selection import validation_curve
representing the degree-6 fit. In this case, we say that the model suffers from high variance. The reason
for the term “high variance” is that if any of the input points are varied slightly, it could result in a very
>>> degrees = np.arange(1, 21)
different model.
(continues on next page)

18.7. Parameter selection, Validation, and Testing 636 18.7. Parameter selection, Validation, and Testing 637
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) Learning Curves

>>> model = make_pipeline(PolynomialFeatures(), LinearRegression()) A learning curve shows the training and validation score as a function of the number of training points.
Note that when we train on a subset of the training data, the training score is computed using this
>>> # Vary the "degrees" on the pipeline step "polynomialfeatures" subset, not the full training set. This curve gives a quantitative view into how beneficial it will be to
>>> train_scores, validation_scores = validation_curve( add training samples.
... model, x[:, np.newaxis], y,
... param_name='polynomialfeatures__degree', Questions:
... param_range=degrees)
• As the number of training samples are increased, what do you expect to see for the training
>>> # Plot the mean train score and validation score across folds score? For the validation score?
>>> plt.plot(degrees, validation_scores.mean(axis=1), label='cross-validation')
[<matplotlib.lines.Line2D object at ...>] • Would you expect the training score to be higher or lower than the validation score? Would you
>>> plt.plot(degrees, train_scores.mean(axis=1), label='training') ever expect this to change?
[<matplotlib.lines.Line2D object at ...>]
>>> plt.legend(loc='best') scikit-learn provides sklearn.model_selection.learning_curve():
<matplotlib.legend.Legend object at ...>
>>> from sklearn.model_selection import learning_curve
>>> train_sizes, train_scores, validation_scores = learning_curve(
... model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20))

>>> # Plot the mean train score and validation score across folds
>>> plt.plot(train_sizes, validation_scores.mean(axis=1), label='cross-validation')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(train_sizes, train_scores.mean(axis=1), label='training')
[<matplotlib.lines.Line2D object at ...>]

This figure shows why validation is important. On the left side of the plot, we have very low-degree
polynomial, which under-fit the data. This leads to a low explained variance for both the training set
and the validation set. On the far right side of the plot, we have a very high degree polynomial, which
over-fits the data. This can be seen in the fact that the training explained variance is very high, while
on the validation set, it is low. Choosing d around 4 or 5 gets us the best tradeoff.

Tip: The astute reader will realize that something is amiss here: in the above plot, d = 4 gives the
best results. But in the previous plot, we found that d = 6 vastly over-fits the data. What’s going on
here? The difference is the number of training points used. In the previous example, there were only
eight training points. In this example, we have 100. As a general rule of thumb, the more training points Fig. 5: For a degree=1 model
used, the more complicated model can be used. But how can you determine for a given model whether
more training points will be helpful? A useful diagnostic for this are learning curves.
Note that the validation score generally increases with a growing training set, while the training score
generally decreases with a growing training set. As the training size increases, they will converge to a
single value.
From the above discussion, we know that d = 1 is a high-bias estimator which under-fits the data. This
is indicated by the fact that both the training and validation scores are low. When confronted with this
type of learning curve, we can expect that adding more training data will not help: both lines converge
to a relatively low score.

When the learning curves have converged to a low score, we have a high bias model.
A high-bias model can be improved by:

18.7. Parameter selection, Validation, and Testing 638 18.7. Parameter selection, Validation, and Testing 639
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• Using a more sophisticated model (i.e. in this case, increase d) High Bias
• Gather more features for each sample.
If a model shows high bias, the following actions might help:
• Decrease regularization in a regularized model.
• Add more features. In our example of predicting home prices, it may be helpful to make use of
Increasing the number of samples, however, does not improve a high-bias model. information such as the neighborhood the house is in, the year the house was built, the size of the
lot, etc. Adding these features to the training and test sets can improve a high-bias estimator
Now let’s look at a high-variance (i.e. over-fit) model:
• Use a more sophisticated model. Adding complexity to the model can help improve on bias.
For a polynomial fit, this can be accomplished by increasing the degree d. Each learning technique
has its own methods of adding complexity.
• Use fewer samples. Though this will not improve the classification, a high-bias algorithm can
attain nearly the same error with a smaller training sample. For algorithms which are compu-
tationally expensive, reducing the training sample size can lead to very large improvements in
speed.
• Decrease regularization. Regularization is a technique used to impose simplicity in some ma-
chine learning models, by adding a penalty term that depends on the characteristics of the param-
eters. If a model has high bias, decreasing the effect of regularization can lead to better results.

High Variance

If a model shows high variance, the following actions might help:

Fig. 6: For a degree=15 model • Use fewer features. Using a feature selection technique may be useful, and decrease the over-
fitting of the estimator.
• Use a simpler model. Model complexity and over-fitting go hand-in-hand.
Here we show the learning curve for d = 15. From the above discussion, we know that d = 15 is a
high-variance estimator which over-fits the data. This is indicated by the fact that the training score • Use more training samples. Adding training samples can reduce the effect of over-fitting, and
is much higher than the validation score. As we add more samples to this training set, the training score lead to improvements in a high variance estimator.
will continue to decrease, while the cross-validation error will continue to increase, until they meet in
• Increase Regularization. Regularization is designed to prevent over-fitting. In a high-variance
the middle.
model, increasing regularization can lead to better results.
These choices become very important in real-world situations. For example, due to limited telescope
Learning curves that have not yet converged with the full training set indicate a high- time, astronomers must seek a balance between observing a large number of objects, and observing a
variance, over-fit model. large number of features for each object. Determining which is more important for a particular learning
task can inform the observing strategy that the astronomer employs.
A high-variance model can be improved by:
• Gathering more training samples.
18.7.4 A last word of caution: separate validation and test set
• Using a less-sophisticated model (i.e. in this case, make d smaller)
• Increasing regularization. Using validation schemes to determine hyper-parameters means that we are fitting the hyper-parameters
to the particular validation set. In the same way that parameters can be over-fit to the training set,
In particular, gathering more features for each sample will not help the results. hyperparameters can be over-fit to the validation set. Because of this, the validation error tends to
under-predict the classification error of new data.
18.7.3 Summary on model selection For this reason, it is recommended to split the data into three sets:
• The training set, used to train the model (usually ~60% of the data)
We’ve seen above that an under-performing algorithm can be due to two possible situations: high
bias (under-fitting) and high variance (over-fitting). In order to evaluate our algorithm, we set aside • The validation set, used to validate the model (usually ~20% of the data)
a portion of our training data for cross-validation. Using the technique of learning curves, we can
• The test set, used to evaluate the expected error of the validated model (usually ~20% of the
train on progressively larger subsets of the data, evaluating the training error and cross-validation error
data)
to determine whether our algorithm has high variance or high bias. But what do we do with this
information? Many machine learning practitioners do not separate test set and validation set. But if your goal is to
gauge the error of a model on unknown data, using an independent test set is vital.

18.7. Parameter selection, Validation, and Testing 640 18.7. Parameter selection, Validation, and Testing 641
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8 Examples for the scikit-learn chapter

18.8.1 Demo PCA in 2D

Load the iris data

from sklearn import datasets

iris = datasets.load_iris()
X = iris.data
y = iris.target

Fit a PCA

from sklearn.decomposition import PCA

pca = PCA(n_components=2, whiten=True)


pca.fit(X)

Project the data in 2D

X_pca = pca.transform(X)

Visualize the data

target_ids = range(len(iris.target_names))

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 5))
for i, c, label in zip(target_ids, "rgbcmykw", iris.target_names, strict=False):
plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) Total running time of the script: (0 minutes 0.110 seconds)
plt.legend()
plt.show()

18.8.2 Measuring Decision Tree performance

Demonstrates overfit when testing on train set.


Get the data

from sklearn.datasets import fetch_california_housing

data = fetch_california_housing(as_frame=True)

Train and test a model

from sklearn.tree import DecisionTreeRegressor

clf = DecisionTreeRegressor().fit(data.data, data.target)

predicted = clf.predict(data.data)
expected = data.target

Plot predicted as a function of expected

import matplotlib.pyplot as plt

(continues on next page)

18.8. Examples for the scikit-learn chapter 642 18.8. Examples for the scikit-learn chapter 643
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


plt.figure(figsize=(4, 3))
plt.scatter(expected, predicted)
plt.plot([0, 5], [0, 5], "--k")
plt.axis("tight")
plt.xlabel("True price ($100k)")
plt.ylabel("Predicted price ($100k)")
plt.tight_layout()

# Load the data


from sklearn.datasets import load_iris

Pretty much no errors! iris = load_iris()


This is too good to be true: we are testing the model on the train data, which is not a measure of
import matplotlib.pyplot as plt
generalization.
The results are not valid # The indices of the features that we are plotting
x_index = 0
Total running time of the script: (0 minutes 1.482 seconds)
y_index = 1

# this formatter will label the colorbar with the correct target names
formatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])
18.8.3 Plot 2D views of the iris dataset
plt.figure(figsize=(5, 4))
Plot a simple scatter plot of 2 features of the iris dataset. plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)
Note that more elaborate visualization of this dataset is detailed in the Statistics in Python chapter. plt.colorbar(ticks=[0, 1, 2], format=formatter)
plt.xlabel(iris.feature_names[x_index])
plt.ylabel(iris.feature_names[y_index])

plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 0.112 seconds)

18.8. Examples for the scikit-learn chapter 644 18.8. Examples for the scikit-learn chapter 645
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.4 A simple linear regression 18.8.5 tSNE to visualize digits

Here we use sklearn.manifold.TSNE to visualize the digits datasets. Indeed, the digits are vectors in
a 8*8 = 64 dimensional space. We want to project them in 2D for visualization. tSNE is often a good
solution, as it groups and separates data points based on their local relationship.
Load the iris data

from sklearn import datasets

digits = datasets.load_digits()
# Take the first 500 data points: it's hard to see 1500 points
X = digits.data[:500]
y = digits.target[:500]

Fit and transform with a TSNE

from sklearn.manifold import TSNE

tsne = TSNE(n_components=2, random_state=0)

Project the data in 2D


import numpy as np
import matplotlib.pyplot as plt X_2d = tsne.fit_transform(X)
from sklearn.linear_model import LinearRegression
Visualize the data
# x from 0 to 30
target_ids = range(len(digits.target_names))
rng = np.random.default_rng()
x = 30 * rng.random((20, 1))
import matplotlib.pyplot as plt
# y = a*x + b with noise
plt.figure(figsize=(6, 5))
y = 0.5 * x + 1.0 + rng.normal(size=x.shape)
colors = "r", "g", "b", "c", "m", "y", "k", "w", "orange", "purple"
for i, c, label in zip(target_ids, colors, digits.target_names, strict=True):
# create a linear regression model
plt.scatter(X_2d[y == i, 0], X_2d[y == i, 1], c=c, label=label)
model = LinearRegression()
plt.legend()
model.fit(x, y)
plt.show()
# predict y from the data
x_new = np.linspace(0, 30, 100)
y_new = model.predict(x_new[:, np.newaxis])

# plot the results


plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.scatter(x, y)
ax.plot(x_new, y_new)

ax.set_xlabel("x")
ax.set_ylabel("y")

ax.axis("tight")

plt.show()

Total running time of the script: (0 minutes 0.056 seconds)

18.8. Examples for the scikit-learn chapter 646 18.8. Examples for the scikit-learn chapter 647
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Ridge: 0.410174971340889
Lasso: 0.3375593674654274

We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso
and Ridge

import numpy as np
import matplotlib.pyplot as plt

alphas = np.logspace(-3, -1, 30)

plt.figure(figsize=(5, 3))

for Model in [Lasso, Ridge]:


scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for alpha in alphas]
plt.plot(alphas, scores, label=Model.__name__)

plt.legend(loc="lower left")
plt.xlabel("alpha")
plt.ylabel("cross validation score")
plt.tight_layout()
plt.show()

Total running time of the script: (0 minutes 1.176 seconds)

18.8.6 Use the RidgeCV and LassoCV to set the regularization parameter

Load the diabetes dataset

from sklearn.datasets import load_diabetes

data = load_diabetes()
X, y = data.data, data.target Total running time of the script: (0 minutes 0.349 seconds)
print(X.shape)

(442, 10)
18.8.7 Plot variance and regularization in linear models
Compute the cross-validation score with the default hyper-parameters

from sklearn.model_selection import cross_val_score import numpy as np


from sklearn.linear_model import Ridge, Lasso
# Smaller figures
for Model in [Ridge, Lasso]: import matplotlib.pyplot as plt
model = Model()
print(f"{ Model.__name__} : { cross_val_score(model, X, y).mean()} ") plt.rcParams["figure.figsize"] = (3, 2)

We consider the situation where we have only 2 data point

18.8. Examples for the scikit-learn chapter 648 18.8. Examples for the scikit-learn chapter 649
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


X = np.c_[0.5, 1].T
y = [0.5, 1] for _ in range(6):
X_test = np.c_[0, 2].T noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
Without noise, as linear regression fits the data perfectly regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))
from sklearn import linear_model
plt.show()
regr = linear_model.LinearRegression()
regr.fit(X, y)
plt.plot(X, y, "o")
plt.plot(X_test, regr.predict(X_test))

Total running time of the script: (0 minutes 0.103 seconds)

[<matplotlib.lines.Line2D object at 0x7f494c1f3bd0>] 18.8.8 Simple picture of the formal problem of machine learning

In real life situation, we have noise (e.g. measurement noise) in our data: This example generates simple synthetic data ploints and shows a separating hyperplane on them.

rng = np.random.default_rng(27446968)
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))

import numpy as np
As we can see, our linear model captures and amplifies the noise in the data. It displays a lot of variance. import matplotlib.pyplot as plt
from sklearn.linear_model import SGDClassifier
We can use another linear estimator that uses regularization, the Ridge estimator. This estimator
from sklearn.datasets import make_blobs
regularizes the coefficients by shrinking them to zero, under the assumption that very high correlations
are often spurious. The alpha parameter controls the amount of shrinkage used.
# we create 50 separable synthetic points
regr = linear_model.Ridge(alpha=0.1) X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
np.random.seed(0)
(continues on next page) (continues on next page)

18.8. Examples for the scikit-learn chapter 650 18.8. Examples for the scikit-learn chapter 651
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


# fit the model LinearSVC(loss='hinge'): 0.9294570108037394
clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True) /opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_
clf.fit(X, Y) ˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣

˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.

# plot the line, the points, and the nearest vectors to the plane warnings.warn(
xx = np.linspace(-1, 5, 10) /opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
yy = np.linspace(-1, 5, 10) ˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣

˓→iterations.

X1, X2 = np.meshgrid(xx, yy) warnings.warn(


Z = np.empty(X1.shape) LinearSVC(loss='squared_hinge'): 0.9341371852581549
for (i, j), val in np.ndenumerate(X1): -------------------
x1 = val KNeighbors(n_neighbors=1): 0.9913675218842191
x2 = X2[i, j] KNeighbors(n_neighbors=2): 0.9848442068835102
p = clf.decision_function([[x1, x2]]) KNeighbors(n_neighbors=3): 0.9867753449543099
Z[i, j] = p[0] KNeighbors(n_neighbors=4): 0.9803719053818863
KNeighbors(n_neighbors=5): 0.9804562804949924
plt.figure(figsize=(4, 3)) KNeighbors(n_neighbors=6): 0.9757924194139573
ax = plt.axes() KNeighbors(n_neighbors=7): 0.9780645792142071
ax.contour( KNeighbors(n_neighbors=8): 0.9780645792142071
X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] KNeighbors(n_neighbors=9): 0.9780645792142071
) KNeighbors(n_neighbors=10): 0.9755550897728812
ax.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)

ax.axis("tight")

plt.show()
from sklearn import model_selection, datasets, metrics
Total running time of the script: (0 minutes 0.049 seconds) from sklearn.svm import LinearSVC
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier

digits = datasets.load_digits()
18.8.9 Compare classifiers on the digits data X = digits.data
y = digits.target
Compare the performance of a variety of classifiers on a test set for the digits data. X_train, X_test, y_train, y_test = model_selection.train_test_split(
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_ X, y, test_size=0.25, random_state=0
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣
)
˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.

warnings.warn( for Model in [LinearSVC, GaussianNB, KNeighborsClassifier]:


/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base. clf = Model().fit(X_train, y_train)
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣
y_pred = clf.predict(X_test)
˓→iterations.
print(f"{ Model.__name__} : { metrics.f1_score(y_test, y_pred, average='macro')} ")
warnings.warn(
LinearSVC: 0.9341800269333108 print("------------------")
GaussianNB: 0.8332741681010102
KNeighborsClassifier: 0.9804562804949924 # test SVC loss
------------------ for loss in ["hinge", "squared_hinge"]:
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_ clf = LinearSVC(loss=loss).fit(X_train, y_train)
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣
y_pred = clf.predict(X_test)
˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.
print(
warnings.warn( f"LinearSVC(loss='{ loss} '): { metrics.f1_score(y_test, y_pred, average='macro
˓→')} "
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣
)
˓→iterations.

warnings.warn( print("-------------------")
(continues on next page) (continues on next page)

18.8. Examples for the scikit-learn chapter 652 18.8. Examples for the scikit-learn chapter 653
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)

# test the number of neighbors


for n_neighbors in range(1, 11):
clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(X_train, y_train)
y_pred = clf.predict(X_test)
print(
f"KNeighbors(n_neighbors={ n_neighbors} ): { metrics.f1_score(y_test, y_pred,␣
˓→average='macro')} "

Total running time of the script: (0 minutes 0.412 seconds)

18.8.10 Plot fitting a 9th order polynomial

Fits data generated from a 9th order polynomial with model of 4th order and 9th order polynomials, to
demonstrate that often simpler models are to be preferred

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

from sklearn import linear_model


<matplotlib.collections.PathCollection object at 0x7f494ca99690>
# Create color maps for 3-class classification problem, as with iris
cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"]) Fitting 4th and 9th order polynomials
cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"]) For this we need to engineer features: the n_th powers of x:

plt.figure(figsize=(6, 4))
rng = np.random.default_rng(27446968) plt.scatter(x, y, s=4)
x = 2 * rng.random(100) - 1
X = np.array([x**i for i in range(5)]).T
f = lambda t: 1.2 * t**2 + 0.1 * t**3 - 0.4 * t**5 - 0.5 * t**9 X_test = np.array([x_test**i for i in range(5)]).T
y = f(x) + 0.4 * rng.normal(size=100) regr = linear_model.LinearRegression()
regr.fit(X, y)
x_test = np.linspace(-1, 1, 100) plt.plot(x_test, regr.predict(X_test), label="4th order")

The data X = np.array([x**i for i in range(10)]).T


X_test = np.array([x_test**i for i in range(10)]).T
plt.figure(figsize=(6, 4)) regr = linear_model.LinearRegression()
plt.scatter(x, y, s=4) regr.fit(X, y)
plt.plot(x_test, regr.predict(X_test), label="9th order")

plt.legend(loc="best")
plt.axis("tight")
plt.title("Fitting a 4th and a 9th order polynomial")

18.8. Examples for the scikit-learn chapter 654 18.8. Examples for the scikit-learn chapter 655
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Text(0.5, 1.0, 'Fitting a 4th and a 9th order polynomial') Total running time of the script: (0 minutes 0.163 seconds)

Ground truth

plt.figure(figsize=(6, 4)) 18.8.11 A simple regression analysis on the California housing data
plt.scatter(x, y, s=4)
plt.plot(x_test, f(x_test), label="truth") Here we perform a simple regression analysis on the California housing data, exploring two types of
plt.axis("tight") regressors.
plt.title("Ground truth (9th order polynomial)")
from sklearn.datasets import fetch_california_housing
plt.show()
data = fetch_california_housing(as_frame=True)

Print a histogram of the quantity to predict: price

import matplotlib.pyplot as plt

plt.figure(figsize=(4, 3))
plt.hist(data.target)
plt.xlabel("price ($100k)")
plt.ylabel("count")
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 656 18.8. Examples for the scikit-learn chapter 657
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0


Print the join histogram for each feature

for index, feature_name in enumerate(data.feature_names):


plt.figure(figsize=(4, 3))
plt.scatter(data.data[feature_name], data.target)
plt.ylabel("Price", size=15)
plt.xlabel(feature_name, size=15)
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 658 18.8. Examples for the scikit-learn chapter 659
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •
Simple prediction

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(data.data, data.target)

from sklearn.linear_model import LinearRegression

clf = LinearRegression()
clf.fit(X_train, y_train)
predicted = clf.predict(X_test)
expected = y_test

plt.figure(figsize=(4, 3))
plt.scatter(expected, predicted)
plt.plot([0, 8], [0, 8], "--k")
plt.axis("tight")
plt.xlabel("True price ($100k)")

plt.ylabel("Predicted price ($100k)")
plt.tight_layout()

18.8. Examples for the scikit-learn chapter 660 18.8. Examples for the scikit-learn chapter 661
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Prediction with gradient boosted tree 18.8.12 Nearest-neighbor prediction on iris


from sklearn.ensemble import GradientBoostingRegressor Plot the decision boundary of nearest neighbor decision on iris, first with a single nearest neighbor, and
then using 3 nearest neighbors.
clf = GradientBoostingRegressor()
clf.fit(X_train, y_train) import numpy as np
import matplotlib.pyplot as plt
predicted = clf.predict(X_test) from sklearn import neighbors, datasets
expected = y_test from matplotlib.colors import ListedColormap

plt.figure(figsize=(4, 3)) # Create color maps for 3-class classification problem, as with iris
plt.scatter(expected, predicted) cmap_light = ListedColormap(["#FFAAAA", "#AAFFAA", "#AAAAFF"])
plt.plot([0, 5], [0, 5], "--k") cmap_bold = ListedColormap(["#FF0000", "#00FF00", "#0000FF"])
plt.axis("tight")
plt.xlabel("True price ($100k)") iris = datasets.load_iris()
plt.ylabel("Predicted price ($100k)") X = iris.data[:, :2] # we only take the first two features. We could
plt.tight_layout() # avoid this ugly slicing by using a two-dim dataset
y = iris.target

knn = neighbors.KNeighborsClassifier(n_neighbors=1)
knn.fit(X, y)

x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1


y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100))
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])

Put the result into a color plot

Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points


plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlabel("sepal length (cm)")
plt.ylabel("sepal width (cm)")
Print the error rate plt.axis("tight")
import numpy as np

print(f"RMS: { np.sqrt(np.mean((predicted - expected) ** 2))!r} ")

plt.show()

RMS: 0.5314909993118918

Total running time of the script: (0 minutes 4.331 seconds)

18.8. Examples for the scikit-learn chapter 662 18.8. Examples for the scikit-learn chapter 663
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(4.180808080808081, 8.019191919191918, 1.8868686868686868, 4.513131313131313) Total running time of the script: (0 minutes 0.706 seconds)

And now, redo the analysis with 3 neighbors

knn = neighbors.KNeighborsClassifier(n_neighbors=3) 18.8.13 Simple visualization and classification of the digits dataset
knn.fit(X, y)
Plot the first few samples of the digits dataset and a 2D representation built using PCA, then do a simple
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()]) classification

# Put the result into a color plot from sklearn.datasets import load_digits
Z = Z.reshape(xx.shape)
plt.figure() digits = load_digits()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points Plot the data: images of digits
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlabel("sepal length (cm)") Each data in a 8x8 image
plt.ylabel("sepal width (cm)")
plt.axis("tight") import matplotlib.pyplot as plt

plt.show() fig = plt.figure(figsize=(6, 6)) # figure size in inches


fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation="nearest")
# label the image with the target value
ax.text(0, 7, str(digits.target[i]))

18.8. Examples for the scikit-learn chapter 664 18.8. Examples for the scikit-learn chapter 665
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.colorbar.Colorbar object at 0x7f4943638490>

Classify with Gaussian naive Bayes

from sklearn.naive_bayes import GaussianNB


from sklearn.model_selection import train_test_split

# split the data into training and validation sets


Plot a projection on the 2 first principal axis
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)

plt.figure() # train the model


clf = GaussianNB()
from sklearn.decomposition import PCA clf.fit(X_train, y_train)

pca = PCA(n_components=2) # use the model to predict the labels of the test data
proj = pca.fit_transform(digits.data) predicted = clf.predict(X_test)
plt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap="Paired") expected = y_test
plt.colorbar()
# Plot the prediction
fig = plt.figure(figsize=(6, 6)) # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

# plot the digits: each image is 8x8 pixels


for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap=plt.cm.binary, interpolation="nearest
˓→")

(continues on next page)

18.8. Examples for the scikit-learn chapter 666 18.8. Examples for the scikit-learn chapter 667
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


print(len(matches))

# label the image with the target value


if predicted[i] == expected[i]: 450
ax.text(0, 7, str(predicted[i]), color="green")
else: And now, the ration of correct predictions
ax.text(0, 7, str(predicted[i]), color="red") matches.sum() / float(len(matches))

0.8622222222222222

Print the classification report

from sklearn import metrics

print(metrics.classification_report(expected, predicted))

precision recall f1-score support

0 1.00 1.00 1.00 51


1 0.62 0.93 0.75 41
2 0.94 0.70 0.80 46
3 0.93 0.87 0.90 47
4 1.00 0.84 0.91 43
5 0.86 0.93 0.89 40
6 0.98 0.98 0.98 45
7 0.86 0.96 0.91 52
8 0.65 0.69 0.67 49
9 0.96 0.69 0.81 36

accuracy 0.86 450


macro avg 0.88 0.86 0.86 450
weighted avg 0.88 0.86 0.86 450

Print the confusion matrix

print(metrics.confusion_matrix(expected, predicted))

plt.show()

[[51 0 0 0 0 0 0 0 0 0]
[ 0 38 0 0 0 0 0 0 3 0]
[ 0 5 32 0 0 0 0 0 9 0]
[ 0 1 0 41 0 2 0 0 2 1]
[ 0 2 1 0 36 0 1 2 1 0]
[ 0 1 0 0 0 37 0 1 1 0]
Quantify the performance [ 0 0 1 0 0 0 44 0 0 0]
[ 0 0 0 0 0 1 0 50 1 0]
First print the number of correct matches [ 0 12 0 0 0 1 0 2 34 0]
[ 0 2 0 3 0 2 0 3 1 25]]
matches = predicted == expected
print(matches.sum()) Total running time of the script: (0 minutes 1.757 seconds)

388

The total number of data points

18.8. Examples for the scikit-learn chapter 668 18.8. Examples for the scikit-learn chapter 669
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.14 The eigenfaces example: chaining PCA and SVMs

The goal of this example is to show how an unsupervised method and a supervised one can be chained
for better prediction. It starts with a didactic but lengthy way of doing things, and finishes with the
idiomatic approach to pipelining in scikit-learn.
Here we’ll take a look at a simple facial recognition example. Ideally, we would use a dataset con-
sisting of a subset of the Labeled Faces in the Wild data that is available with sklearn.datasets.
fetch_lfw_people(). However, this is a relatively large download (~200MB) so we will do the tutorial
on a simpler, less rich dataset. Feel free to explore the LFW dataset.

from sklearn import datasets

faces = datasets.fetch_olivetti_faces()
faces.data.shape

downloading Olivetti faces from https://ndownloader.figshare.com/files/5976027 to /


˓→home/runner/scikit_learn_data

(400, 4096)

Let’s visualize these faces to see what we’re working with

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 6))


# plot several images
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(faces.images[i], cmap=plt.cm.bone)
Tip: Note is that these faces have already been localized and scaled to a common size. This is an
important preprocessing piece for facial recognition, and is a process that can require a large collection
of training data. This can be done in scikit-learn, but the challenge is gathering a sufficient amount of
training data for the algorithm to work. Fortunately, this piece is common enough that it has been done.
One good resource is OpenCV, the Open Computer Vision Library.

We’ll perform a Support Vector classification of the images. We’ll do a typical train-test split on the
images:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(


faces.data, faces.target, random_state=0
)

print(X_train.shape, X_test.shape)

(300, 4096) (100, 4096)

18.8. Examples for the scikit-learn chapter 670 18.8. Examples for the scikit-learn chapter 671
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

Preprocessing: Principal Component Analysis

1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable size,
while maintaining most of the information in the dataset.

from sklearn import decomposition

pca = decomposition.PCA(n_components=150, whiten=True)


pca.fit(X_train)

One interesting part of PCA is that it computes the “mean” face, which can be interesting to examine:

plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=plt.cm.bone)

The components (“eigenfaces”) are ordered by their importance from top-left to bottom-right. We
see that the first few components seem to primarily take care of lighting conditions; the remaining
components pull out certain identifying features: the nose, eyes, eyebrows, etc.
With this projection computed, we can now project our original training and test data onto the PCA
basis:

X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print(X_train_pca.shape)

(300, 150)

print(X_test_pca.shape)

(100, 150)

These projected components correspond to factors in a linear combination of component images such
that the combination approaches the original face.

Doing the Learning: Support Vector Machines

Now we’ll perform support-vector-machine classification on this reduced dataset:

from sklearn import svm

clf = svm.SVC(C=5.0, gamma=0.001)


<matplotlib.image.AxesImage object at 0x7f49559aca90> clf.fit(X_train_pca, y_train)

The principal components measure deviations about this mean along orthogonal axes. Finally, we can evaluate how well this classification did. First, we might plot a few of the test-cases with
the labels learned from the training set:
print(pca.components_.shape)
import numpy as np
(150, 4096) fig = plt.figure(figsize=(8, 6))
for i in range(15):
It is also interesting to visualize these principal components: ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
fig = plt.figure(figsize=(16, 6)) ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap=plt.cm.bone)
for i in range(30): y_pred = clf.predict(X_test_pca[i, np.newaxis])[0]
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[]) color = "black" if y_pred == y_test[i] else "red"
ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=plt.cm.bone) ax.set_title(y_pred, fontsize="small", color=color)

18.8. Examples for the scikit-learn chapter 672 18.8. Examples for the scikit-learn chapter 673
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


15 1.00 1.00 1.00 3
17 1.00 1.00 1.00 6
19 1.00 1.00 1.00 4
20 1.00 1.00 1.00 1
21 1.00 1.00 1.00 1
22 1.00 1.00 1.00 2
23 1.00 1.00 1.00 1
24 1.00 1.00 1.00 2
25 1.00 0.50 0.67 2
26 1.00 0.75 0.86 4
27 1.00 1.00 1.00 1
28 0.67 1.00 0.80 2
29 1.00 1.00 1.00 3
30 1.00 1.00 1.00 4
31 1.00 1.00 1.00 3
32 1.00 1.00 1.00 3
33 1.00 1.00 1.00 2
34 1.00 1.00 1.00 3
35 1.00 1.00 1.00 1
36 1.00 1.00 1.00 3
37 1.00 1.00 1.00 3
38 1.00 1.00 1.00 1
39 1.00 1.00 1.00 3

accuracy 0.94 100


macro avg 0.95 0.96 0.94 100
weighted avg 0.97 0.94 0.94 100

The classifier is correct on an impressive number of images given the simplicity of its learning model! Another interesting metric is the confusion matrix, which indicates how often any two items are mixed-
Using a linear classifier on 150 features derived from the pixel-level data, the algorithm correctly identifies up. The confusion matrix of a perfect classifier would only have nonzero entries on the diagonal, with
a large number of the people in the images. zeros on the off-diagonal:
Again, we can quantify this effectiveness using one of several measures from sklearn.metrics. First we
print(metrics.confusion_matrix(y_test, y_pred))
can do the classification report, which shows the precision, recall and other measures of the “goodness”
of the classification:
[[3 0 0 ... 0 0 0]
from sklearn import metrics [0 4 0 ... 0 0 0]
[0 0 2 ... 0 0 0]
y_pred = clf.predict(X_test_pca) ...
print(metrics.classification_report(y_test, y_pred)) [0 0 0 ... 3 0 0]
[0 0 0 ... 0 1 0]
precision recall f1-score support [0 0 0 ... 0 0 3]]

0 1.00 0.50 0.67 6


1 1.00 1.00 1.00 4 Pipelining
2 0.50 1.00 0.67 2
3 1.00 1.00 1.00 1 Above we used PCA as a pre-processing step before applying our support vector machine classifier.
4 0.33 1.00 0.50 1 Plugging the output of one estimator directly into the input of a second estimator is a commonly used
5 1.00 1.00 1.00 5 pattern; for this reason scikit-learn provides a Pipeline object which automates this process. The above
6 1.00 1.00 1.00 4 problem can be re-expressed as a pipeline as follows:
7 1.00 0.67 0.80 3
9 1.00 1.00 1.00 1 from sklearn.pipeline import Pipeline
10 1.00 1.00 1.00 4
11 1.00 1.00 1.00 1 clf = Pipeline(
12 0.67 1.00 0.80 2 [
13 1.00 1.00 1.00 3 ("pca", decomposition.PCA(n_components=150, whiten=True)),
14 1.00 1.00 1.00 5 ("svm", svm.LinearSVC(C=1.0)),
(continues on next page) (continues on next page)

18.8. Examples for the scikit-learn chapter 674 18.8. Examples for the scikit-learn chapter 675
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


] data = np.random.normal(0, 10, (n_samples, 2))
) data[: n_samples // 2] -= 15
data[n_samples // 2 :] += 15
clf.fit(X_train, y_train)
labels = np.ones(n_samples)
y_pred = clf.predict(X_test) labels[: n_samples // 2] = -1
print(metrics.confusion_matrix(y_pred, y_test))
plt.show() return data, labels

/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_
˓→classes.py:31: FutureWarning: The default value of `dual` will change from `True`␣
X, y = linear_model()
˓→to `'auto'` in 1.5. Set the value of `dual` explicitly to suppress the warning.
clf = svm.SVC(kernel="linear")
warnings.warn( clf.fit(X, y)
/opt/hostedtoolcache/Python/3.11.9/x64/lib/python3.11/site-packages/sklearn/svm/_base.
˓→py:1237: ConvergenceWarning: Liblinear failed to converge, increase the number of␣
plt.figure(figsize=(6, 4))
˓→iterations.
ax = plt.subplot(111, xticks=[], yticks=[])
warnings.warn( ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone)
[[5 0 0 ... 0 0 0]
[0 4 0 ... 0 0 0] ax.scatter(
[0 0 1 ... 0 0 0] clf.support_vectors_[:, 0],
... clf.support_vectors_[:, 1],
[0 0 0 ... 3 0 0] s=80,
[0 0 0 ... 0 1 0] edgecolors="k",
[0 0 0 ... 0 0 3]] facecolors="none",
)

delta = 1
A Note on Facial Recognition
y_min, y_max = -50, 50
x_min, x_max = -50, 50
Here we have used PCA “eigenfaces” as a pre-processing step for facial recognition. The reason we x = np.arange(x_min, x_max + delta, delta)
chose this is because PCA is a broadly-applicable technique, which can be useful for a wide array of y = np.arange(y_min, y_max + delta, delta)
data types. Research in the field of facial recognition in particular, however, has shown that other more X1, X2 = np.meshgrid(x, y)
specific feature extraction methods are can be much more effective. Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
Total running time of the script: (0 minutes 3.737 seconds) Z = Z.reshape(X1.shape)

ax.contour(
X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"]
)
18.8.15 Example of linear and non-linear models

This is an example plot from the tutorial which accompanies an explanation of the support vector
machine GUI.

import numpy as np
import matplotlib.pyplot as plt

from sklearn import svm

rng = np.random.default_rng(27446968)

data that is linearly separable

def linear_model(rseed=42, n_samples=30):


"Generate data according to a linear model"
np.random.seed(rseed)

(continues on next page)

18.8. Examples for the scikit-learn chapter 676 18.8. Examples for the scikit-learn chapter 677
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax.scatter(
clf.support_vectors_[:, 0],
clf.support_vectors_[:, 1],
s=80,
edgecolors="k",
facecolors="none",
)

delta = 1
y_min, y_max = -50, 50
x_min, x_max = -50, 50
x = np.arange(x_min, x_max + delta, delta)
y = np.arange(y_min, y_max + delta, delta)
X1, X2 = np.meshgrid(x, y)
Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
Z = Z.reshape(X1.shape)

ax.contour(
X1,
X2,
Z,
[-1.0, 0.0, 1.0],
colors="k",
linestyles=["dashed", "solid", "dashed"],
<matplotlib.contour.QuadContourSet object at 0x7f494c053150> zorder=1,
)
data with a non-linear separation
plt.show()
def nonlinear_model(rseed=27446968, n_samples=30):
rng = np.random.default_rng(rseed)

radius = 40 * rng.random(n_samples)
far_pts = radius > 20
radius[far_pts] *= 1.2
radius[~far_pts] *= 1.1

theta = rng.random(n_samples) * np.pi * 2

data = np.empty((n_samples, 2))


data[:, 0] = radius * np.cos(theta)
data[:, 1] = radius * np.sin(theta)

labels = np.ones(n_samples)
labels[far_pts] = -1

return data, labels

X, y = nonlinear_model()
clf = svm.SVC(kernel="rbf", gamma=0.001, coef0=0, degree=3)
clf.fit(X, y)

plt.figure(figsize=(6, 4))
ax = plt.subplot(1, 1, 1, xticks=[], yticks=[])
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone, zorder=2) Total running time of the script: (0 minutes 0.065 seconds)

(continues on next page)

18.8. Examples for the scikit-learn chapter 678 18.8. Examples for the scikit-learn chapter 679
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

18.8.16 Bias and variance of polynomial fit

Demo overfitting, underfitting, and validation and learning curves with polynomial regression.
Fit polynomes of different degrees to a dataset: for too small a degree, the model underfits, while for too
large a degree, it overfits.

import numpy as np
import matplotlib.pyplot as plt

def generating_func(x, rng=None, error=0.5):


rng = np.random.default_rng(rng)
return rng.normal(10 - 1.0 / (x + 0.1), error)

A polynomial regression
Generate a larger dataset
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
n_samples = 200
A simple figure to illustrate the problem test_size = 0.4
error = 1.0
n_samples = 8
# randomly sample the data
rng = np.random.default_rng(27446968) x = rng.random(n_samples)
x = 10 ** np.linspace(-2, 0, n_samples) y = generating_func(x, rng=rng, error=error)
y = generating_func(x, rng=rng)
# split into training, validation, and testing sets.
x_test = np.linspace(-0.2, 1.2, 1000) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=test_size)

titles = ["d = 1 (under-fit; high bias)", "d = 2", "d = 6 (over-fit; high variance)"] # show the training and validation sets
degrees = [1, 2, 6] plt.figure(figsize=(6, 4))
plt.scatter(x_train, y_train, color="red", label="Training set")
fig = plt.figure(figsize=(9, 3.5)) plt.scatter(x_test, y_test, color="blue", label="Test set")
fig.subplots_adjust(left=0.06, right=0.98, bottom=0.15, top=0.85, wspace=0.05) plt.title("The data")
plt.legend(loc="best")
for i, d in enumerate(degrees):
ax = fig.add_subplot(131 + i, xticks=[], yticks=[])
ax.scatter(x, y, marker="x", c="k", s=50)

model = make_pipeline(PolynomialFeatures(d), LinearRegression())


model.fit(x[:, np.newaxis], y)
ax.plot(x_test, model.predict(x_test[:, np.newaxis]), "-b")

ax.set_xlim(-0.2, 1.2)
ax.set_ylim(0, 12)
ax.set_xlabel("house size")
if i == 0:
ax.set_ylabel("price")

ax.set_title(titles[i])

18.8. Examples for the scikit-learn chapter 680 18.8. Examples for the scikit-learn chapter 681
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

<matplotlib.legend.Legend object at 0x7f49437c1bd0>


Learning curves
Plot a validation curve
Plot train and test error with an increasing number of samples
from sklearn.model_selection import validation_curve
# A learning curve for d=1, 5, 15
degrees = np.arange(1, 21) for d in [1, 5, 15]:
model = make_pipeline(PolynomialFeatures(degree=d), LinearRegression())
model = make_pipeline(PolynomialFeatures(), LinearRegression())
from sklearn.model_selection import learning_curve
# The parameter to vary is the "degrees" on the pipeline step
# "polynomialfeatures" train_sizes, train_scores, validation_scores = learning_curve(
train_scores, validation_scores = validation_curve( model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20)
model, )
x[:, np.newaxis],
y, # Plot the mean train error and validation error across folds
param_name="polynomialfeatures__degree", plt.figure(figsize=(6, 4))
param_range=degrees, plt.plot(
) train_sizes, validation_scores.mean(axis=1), lw=2, label="cross-validation"
)
# Plot the mean train error and validation error across folds plt.plot(train_sizes, train_scores.mean(axis=1), lw=2, label="training")
plt.figure(figsize=(6, 4)) plt.ylim(ymin=-0.1, ymax=1)
plt.plot(degrees, validation_scores.mean(axis=1), lw=2, label="cross-validation")
plt.plot(degrees, train_scores.mean(axis=1), lw=2, label="training") plt.legend(loc="best")
plt.xlabel("number of train samples")
plt.legend(loc="best") plt.ylabel("explained variance")
plt.xlabel("degree of fit") plt.title("Learning curve (degree=%i )" % d)
plt.ylabel("explained variance") plt.tight_layout()
plt.title("Validation curve")
plt.tight_layout()
plt.show()

18.8. Examples for the scikit-learn chapter 682 18.8. Examples for the scikit-learn chapter 683
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

• •
Total running time of the script: (0 minutes 1.252 seconds)

18.8.17 Tutorial Diagrams

This script plots the flow-charts used in the scikit-learn tutorials.

18.8. Examples for the scikit-learn chapter 684 18.8. Examples for the scikit-learn chapter 685
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page)


ax = plt.axes((0, 0, 1, 1), xticks=[], yticks=[], frameon=False)
ax.set_xlim(0, 9)
ax.set_ylim(0, 6)

patches = [
Rectangle((0.3, 3.6), 1.5, 1.8, zorder=1, fc=box_bg),
Rectangle((0.5, 3.8), 1.5, 1.8, zorder=2, fc=box_bg),
Rectangle((0.7, 4.0), 1.5, 1.8, zorder=3, fc=box_bg),
Rectangle((2.9, 3.6), 0.2, 1.8, fc=box_bg),
Rectangle((3.1, 3.8), 0.2, 1.8, fc=box_bg),
Rectangle((3.3, 4.0), 0.2, 1.8, fc=box_bg),
Rectangle((0.3, 0.2), 1.5, 1.8, fc=box_bg),
Rectangle((2.9, 0.2), 0.2, 1.8, fc=box_bg),
Circle((5.5, 3.5), 1.0, fc=box_bg),
Polygon([[5.5, 1.7], [6.1, 1.1], [5.5, 0.5], [4.9, 1.1]], fc=box_bg),
FancyArrow(
2.3, 4.6, 0.35, 0, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
3.75, 4.2, 0.5, -0.2, fc=arrow1, width=0.25, head_width=0.5, head_
˓→length=0.2

),
• FancyArrow(
5.5, 2.4, 0, -0.4, fc=arrow1, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
2.0, 1.1, 0.5, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
3.3, 1.1, 1.3, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2
),
FancyArrow(
6.2, 1.1, 0.8, 0, fc=arrow2, width=0.25, head_width=0.5, head_length=0.2
),
]

if supervised:
patches += [
Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg),
Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg),
Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg),
FancyArrow(
2.3, 2.9, 2.0, 0, fc=arrow1, width=0.25, head_width=0.5, head_
˓→length=0.2

),
Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg),
• ]
else:
import numpy as np patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)]
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow for p in patches:
ax.add_patch(p)

def create_base(box_bg="#CCCCCC", arrow1="#88CCFF", arrow2="#88FF88",␣ plt.text(


˓→supervised=True): 1.45,
fig = plt.figure(figsize=(9, 6), facecolor="w") 4.9,
(continues on next page) (continues on next page)

18.8. Examples for the scikit-learn chapter 686 18.8. Examples for the scikit-learn chapter 687
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

(continued from previous page) (continued from previous page)


"Training\nText,\nDocuments,\nImages,\netc.", fontdict=fontdict,
ha="center", rotation=20,
va="center", ha="left",
fontsize=14, va="bottom",
) )
plt.text(
plt.text(3.6, 4.9, "Feature\nVectors", ha="left", va="center", fontsize=14) 3.7,
3.2,
plt.text( "clf.fit(X, y)",
5.5, 3.5, "Machine\nLearning\nAlgorithm", ha="center", va="center",␣ fontdict=fontdict,
˓→fontsize=14 rotation=20,
) ha="left",
va="bottom",
plt.text( )
1.05, plt.text(
1.1, 1.7,
"New Text,\nDocument,\nImage,\netc.", 1.5,
ha="center", "X_new = vec.transform(input)",
va="center", fontdict=fontdict,
fontsize=14, rotation=20,
) ha="left",
va="bottom",
plt.text(3.3, 1.7, "Feature\nVector", ha="left", va="center", fontsize=14) )
plt.text(
plt.text(5.5, 1.1, "Predictive\nModel", ha="center", va="center", fontsize=12) 6.1,
1.5,
if supervised: "y_new = clf.predict(X_new)",
plt.text(1.45, 3.05, "Labels", ha="center", va="center", fontsize=14) fontdict=fontdict,
rotation=20,
plt.text(8.05, 1.1, "Expected\nLabel", ha="center", va="center", fontsize=14) ha="left",
plt.text( va="bottom",
8.8, 5.8, "Supervised Learning Model", ha="right", va="top", fontsize=18 )
)

else: def plot_unsupervised_chart():


plt.text( create_base(supervised=False)
8.05,
1.1,
"Likelihood\nor Cluster ID\nor Better\nRepresentation", if __name__ == "__main__":
ha="center", plot_supervised_chart(False)
va="center", plot_supervised_chart(True)
fontsize=12, plot_unsupervised_chart()
) plt.show()
plt.text(
8.8, 5.8, "Unsupervised Learning Model", ha="right", va="top", fontsize=18 Total running time of the script: (0 minutes 0.195 seconds)
)

See also:
def plot_supervised_chart(annotate=False):
create_base(supervised=True) Going further
if annotate: • The documentation of scikit-learn is very complete and didactic.
fontdict = {"color": "r", "weight": "bold", "size": 14}
plt.text( • Introduction to Machine Learning with Python, by Sarah Guido, Andreas Müller (notebooks avail-
1.9, able here).
4.55,
"X = vec.fit_transform(input)",
(continues on next page)

18.8. Examples for the scikit-learn chapter 688 18.8. Examples for the scikit-learn chapter 689
CHAPTER 19
Part IV
About the Scientific Python Lectures
About the Scientific Python
Lectures
Release: 2024.2rc0.dev0
The lectures are archived on zenodo: http://dx.doi.org/10.5281/zenodo.594102
All code and material is licensed under a Creative Commons Attribution 4.0 International License (CC-
by) http://creativecommons.org/licenses/by/4.0/

19.1 Authors • Christophe Combelles

• André Espaze
19.1.1 Editors
• Emmanuelle Gouillart
• Gaël Varoquaux
• Emmanuelle Gouillart • Mike Müller
• Olav Vahtras
• Fabian Pedregosa
• Pierre de Buyl
• K. Jarrod Millman • Didrik Pinte
• Stéfan van der Walt
• Nicolas Rougier

19.1.2 Chapter authors • Gaël Varoquaux

Listed by alphabetical order. • Pauli Virtanen


• Christopher Burns
• Zbigniew Jędrzejewski-Szmek
• Adrian Chauve
• Robert Cimrman • Valentin Haenel (editor from 2011 to 2015)

690 691
Scientific Python Lectures, Edition 2024.2rc0.dev0 Scientific Python Lectures, Edition 2024.2rc0.dev0

19.1.3 Additional Contributions • Valentin Haenel • Nicolas Pettiaux • strpeter


• Pierre Haessig • Didrik Pinte • surfer190
Listed by alphabetical order
• Bruno Hanzen • Evgeny Pogrebnyak • Bartosz Telenczuk
• Osayd Abdu
• Michael Hartmann • reverland • tommyod
• arunpersaud
• Jonathan Helmus • Maximilien Riehl • Wes Turner
• Ross Barnowski
• Andreas Hilboll • Kristian Rother
• Sebastian Berg • Akihiro Uchida
• Himanshu • Nicolas P. Rougier
• Lilian Besson • Utkarsh Upadhyay
• Julian Hofer • Pamphile Roy
• Matthieu Boileau • Olav Vahtras
• Tim Hoffmann • Rutzmoser
• Joris Van den Bossche • Stéfan van der Walt
• B. Hohl • Sander
• Michael Boyle • Gaël Varoquaux
• Tarek Hoteit • João Felipe Santos
• Matthew Brett • Nelle Varoquaux
• Gert-Ludwig Ingold • Mark Setchell
• BSGalvan
• Olivier Verdier
• Zbigniew Jędrzejewski-Szmek • Helen Sherwood-Taylor
• Lars Buitinck
• Shoeboxam • VirgileFritsch
• Pierre de Buyl • Thouis (Ray) Jones
• Simon • Pauli Virtanen
• Ozan Çağlayan • jorgeprietoarranz
• josephsalmon • solarjoe • Yosh Wakeham
• Lawrence Chan
• Greg Kiar • ssmiller • yasutomo57jp
• Adrien Chauve
• kikocorreoso • Scott Staniewicz
• Robert Cimrman
• Christophe Combelles • Vince Knight

• David Cournapeau • LFP6

• Dave • Manuel López-Ibáñez

• dogacan dugmeci • Marco Mangan

• Török Edwin • Nicola Masarone

• egens • John McLaughlin

• Andre Espaze • mhemantha

• André Espaze • michelemaroni89

• Loïc Estève • K. Jarrod Millman

• Corey Farwell • Mohammad


• Tim Gates • Zachary Moon
• Stuart Geiger • Mike Mueller
• Olivier Georg • negm
• Daniel Gerigk • John B Nelson
• Robert Gieseke • nicoguaro
• Philip Gillißen • Sergio Oller
• Ralf Gommers • Theofilos Papapanagiotou
• Emmanuelle Gouillart • patniharshit
• Julia Gustavsen • Fabian Pedregosa
• Omar Gutiérrez • Philippe Pepiot
• Matt Haberland • Tiago M. D. Pereira

19.1. Authors 692 19.1. Authors 693


Index

D
diff, 572, 576
differentiation, 572
dsolve, 576

E
equations
algebraic, 574
differential, 576

I
integration, 574

M
Matrix, 576

P
Python Enhancement Proposals
PEP 255, 301
PEP 3118, 340
PEP 3129, 311
PEP 318, 303, 311
PEP 342, 301
PEP 343, 311
PEP 380, 302
PEP 380#id13, 302
PEP 8, 305

S
solve, 574

694

You might also like