Scientific Python Lectures
Scientific Python Lectures
2025
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 . . . . . . . . . . . . . . . . . . 7
SciPy Python EDITION
2 The Python language 12
2.1 First steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Basic types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.4 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
IP[y]: 2.5 Reusing code: scripts and modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.6 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Cython IPython
2.7 Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.8 Exception handling in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
2.9 Object-oriented programming (OOP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Scien�fic Python
3.2 Numerical operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
K. Jarrod Millman 3.3 More elaborate arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Stéfan van der Walt 3.4 Advanced operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Gaël Varoquaux 3.5 Some exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Lectures
Emmanuelle Gouillart 3.6 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Olaf Vahtras
Pierre de Buyl 4 Matplotlib: plotting 108
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
4.2 Simple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
lectures.scientific-python.org 4.3 Figures, Subplots, Axes and Ticks .
4.4 Other Types of Plots: examples and
. . . . . .
exercises .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
118
121
4.5 Beyond this tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
4.6 Quick references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
4.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Gaël Varoquaux • Emmanuelle Gouillart • Olav Vahtras
Pierre de Buyl • K. Jarrod Millman • Stéfan van der Walt 5 SciPy : high-level scientific computing 211
5.1 File input/output: scipy.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Christopher Burns • Adrian Chauve • Robert Cimrman • Christophe Combelles 5.2 Special functions: scipy.special . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Ralf Gommers • André Espaze • Zbigniew Jędrzejewski-Szmek
Valen� n Haenel • Michael Hartmann • Gert-Ludwig Ingold • Fabian Pedregosa
i
Didrik Pinte • Nicolas P. Rougier • Joris Van den Bossche • Pauli Virtanen
and many others...
5.3 Linear algebra operations: scipy.linalg . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 13.3 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
5.4 Interpolation: scipy.interpolate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 13.4 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . 442
5.5 Optimization and fit: scipy.optimize . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 13.5 Practical guide to optimization with SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . 480
5.6 Statistics and random numbers: scipy.stats . . . . . . . . . . . . . . . . . . . . . . . . 223 13.6 Special case: non-linear least-squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
5.7 Numerical integration: scipy.integrate . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 13.7 Optimization with constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
5.8 Fast Fourier transforms: scipy.fft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 13.8 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
5.9 Signal processing: scipy.signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 13.9 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . 485
5.10 Image manipulation: scipy.ndimage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
5.11 Summary exercises on scientific computing . . . . . . . . . . . . . . . . . . . . . . . . . . 237 14 Interfacing with C 486
5.12 Full code examples for the SciPy chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
14.2 Python-C-Api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
6 Getting help and finding documentation 291 14.3 Ctypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
14.4 SWIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
14.5 Cython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
II Advanced topics 294 14.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
14.7 Further Reading and References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
7 Advanced Python Constructs 296 14.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
7.1 Iterators, generator expressions and generators . . . . . . . . . . . . . . . . . . . . . . . . 297
7.2 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
7.3 Context managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 III Packages and applications 511
8 Advanced NumPy 313 15 Statistics in Python 513
8.1 Life of ndarray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 15.1 Data representation and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
8.2 Universal functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 15.2 Hypothesis testing: comparing two groups . . . . . . . . . . . . . . . . . . . . . . . . . . 519
8.3 Interoperability features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337 15.3 Linear models, multiple factors, and analysis of variance . . . . . . . . . . . . . . . . . . . 522
8.4 Array siblings: chararray, maskedarray . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 15.4 More visualization: seaborn for statistical exploration . . . . . . . . . . . . . . . . . . . . 528
8.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 15.5 Testing for interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
8.6 Contributing to NumPy/SciPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 15.6 Full code for the figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
15.7 Solutions to this chapter’s exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
9 Debugging code 346
9.1 Avoiding bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 16 Sympy : Symbolic Mathematics in Python 564
9.2 Debugging workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 16.1 First Steps with SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
9.3 Using the Python debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 16.2 Algebraic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
9.4 Debugging segmentation faults using gdb . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 16.3 Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
16.4 Equation solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
10 Optimizing code 358 16.5 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
10.1 Optimization workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
10.2 Profiling Python code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 17 scikit-image: image processing 572
10.3 Making code go faster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362 17.1 Introduction and concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
10.4 Writing faster numerical code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 17.2 Importing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
17.3 Example data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
11 Sparse Arrays in SciPy 366 17.4 Input/output, data types and colorspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 17.5 Image preprocessing / enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
11.2 Storage Schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 17.6 Image segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
11.3 Linear System Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 17.7 Measuring regions’ properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
11.4 Other Interesting Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386 17.8 Data visualization and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
17.9 Feature extraction for computer vision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
12 Image manipulation and processing using NumPy and SciPy 387
17.10 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
12.1 Opening and writing to image files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
17.11 Examples for the scikit-image chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
12.2 Displaying images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
12.3 Basic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 18 scikit-learn: machine learning in Python 598
12.4 Image filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 18.1 Introduction: problem settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
12.5 Feature extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 18.2 Basic principles of machine learning with scikit-learn . . . . . . . . . . . . . . . . . . . . 603
12.6 Measuring objects properties: scipy.ndimage.measurements . . . . . . . . . . . . . . . . 401 18.3 Supervised Learning: Classification of Handwritten Digits . . . . . . . . . . . . . . . . . . 608
12.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405 18.4 Supervised Learning: Regression of Housing Data . . . . . . . . . . . . . . . . . . . . . . 613
12.8 Examples for the image processing chapter . . . . . . . . . . . . . . . . . . . . . . . . . . 405 18.5 Measuring prediction performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
18.6 Unsupervised Learning: Dimensionality Reduction and Visualization . . . . . . . . . . . . 623
13 Mathematical optimization: finding minima of functions 432
18.7 Parameter selection, Validation, and Testing . . . . . . . . . . . . . . . . . . . . . . . . . 626
13.1 Knowing your problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
18.8 Examples for the scikit-learn chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
13.2 A review of the different optimizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
ii iii
Scientific Python Lectures, Edition 2025.1rc0.dev0
Index 685
iv Contents 1
Scientific Python Lectures, Edition 2025.1rc0.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
2 3
Scientific Python Lectures, Edition 2025.1rc0.dev0
• Universal Python is a language used for many different problems. Learning Python avoids learning
a new software for each new problem.
1
Compiled languages: C, C++, Fortran. . .
Pros
• Very fast. For heavy computations, it’s difficult to outperform these languages.
Cons
• Well thought out language, allowing to write very readable and well structured code: chapter on matplotlib
we “code what we think”.
• Many libraries beyond scientific computing (web server, serial port access, etc.) Advanced interactive environments:
• Free and open-source software, widely spread, with a vibrant community. • IPython, an advanced Python console https://ipython.org/
• A variety of powerful environments to work in, such as IPython, Spyder, Jupyter • Jupyter, notebooks in the browser https://jupyter.org/
notebooks, Pycharm, Visual Studio Code
Domain-specific packages,
Cons
• pandas, statsmodels, seaborn for statistics
• Not all the algorithms that can be found in more specialized software or toolboxes.
• sympy for symbolic computing
• scikit-image for image processing
1.2 The scientific Python ecosystem
• scikit-learn for machine learning
Unlike Matlab, or R, Python does not come with a pre-bundled set of modules for scientific computing. and many more packages not documented in the Scientific Python Lectures.
Below are the basic building blocks that can be combined to obtain a scientific computing environment:
ã See also
ã See also
1.4 The workflow: interactive environments and text editors
chapter on numpy
Interactive work to test and understand algorithms: In this section, we describe a workflow
• SciPy : high-level numerical routines. Optimization, regression, interpolation, etc https://scipy. combining interactive work and consolidation.
org/ 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.
ã See also
chapter on SciPy
1.2. The scientific Python ecosystem 6 1.3. Before starting: Installing a working environment 7
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
sep
string inserted between values, default a space. 1.4.3 IPython and Jupyter Tips and Tricks
end The user manuals contain a wealth of information. Here we give a quick introduction to four useful
string appended after the last value, default a newline. features: history, tab completion, magic functions, and aliases.
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/
In [7]: <UP>
• Jupyter Notebook QuickStart: https://docs.jupyter.org/en/latest/start/index.html
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. . .
Tab completion Tab completion, is a convenient way to explore the structure of any object you’re
• PyCharm: integrates an IPython console, notebooks, a debugger. . . (freely available, but commer-
dealing with. Simply type object_name.<TAB> to view the object’s attributes. Besides Python objects
cial)
and keywords, tab completion also works on file and directory names.*
• Visual Studio Code: integrates a Python console, notebooks, a debugger, . . .
In [9]: x = 10
Some of these are shipped by the various scientific Python distributions, and you can find them in the
menus. In [10]: x.<TAB>
As an exercise, create a file my_file.py in a code editor, and add the following lines: as_integer_ratio() conjugate() imag to_bytes()
bit_count() denominator numerator
s = 'Hello world' bit_length() from_bytes() real
print(s)
Now, you can run it in IPython console or a notebook and explore the resulting variables:
1.4. The workflow: interactive environments and text editors 8 1.4. The workflow: interactive environments and text editors 9
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Magic functions The console and the notebooks support so-called magic functions by prefixing a
Chapter on debugging
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.
Aliases Furthermore IPython ships with various aliases which emulate common UNIX command line
In [11]: cd /tmp
tools such as ls to list files, cp to copy files and rm to remove files (a full list of aliases is shown when
/tmp
typing alias).
• %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]): Getting help
In [12]: %cpaste • The built-in cheat-sheet is accessible via the %quickref magic function.
• A list of all available magic functions is shown when typing %magic.
• %timeit allows you to time the execution of short snippets using the timeit module from the
standard library:
In [12]: %timeit x = 10
11.8 ns +- 0.0116 ns per loop (mean +- std. dev. of 7 runs, 100,000,000 loops␣
˓→each)
ã See also
• %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()
87
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
1.4. The workflow: interactive environments and text editors 10 1.4. The workflow: interactive environments and text editors 11
Scientific Python Lectures, Edition 2025.1rc0.dev0
2
• 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.
CHAPTER
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.
Authors: Chris Burns, Christophe Combelles, Emmanuelle Gouillart, Gaël Varoquaux
The message “Hello, world!” is then displayed. You just executed your first Python instruction,
congratulations!
>>> a = 3
Tip >>> b = 2*a
Python is a programming language, as are C, Fortran, BASIC, PHP, etc. Some specific features >>> type(b)
of Python are as follows: <class 'int'>
>>> print(b)
• an interpreted (as opposed to compiled) language. Contrary to e.g. C or Fortran, one does 6
not compile Python code before executing it. In addition, Python can be used interactively: >>> a*b
many Python interpreters are available, from which commands and scripts can be executed. 18
• a free software released under an open-source license: Python can be used and distributed >>> b = 'hello'
free of charge, even for building commercial software. >>> type(b)
<class 'str'>
• multi-platform: Python is available for all major operating systems, Windows, Linux/Unix, >>> b + b
MacOS X, most likely your mobile phone OS, etc. 'hellohello'
(continues on next page)
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: Tip
int a = 3;
A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations +,
In addition, the type of a variable may change, in the sense that at one point in time it can be equal -, *, /, % (modulo) natively implemented
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 >>> 7 * 3.
such as additions and multiplications, which amount respectively to concatenation and repetition. 21.0
>>> 2**10
1024
>>> 8 % 3
2
Tip
2.2.2 Containers
Python supports the following numerical, scalar types:
Tip
Integer
Python provides many efficient types of containers, in which collections of objects can be stored.
>>> 1 + 1
2
>>> a = 4 Lists
>>> type(a)
<class 'int'>
Tip
Floats
A list is an ordered collection of objects, that may have different types. For example:
>>> c = 2.1
>>> type(c)
>>> colors = ['red', 'blue', 'green', 'black', 'white']
<class 'float'>
>>> type(colors)
<class 'list'>
Complex
>>> a = 1.5 + 0.5j Indexing: accessing individual objects contained in the list:
>>> a.real
>>> colors[2]
1.5
'green'
>>> a.imag
0.5
>>> type(1. + 0j) Counting from the end with negative indices:
<class 'complex'> >>> colors[-1]
'white'
Booleans >>> colors[-2]
'black'
>>> 3 > 4
False
(continues on next page)
. Warning
Tip
Indexing starts at 0 (as in C), not at 1 (as in Fortran or Matlab)! 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
Slicing: obtaining sublists of regularly-spaced elements: 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
>>> colors instead of Python loops.
['red', 'blue', 'green', 'black', 'white']
>>> colors[2:4]
['green', 'black']
Tip
. Warning 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
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.
Add and remove elements:
Slicing syntax: colors[start:stop:stride] >>> colors = ['red', 'blue', 'green', 'black', 'white']
>>> colors.append('pink')
>>> colors
Tip ['red', 'blue', 'green', 'black', 'white', 'pink']
>>> colors.pop() # removes and returns the last item
All slicing parameters are optional: 'pink'
>>> colors >>> colors
['red', 'blue', 'green', 'black', 'white'] ['red', 'blue', 'green', 'black', 'white']
>>> colors[3:] >>> colors.extend(['pink', 'purple']) # extend colors, in-place
['black', 'white'] >>> colors
>>> colors[:3] ['red', 'blue', 'green', 'black', 'white', 'pink', 'purple']
['red', 'blue', 'green'] >>> colors = colors[:-2]
>>> colors[::2] >>> colors
['red', 'green', 'white'] ['red', 'blue', 'green', 'black', 'white']
Reverse:
Lists are mutable objects and can be modified:
>>> rcolors = colors[::-1]
>>> colors[0] = 'yellow' >>> rcolors
>>> colors ['white', 'black', 'green', 'blue', 'red']
['yellow', 'blue', 'green', 'black', 'white'] >>> rcolors2 = list(colors) # new object that is a copy of colors in a different␣
>>> colors[2:4] = ['gray', 'purple'] ˓→memory area
The elements of a list may have different types: Concatenate and repeat lists:
>>> colors = [3, -200, 'hello'] >>> rcolors + colors
>>> colors ['white', 'black', 'green', 'blue', 'red', 'red', 'blue', 'green', 'black', 'white']
[3, -200, 'hello'] >>> rcolors * 2
>>> colors[1], colors[2] ['white', 'black', 'green', 'blue', 'red', 'white', 'black', 'green', 'blue', 'red']
(-200, 'hello')
Tip
Sort:
Tip
Methods and Object-Oriented Programming
(Remember that negative indices correspond to counting from the right end.)
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 . Slicing:
is necessary for going through this tutorial.
>>> a = "hello, world!"
>>> a[3:6] # 3rd to 6th (excluded) elements: elements 3, 4, 5
'lo,'
Discovering methods:
>>> a[2:10:2] # Syntax: a[start:stop:step]
Reminder: in Ipython: tab-completion (press tab) 'lo o'
>>> a[::3] # every three characters, from beginning to end
In [1]: rcolors.<TAB> 'hl r!'
append() count() insert() reverse()
clear() extend() pop() sort()
copy() index() remove()
Tip
Accents and special characters can also be handled as in Python 3 strings consist of Unicode charac-
Strings ters.
Different string syntaxes (simple, double or triple quotes):
A string is an immutable object and it is not possible to modify its contents. One may however create
s = 'Hello, how are you?' new strings from the original one.
s = "Hi, what's up"
s = '''Hello, In [3]: a = "hello, world!"
how are you''' # tripling the quotes allows the
# string to span more than one line In [4]: a.replace('l', 'z', 1)
s = """Hi, Out[4]: 'hezlo, world!'
what's up?"""
This syntax error can be avoided by enclosing the string in double quotes instead of single quotes. ã See also
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. 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
Tip
Strings are collections like lists. Hence they can be indexed and sliced, using the same syntax and String formatting:
rules.
>>> 'An integer: %i ; a float: %f ; another string: %s ' % (1, 0.1, 'string') # with␣
˓→more values use tuple after %
Indexing:
'An integer: 1; a float: 0.100000; another string: string'
(continues on next page)
>>> z = 1 + 1j
2.3 Control Flow >>> while abs(z) < 100:
... z = z**2 + 1
Controls the order in which the code is executed. >>> z
(-134+352j)
2.3.1 if/elif/else
More advanced features
>>> if 2**2 == 4:
... print("Obvious!") break out of enclosing for/while loop:
...
>>> z = 1 + 1j
Obvious!
>>> while abs(z) < 100:
Blocks are delimited by indentation
... if z.imag == 0:
... break
Tip ... z = z**2 + 1
Type the following lines in your Python interpreter, and be careful to respect the indentation continue the next iteration of a loop.:
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 >>> a = [1, 0, 2, 4]
key twice to leave the logical block. >>> for element in a:
... if element == 0:
... continue
>>> a = 10 ... print(1. / element)
1.0
>>> if a == 1: 0.5
... print(1) 0.25
... elif a == 2:
... print(2)
... else: 2.3.4 Conditional Expressions
... print("A lot")
... if <OBJECT>
A lot Evaluates to False:
• any number equal to zero (0, 0.0, 0+0j)
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. • an empty container (list, tuple, set, dictionary, . . . )
>>> a = 1
>>> b = 1.
>>> a == b . Warning
True
>>> a is b Not safe to modify the sequence you are iterating over.
False
Keeping track of enumeration number
>>> a = 1
>>> b = 1 Common task is to iterate over a sequence while keeping track of the item number.
>>> a is b
• Could use while loop with a counter as above. Or a for loop:
True
>>> words = ('cool', 'powerful', 'readable')
a in b >>> for i in range(0, len(words)):
For any collection b: b contains a ... print((i, words[i]))
(0, 'cool')
>>> b = [1, 2, 3]
(1, 'powerful')
>>> 2 in b
(2, 'readable')
True
>>> 5 in b
False • But, Python provides a built-in function - enumerate - for this:
In [6]: double_it(3)
Out[6]: 6
In [10]: double_it(3)
2.4.2 Return statement Out[10]: 6
Functions can optionally return values.
Keyword arguments allow you to specify default values.
In [3]: def disk_area(radius):
...: return 3.14 * radius * radius
...: . Warning
Default values are evaluated when the function is defined, not when it is called. This can be prob-
In [4]: disk_area(1.5) lematic when using mutable types (e.g. dictionary or list) and modifying them in the function body,
Out[4]: 7.0649999999999995 since the modifications will be persistent across invocations of the function.
Using an immutable type in a keyword argument:
ò Note In [11]: bigx = 10
In [18]: add_to_dict() If the value passed in a function is immutable, the function does not modify the caller’s variable. If the
{'a': 3, 'b': 4} value is mutable, the function may modify the caller’s variable in-place:
In [33]: x
Out[33]: 5 ò Note
Let us first write a script, that is a file with a sequence of instructions that are executed each time $ python file.py test arguments
the script is called. Instructions may be e.g. copied-and-pasted from the interpreter (but take care ['file.py', 'test', 'arguments']
to respect indentation rules!).
. Warning
The extension for Python files is .py. Write or copy-and-paste the following lines in a file called test.py
Don’t implement option parsing yourself. Use a dedicated module such as argparse.
message = "Hello how are you?"
for word in message.split():
print(word)
2.5.2 Importing objects from modules
In [3]: import os
Tip
In [4]: os
Let us now execute the script interactively, that is inside the Ipython interpreter. This is maybe the Out[4]: <module 'os' (frozen)>
most common use of scripts in scientific computing.
In [5]: os.listdir('.')
Out[5]:
['profile_1f1y_tei',
ò Note
'profile_fafmr45r',
in Ipython, the syntax to execute a script is %run script.py. For example, 'profile__degnych',
'clr-debug-pipe-1744-11435-out',
'dotnet-diagnostic-1744-11435-socket',
In [1]: %run test.py 'systemd-private-4d98e5f0d5f9404e9f14cc2cacc4c564-chrony.service-EWImxL',
Hello 'profile_z1bv__o8',
how 'profile_piq4dc_g',
are 'profile_vpgc00e4',
you? 'profile_clzffj76',
'clr-debug-pipe-841-947-in',
In [2]: message 'profile_pk7qvgfa',
Out[2]: 'Hello how are you?' 'profile_r5e9rl10',
'profile_xzyebo3o',
The script has been executed. Moreover the variables defined in the script (such as message) are now 'snap-private-tmp',
available inside the interpreter’s namespace. (continues on next page)
2.5. Reusing code: scripts and modules 32 2.5. Reusing code: scripts and modules 33
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
2.5. Reusing code: scripts and modules 34 2.5. Reusing code: scripts and modules 35
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
In [14]: dir(demo)
Out[14]: def print_a():
(continues on next page) (continues on next page)
2.5. Reusing code: scripts and modules 36 2.5. Reusing code: scripts and modules 37
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
(continued from previous page) • write your own modules within directories already defined in the search path (e.g. $HOME/.venv/
"Prints a." lectures/lib64/python3.11/site-packages). You may use symbolic links (on Linux) to keep
print("a") the code somewhere else.
• modify the environment variable PYTHONPATH to include the directories containing the user-defined
modules.
# print_b() runs on import
print_b()
Tip
if __name__ == "__main__":
# print_a() is only executed when the module is run directly. On Linux/Unix, add the following line to a file read by the shell at startup (e.g. /etc/profile,
print_a() .profile)
export PYTHONPATH=$PYTHONPATH:/home/emma/user_defined_modules
Importing it:
On Windows, https://support.microsoft.com/kb/310519 explains how to handle environment
In [19]: import demo2 variables.
b
In [20]: import demo2 • or modify the sys.path variable itself within a Python script.
Rule of thumb
• Sets of instructions that are called several times should be written inside functions for better ã See also
code reusability.
See https://docs.python.org/3/tutorial/modules.html for more information about modules.
• 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!).
2.5.6 Packages
A directory that contains many modules is called a package. A package is a module with submodules
How modules are found and imported (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.
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. $ ls
11) as well as the list of directories specified by the environment variable PYTHONPATH. _build_utils/ fft/ _lib/ odr/ spatial/
The list of directories searched by Python is given by the sys.path variable cluster/ fftpack/ linalg/ optimize/ special/
conftest.py __init__.py linalg.pxd optimize.pxd special.pxd
In [22]: import sys constants/ integrate/ meson.build setup.py stats/
datasets/ interpolate/ misc/ signal/
In [23]: sys.path _distributor_init.py io/ ndimage/ sparse/
Out[23]: $ cd ndimage
['/home/runner/work/scientific-python-lectures/scientific-python-lectures', $ ls
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python312.zip', _filters.py __init__.py _measurements.py morphology.py src/
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12', filters.py _interpolation.py measurements.py _ni_docstrings.py tests/
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/lib-dynload', _fourier.py interpolation.py meson.build _ni_support.py utils/
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages'] fourier.py LICENSE.txt _morphology.py setup.py
Modules must be located in the search path, therefore you can: From Ipython:
2.5. Reusing code: scripts and modules 38 2.5. Reusing code: scripts and modules 39
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Spaces
In [24]: import scipy as sp
Write well-spaced code: put whitespaces after commas, around arithmetic operators, etc.:
In [25]: sp.__file__
Out[25]: '/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages/scipy/__ >>> a = 1 # yes
˓→init__.py'
>>> a=1 # too cramped
In [26]: sp.version.version A certain number of rules for writing “beautiful” code (and more importantly using the same
Out[26]: '1.15.2' 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( Quick read
input,
If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem,
structure=None,
you can directly skip to the next chapter: NumPy: creating and manipulating numerical data.
iterations=1,
mask=None, The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
output=None, come back and finish this chapter later.
border_value=0,
origin=0,
brute_force=False,
)
Docstring: 2.6 Input and Output
Multidimensional binary dilation with the given structuring element.
... 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:
2.5.7 Good practices
• Use meaningful object names >>> f = open('workfile', 'w') # opens the workfile file
>>> type(f)
• Indentation: no choice! <class '_io.TextIOWrapper'>
>>> f.write('This is a test \nand another test')
>>> f.close()
Tip
Indenting is compulsory in Python! Every command block following a colon bears an additional To read from a file
indentation level with respect to the previous line with a colon. One must therefore indent after
In [1]: f = open('workfile', 'r')
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.)
In [2]: s = f.read()
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 In [3]: print(s)
This is a test
------------------------------------------------------------
and another test
IndentationError: unexpected indent (test.py, line 2)
All this indentation business can be a bit confusing in the beginning. However, with the clear In [4]: f.close()
indentation, and in the absence of extra characters, the resulting code is very nice to read
compared to other languages.
ã See also
• Indentation depth: Inside your text editor, you may choose to indent with any positive number For more details: https://docs.python.org/3/tutorial/inputoutput.html
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 2.6.1 Iterating over a file
Long lines: you should not write very long lines that span over more than (e.g.) 80 characters. In [5]: f = open('workfile', 'r')
Long lines can be broken with the \ character
In [6]: for line in f:
>>> long_line = "Here is a very very long line \ ...: print(line)
... that we break in two parts." (continues on next page)
2.5. Reusing code: scripts and modules 40 2.6. Input and Output 41
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
In [12]: fp.close()
ò Note
In [13]: 'junk.txt' in os.listdir(os.curdir) Alternative to os.system
(continues on next page)
Environment variables:
In [43]: sys.path
In [34]: os.environ.keys() Out[43]:
Out[34]: KeysView(environ({'SHELL': '/bin/bash', 'COLORTERM': 'truecolor', ...})) ['/home/runner/work/scientific-python-lectures/scientific-python-lectures',
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python312.zip',
In [35]: os.environ['SHELL'] '/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12',
Out[35]: '/bin/bash' '/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/lib-dynload',
'/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages']
2.7.3 glob: Pattern matching on files In [46]: with open('test.pkl', 'wb') as file:
....: pickle.dump(l, file)
The glob module provides convenient file pattern matching. ....:
Find all files ending in .txt:
In [47]: with open('test.pkl', 'rb') as file:
In [36]: import glob ....: out = pickle.load(file)
....:
In [37]: glob.glob('*.txt')
Out[37]: ['junk.txt'] In [48]: out
Out[48]: [1, None, 'Stan']
• Which version of python are you running and where is it installed: Write a program to search your PYTHONPATH for the module site.py.
In [39]: sys.platform
Out[39]: 'linux'
In [42]: sys.argv
Out[42]:
2.8.1 Exceptions
['/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages/sphinx/__main__. Exceptions are raised by errors in Python:
˓→py',
(continued from previous page) (methods) and variables (attributes), we will be able to use:
Cell In[15], line 3, in filter_name(name) In the previous example, the Student class has __init__, set_age and set_major methods. Its at-
1 def filter_name(name): tributes are name, age and major. We can call these methods and attributes with the following notation:
2 try: classinstance.method or classinstance.attribute. The __init__ constructor is a special method
----> 3 name = name.encode('ascii') we call with: MyClass(init parameters if any).
4 except UnicodeError as e: Now, suppose we want to create a new class MasterStudent with the same methods and attributes as
5 if name == 'Gaël': the previous one, but with an additional internship attribute. We won’t copy the previous class, but
inherit from it:
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 2:␣
˓→ordinal not in range(128) >>> class MasterStudent(Student):
... internship = 'mandatory, from March to June'
• Exceptions to pass messages between parts of the code: ...
>>> james = MasterStudent('james')
In [18]: def achilles_arrow(x): >>> james.internship
....: if abs(x - 1) < 1e-3: 'mandatory, from March to June'
....: raise StopIteration >>> james.set_age(23)
....: x = 1 - (1-x)/2. >>> james.age
....: return x 23
....:
The MasterStudent class inherited from the Student attributes and methods.
In [19]: x = 0
Thanks to classes and object-oriented programming, we can organize code with different classes corre-
In [20]: while True: sponding to different objects we encounter (an Experiment class, an Image class, a Flow class, etc.), with
....: try: their own methods and attributes. Then we can use inheritance to consider variations around a base
....: x = achilles_arrow(x) class and reuse code. Ex : from a Flow base class, we can create derived StokesFlow, TurbulentFlow,
....: except StopIteration: PotentialFlow, etc.
....: 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)
3
• containers: lists (costless insertion and append), dictionaries (fast lookup)
NumPy provides
• extension package to Python for multi-dimensional arrays
• closer to hardware (efficiency)
CHAPTER
• designed for scientific computation (convenience)
• Also known as array oriented computing
Tip
3.1 The NumPy array object Why it is useful: Memory-efficient container that provides fast numerical operations.
In [1]: L = range(1000)
Section contents
In [2]: %timeit [i**2 for i in L]
• What are NumPy and NumPy arrays? 53.9 us +- 961 ns per loop (mean +- std. dev. of 7 runs, 10,000 loops each)
• Creating arrays
In [3]: a = np.arange(1000)
• Basic data types
• Basic visualization In [4]: %timeit a**2
950 ns +- 4.13 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)
• Indexing and slicing
• Copies and views NumPy Reference documentation
• Fancy indexing
• On the web: https://numpy.org/doc/
• Interactive help:
In [5]: np.array?
Docstring:
(continues on next page)
When ``copy=None`` and a copy is made for other reasons, the result is >>> np.array([[1, 2], [3, 4]])
the same as if ``copy=True``, with some exceptions for 'A', see the array([[1, 2],
Notes section. The default order is 'K'. [3, 4]])
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise Minimum dimensions 2:
the returned array will be forced to be a base-class array (default).
ndmin : int, optional >>> np.array([1, 2, 3], ndmin=2)
Specifies the minimum number of dimensions that the resulting array([[1, 2, 3]])
array should have. Ones will be prepended to the shape as
needed to meet this requirement. Type provided:
like : array_like, optional
Reference object to allow the creation of arrays which are not >>> np.array([1, 2, 3], dtype=complex)
NumPy arrays. If an array-like passed in as ``like`` supports array([ 1.+0.j, 2.+0.j, 3.+0.j])
the ``__array_function__`` protocol, the result will be defined
by it. In this case, it ensures the creation of an array object Data-type consisting of more than one element:
compatible with that passed in via this argument.
(continues on next page) (continues on next page)
3.1. The NumPy array object 56 3.1. The NumPy array object 57
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
[[3],
Tip [4]]])
>>> c.shape
>>> help(np.array) (2, 2, 1)
Help on built-in function array in module numpy:
3.1. The NumPy array object 58 3.1. The NumPy array object 59
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> a = np.ones((3, 3)) # reminder: (3, 3) is a tuple Different data-types allow us to store data more compactly in memory, but most of the time we
>>> a simply work with floating point numbers. Note that, in the example above, NumPy auto-detects the
array([[1., 1., 1.], data-type from the input.
[1., 1., 1.],
[1., 1., 1.]])
>>> b = np.zeros((2, 2))
>>> b You can explicitly specify which data-type you want:
array([[0., 0.],
[0., 0.]]) >>> c = np.array([1, 2, 3], dtype=float)
>>> c = np.eye(3) >>> c.dtype
>>> c dtype('float64')
array([[1., 0., 0.],
[0., 1., 0.], The default data type is floating point:
[0., 0., 1.]])
>>> d = np.diag(np.array([1, 2, 3, 4])) >>> a = np.ones((3, 3))
>>> d >>> a.dtype
array([[1, 0, 0, 0], dtype('float64')
[0, 2, 0, 0],
[0, 0, 3, 0], There are also other types:
[0, 0, 0, 4]])
Complex
• np.random: random numbers (Mersenne Twister PRNG): >>> d = np.array([1+2j, 3+4j, 5+6*1j])
>>> d.dtype
>>> rng = np.random.default_rng(27446968) dtype('complex128')
>>> a = rng.random(4) # uniform in [0, 1]
>>> a
Bool
array([0.64613018, 0.48984931, 0.50851229, 0.22563948])
>>> e = np.array([True, False, False, True])
>>> b = rng.standard_normal(4) # Gaussian >>> e.dtype
>>> b dtype('bool')
array([-0.38250769, -0.61536465, 0.98131732, 0.59353096])
Strings
3.1. The NumPy array object 60 3.1. The NumPy array object 61
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> %matplotlib
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:
And then use (note that you have to use show explicitly if you have not enabled interactive plots with
%matplotlib):
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[0], a[2], a[-1]
(np.int64(0), np.int64(2), np.int64(9))
. Warning
Indices begin at 0, like other Python sequences (and C/C++). In contrast, in Fortran or Matlab,
indices begin at 1.
• 2D arrays (such as images):
The usual python idiom for reversing a sequence is supported:
>>> rng = np.random.default_rng(27446968)
>>> image = rng.random((30, 30)) >>> a[::-1]
>>> plt.imshow(image, cmap=plt.cm.hot) array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
<matplotlib.image.AxesImage object at ...>
>>> plt.colorbar() For multidimensional arrays, indices are tuples of integers:
<matplotlib.colorbar.Colorbar object at ...>
>>> a = np.diag(np.arange(3))
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 2]])
>>> a[1, 1]
(continues on next page)
3.1. The NumPy array object 62 3.1. The NumPy array object 63
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
3.1. The NumPy array object 64 3.1. The NumPy array object 65
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
3.1.6 Copies and views • Cross out 0 and 1 which are not primes:
A slicing operation creates a view on the original array, which is just a way of accessing array data. >>> is_prime[:2] = 0
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 • For each integer j starting from 2, cross out its higher multiples:
positives.
>>> N_max = int(np.sqrt(len(is_prime) - 1))
When modifying the view, the original array is modified as well: >>> for j in range(2, N_max + 1):
... is_prime[2*j::j] = False
>>> a = np.arange(10)
>>> a • Skim through help(np.nonzero), and print the prime numbers
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
• Follow-up:
>>> b = a[::2]
>>> b – Move the above code into a script file named prime_sieve.py
array([0, 2, 4, 6, 8])
– Run it to check it works
>>> np.may_share_memory(a, b)
True – Use the optimization suggested in the sieve of Eratosthenes:
>>> b[0] = 12
1. Skip j which are already known to not be primes
>>> b
array([12, 2, 4, 6, 8]) 2. The first number to cross out is 𝑗 2
>>> a # (!)
array([12, 1, 2, 3, 4, 5, 6, 7, 8, 9])
3.1.7 Fancy indexing
>>> a = np.arange(10)
>>> c = a[::2].copy() # force a copy
>>> c[0] = 12 Tip
>>> a
NumPy arrays can be indexed with slices, but also with boolean or integer arrays (masks). This
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
method is called fancy indexing. It creates copies not views.
>>> np.may_share_memory(a, c)
False Using boolean masks
This behavior can be surprising at first sight. . . but it allows to save both memory and time. >>> rng = np.random.default_rng(27446968)
>>> a = rng.integers(0, 21, 15)
>>> a
Worked example: Prime number sieve 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])
• Construct a shape (100,) boolean array is_prime, filled with True in the beginning: Indexing can be done with an array of integers, where the same index is repeated several time:
>>> is_prime = np.ones((100,), dtype=bool)
3.1. The NumPy array object 66 3.1. The NumPy array object 67
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Tip
When a new array is created by indexing with an array of integers, the new array has the same shape 3.2.1 Elementwise operations
as the array of integers: Basic operations
>>> a = np.arange(10) With scalars:
>>> idx = np.array([[3, 4], [9, 7]])
>>> idx.shape >>> a = np.array([1, 2, 3, 4])
(2, 2) >>> a + 1
>>> a[idx] array([2, 3, 4, 5])
array([[3, 4], >>> 2**a
[9, 7]]) array([ 2, 4, 8, 16])
>>> b = np.ones(4) + 1
The image below illustrates various fancy indexing applications >>> a - b
array([-1., 0., 1., 2.])
>>> a[(0,1,2,3,4), (1,2,3,4,5)] >>> a * b
0 1 2 3 4 5 array([2., 4., 6., 8.])
array([1, 12, 23, 34, 45])
Section contents
ò Note
>>> a = np.arange(4)
Exercise: Elementwise operations >>> a + np.array([1, 2])
Traceback (most recent call last):
• Try simple arithmetic elementwise operations: add even elements with odd elements File "<stdin>", line 1, in <module>
• Time them against their pure python counterparts using %timeit. ValueError: operands could not be broadcast together with shapes (4,) (2,)
Logical operations:
ò Note
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:
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.
>>> n_stories = 1000 # number of walkers The image below gives an example of broadcasting:
>>> t_max = 200 # time during which we follow the walker
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.
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,
Let’s verify: ... 1913, 2448])
>>> distance_array = np.abs(mileposts - mileposts[:, np.newaxis])
>>> a = np.tile(np.arange(0, 40, 10), (3, 1)).T >>> distance_array
>>> a array([[ 0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448],
array([[ 0, 0, 0], [ 198, 0, 105, 538, 673, 977, 1277, 1346, 1715, 2250],
[10, 10, 10], [ 303, 105, 0, 433, 568, 872, 1172, 1241, 1610, 2145],
[20, 20, 20], [ 736, 538, 433, 0, 135, 439, 739, 808, 1177, 1712],
[30, 30, 30]]) [ 871, 673, 568, 135, 0, 304, 604, 673, 1042, 1577],
>>> b = np.array([0, 1, 2]) [1175, 977, 872, 439, 304, 0, 300, 369, 738, 1273],
>>> a + b [1475, 1277, 1172, 739, 604, 300, 0, 69, 438, 973],
array([[ 0, 1, 2], [1544, 1346, 1241, 808, 673, 369, 69, 0, 369, 904],
[10, 11, 12], [1913, 1715, 1610, 1177, 1042, 738, 438, 369, 0, 535],
[20, 21, 22], [2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535, 0]])
[30, 31, 32]])
A useful trick:
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],
A lot of grid-based or network-based problems can also use broadcasting. For instance, if we want to [1, 1, 1, 1],
compute the distance from the origin of points on a 5x5 grid, we can do [2, 2, 2, 2],
>>> x, y = np.arange(5), np.arange(5)[:, np.newaxis] [3, 3, 3, 3]])
>>> distance = np.sqrt(x ** 2 + y ** 2) >>> y
>>> distance array([[0, 1, 2, 3],
array([[0. , 1. , 2. , 3. , 4. ], [0, 1, 2, 3],
[1. , 1.41421356, 2.23606798, 3.16227766, 4.12310563], [0, 1, 2, 3],
[2. , 2.23606798, 2.82842712, 3.60555128, 4.47213595], [0, 1, 2, 3]])
[3. , 3.16227766, 3.60555128, 4.24264069, 5. ],
[4. , 4.12310563, 4.47213595, 5. , 5.65685425]])
Reshaping
Remark : the numpy.ogrid() function allows to directly create vectors x and y of the previous example, The inverse operation to flattening:
with two “significant dimensions”:
>>> a.shape
>>> x, y = np.ogrid[0:5, 0:5] (2, 3)
>>> x, y >>> b = a.ravel()
(continues on next page) (continues on next page)
Tip Resizing
>>> b[0, 0] = 99 Size of an array can be changed with ndarray.resize:
>>> a
array([[99, 2, 3], >>> a = np.arange(4)
[ 4, 5, 6]]) >>> a.resize((8,))
>>> a
Beware: reshape may also return a copy!: array([0, 1, 2, 3, 0, 0, 0, 0])
>>> a = np.zeros((3, 2))
>>> b = a.T.reshape(3*2) However, it must not be referred to somewhere else:
>>> b[0] = 9 >>> b = a
>>> a >>> a.resize((4,))
array([[0., 0.], Traceback (most recent call last):
[0., 0.], File "<stdin>", line 1, in <module>
[0., 0.]]) ValueError: cannot resize an array that references or is referenced
To understand this you need to learn more about the memory layout of a NumPy array. by another array in this way.
Use the np.resize function or refcheck=False
Adding a dimension
Exercise: Shape manipulations
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): • Look at the docstring for reshape, especially the notes section which has some more information
about copies and views.
>>> z = np.array([1, 2, 3])
>>> z • Use flatten as an alternative to ravel. What is the difference? (Hint: check which one returns
array([1, 2, 3]) a view and which a copy)
• Experiment with transpose for dimension shuffling.
>>> z[:, np.newaxis]
array([[1],
[2],
3.2.5 Sorting data
[3]])
Sorting along an axis:
>>> z[np.newaxis, :]
array([[1, 2, 3]]) >>> a = np.array([[4, 3, 5], [1, 2, 1]])
>>> b = np.sort(a, axis=1)
>>> b
array([[3, 4, 5],
[1, 1, 2]])
ò Note
Quick read
Sorts each row separately!
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.
In-place sort: The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to
>>> a.sort(axis=1) come back and finish this chapter, as well as to do some more exercises.
>>> a
array([[3, 4, 5],
[1, 1, 2]])
• Try both in-place and out-of-place sorting. Assignment never changes the type!
• Try creating arrays with different dtypes and sorting them. >>> a = np.array([1, 2, 3])
• Use all or array_equal to check the results. >>> a.dtype
dtype('int64')
• Look at np.random.shuffle for a way to create sortable input quicker. >>> a[0] = 1.9 # <-- float is truncated to integer
• Combine ravel, sort and reshape. >>> a
array([1, 2, 3])
• Look at the axis keyword for sort and rewrite the previous exercise.
Forced casts:
Different data type sizes • Half the size in memory and on disk
Integers (signed): • Half the memory bandwidth required (may be a bit faster in some operations)
In [1]: a = np.zeros((int(1e6),), dtype=np.float64)
int8 8 bits
int16 16 bits In [2]: b = np.zeros((int(1e6),), dtype=np.float32)
int32 32 bits (same as int on 32-bit platform)
int64 64 bits (same as int on 64-bit platform) In [3]: %timeit a*a
269 us +- 2.39 us per loop (mean +- std. dev. of 7 runs, 1,000 loops each)
If you don’t know you need special data types, then you probably don’t. >>> samples[['position', 'value']]
array([(1. , 0.37), (1. , 0.11), (1. , 0.13), (1.5, 0.37),
Comparison on using float32 instead of float64:
(continues on next page)
(continued from previous page) • Except some rare cases, variable names and comments in English.
(3. , 0.11), (1.2, 0.13)],
dtype={'names': ['position', 'value'], 'formats': ['<f8', '<f8'], 'offsets': [4,
˓→ 12], 'itemsize': 20})
There are a bunch of other syntaxes for constructing structured arrays, see here and here.
3.4.1 Polynomials
3.3.3 maskedarray: dealing with (propagation of) missing data NumPy also contains polynomials in different bases:
• For floats one could use NaN’s, but masks work for all types: For example, 3𝑥2 + 2𝑥 − 1:
>>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1]) >>> p = np.poly1d([3, 2, -1])
>>> x >>> p(0)
masked_array(data=[1, --, 3, --], np.int64(-1)
mask=[False, True, False, True], >>> p.roots
fill_value=999999) array([-1. , 0.33333333])
>>> p.order
2
>>> y = np.ma.array([1, 2, 3, 4], mask=[0, 1, 1, 1])
>>> x + y
>>> x = np.linspace(0, 1, 20)
masked_array(data=[2, --, --, --],
>>> rng = np.random.default_rng()
mask=[False, True, True, True],
>>> y = np.cos(x) + 0.3*rng.random(20)
fill_value=999999)
>>> p = np.poly1d(np.polyfit(x, y, 3))
• Masking versions of common functions:
>>> t = np.linspace(0, 1, 200) # use a larger number of points for smoother plotting
>>> np.ma.sqrt([1, -1, 2, -2]) >>> plt.plot(x, y, 'o', t, p(t), '-')
masked_array(data=[1.0, --, 1.41421356237... --], [<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
mask=[False, True, False, True],
fill_value=1e+20)
ò Note
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)
See https://numpy.org/doc/stable/reference/routines.polynomials.poly1d.html for more.
• 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).
NumPy also has a more sophisticated polynomial interface, which supports e.g. the Chebyshev basis. [ 1902., 70200., 9800., 41500.],
...
3𝑥2 + 2𝑥 − 1:
>>> plt.imshow(plt.imread('red_elephant.png'))
>>> data = np.loadtxt('data/populations.txt') <matplotlib.image.AxesImage object at ...>
>>> data
array([[ 1900., 30000., 4000., 48300.],
[ 1901., 47200., 6100., 48200.],
(continues on next page)
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.
and generate a new array containing its 2nd and 4th rows.
2. Divide each column of the array:
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
NumPy’s own format row numbers corresponding to stuff in j.)
NumPy has its own binary format, not portable but with efficient I/O:
3.5.2 Picture manipulation: Framing a Face
>>> data = np.ones((3, 3))
>>> np.save('pop.npy', data) Let’s do some manipulations on NumPy arrays by starting with an image of a raccoon. scipy provides
>>> data3 = np.load('pop.npy') a 2D array of this image with the scipy.datasets.face function:
>>> crop_face = face[100:-100, 100:-100] 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.
• 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 2. Which year each species had the largest population.
is around (660, 330), so we defined the mask by this condition (y-300)**2 + (x-660)**2 3. Which species has the largest population for each year. (Hint: argsort & fancy indexing of
np.array(['H', 'L', 'C']))
>>> sy, sx = face.shape
>>> y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels 4. Which years any of the populations is above 50000. (Hint: comparisons and np.any)
>>> y.shape, x.shape 5. The top 2 years for each species when they had the lowest populations. (Hint: argsort, fancy
((768, 1), (1, 1024)) indexing)
>>> centerx, centery = (660, 300) # center of the image
>>> mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle 6. Compare (plot) the change in hare population (see help(np.gradient)) and the number of lynxes.
Check correlation (see help(np.corrcoef)).
then we assign the value 0 to the pixels of the image corresponding to the mask. The syntax . . . all without for-loops.
is extremely simple and intuitive:
Solution: Python source file
>>> face[mask] = 0
>>> plt.imshow(face) 3.5.4 Crude integral approximations
<matplotlib.image.AxesImage object at 0x...>
Write a function f(a, b, c) that returns 𝑎𝑏 −𝑐. Form a 24x12x6 array containing its values in parameter
• Follow-up: copy all instructions of this exercise in a script called ranges [0,1] x [0,1] x [0,1].
face_locket.py then execute this script in IPython with %run face_locket.py.
Approximate the 3-d integral
Change the circle to an ellipsoid. ∫︁ ∫︁ ∫︁
1 1 1
(𝑎𝑏 − 𝑐)𝑑𝑎 𝑑𝑏 𝑑𝑐
3.5.3 Data statistics 0 0 0
The data in populations.txt describes the populations of hares and lynxes (and carrots) in northern over this volume with the mean. The exact result is: ln 2 − 21 ≈ 0.1931 . . . — what is your relative error?
Canada during 20 years: (Hints: use elementwise operations and broadcasting. You can make np.ogrid give a number of points
>>> data = np.loadtxt('data/populations.txt') in given range with np.ogrid[0:1:20j].)
>>> year, hares, lynxes, carrots = data.T # trick: columns to variables Reminder Python functions:
Write a script that computes the Mandelbrot fractal. The Mandelbrot iteration:
N_max = 50
some_threshold = 50 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
c = x + 1j*y
2. Transition rule: 𝑝𝑛𝑒𝑤 = 𝑃 𝑇 𝑝𝑜𝑙𝑑
z = 0 3. all(sum(P, axis=1) == 1), p.sum() == 1: normalization
for j in range(N_max):
z = z**2 + c Write a script that works with 5 states, and:
• Constructs a random matrix, and normalizes each row so that it is a transition matrix.
Point (x, y) belongs to the Mandelbrot set if |𝑧| < some_threshold.
• Starts from a random (normalized) probability distribution p and takes 50 steps => p_50
Do this computation by:
• Computes the stationary distribution: the eigenvector of P.T with eigenvalue 1 (numerically: closest
1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5] to 1) => p_stationary
2. Do the iteration Remember to normalize the eigenvector — I didn’t. . .
3. Form the 2-d boolean mask indicating which points are in the set • Checks if p_50 and p_stationary are equal to tolerance 1e-5
4. Save the result to an image with: Toolbox: np.random, @, np.linalg.eig, reductions, abs(), argmin, comparisons, all, np.linalg.norm,
>>> import matplotlib.pyplot as plt etc.
>>> plt.imshow(mask.T, extent=[-2, 1, -1.5, 1.5]) Solution: Python source file
<matplotlib.image.AxesImage object at ...>
>>> plt.gray()
>>> plt.savefig('mandelbrot.png')
3.6 Full code examples
Solution: Python source file
3.6.1 Full code examples for the numpy chapter
1D plotting
Plot a basic 1D figure
Total running time of the script: (0 minutes 0.059 seconds) Total running time of the script: (0 minutes 0.067 seconds)
Total running time of the script: (0 minutes 0.061 seconds) t = np.linspace(0, 1, 200)
plt.plot(x, y, "o", t, p(t), "-")
plt.show()
Fitting to polynomial Total running time of the script: (0 minutes 0.045 seconds)
Plot noisy data and their polynomial fit
original figure
plt.figure()
img = plt.imread("../../../data/elephant.png")
plt.imshow(img)
3.6. Full code examples 100 3.6. Full code examples 101
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.figure() plt.figure()
img_red = img[:, :, 0] img_tiny = img[::6, ::6]
plt.imshow(img_red, cmap="gray") plt.imshow(img_tiny, interpolation="nearest")
plt.show()
3.6. Full code examples 102 3.6. Full code examples 103
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.245 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)
# 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
3.6. Full code examples 104 3.6. Full code examples 105
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import matplotlib.pyplot as plt
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
3.6. Full code examples 106 3.6. Full code examples 107
Scientific Python Lectures, Edition 2025.1rc0.dev0
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
Tip
The Jupyter notebook and the IPython enhanced interactive Python, are tuned for the scientific-
computing workflow in Python, in combination with Matplotlib:
CHAPTER
For interactive matplotlib sessions, turn on the matplotlib mode
IPython console
When using the IPython console, use:
In [1]: %matplotlib
Jupyter notebook
Matplotlib: plotting
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
Thanks closely after Matlab™. Therefore, the majority of plotting commands in pyplot have Matlab™ analogs
with similar arguments. Important commands are explained with interactive examples.
Many thanks to Bill Wing and Christoph Deil for review and corrections.
• Figures, Subplots, Axes and Ticks 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.
• Other Types of Plots: examples and exercises
First step is to get the data for the sine and cosine functions:
• Beyond this tutorial
• Quick references
import numpy as np
• Full code examples
X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)
4.1 Introduction 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:
Tip
$ ipython --matplotlib
Matplotlib is probably the most used Python package for 2D-graphics. It provides both a quick way
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
In the script below, we’ve instantiated (and commented) all the figure settings that influence the ap-
pearance of the plot.
Tip
Hint
The settings have been explicitly set to their default values, but now you can interactively play with
Documentation the values to explore their affect (see Line properties and Line styles below).
• plot tutorial
• plot() command
import numpy as np
import matplotlib.pyplot as plt
Tip
# Create a figure of size 8x6 inches, 80 dots per inch
Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You plt.figure(figsize=(8, 6), dpi=80)
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. # Create a new subplot from a grid of 1x1
plt.subplot(1, 1, 1)
# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))
# Set y limits
plt.ylim(-1.0, 1.0)
# Set y ticks
plt.yticks(np.linspace(-1, 1, 5))
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)
...
Hint
Documentation
4.2.5 Setting ticks
• 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) Hint
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") Documentation
... • xticks() command
• yticks() command
• Tick container
Tip
4.2.7 Moving spines
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])
...
Hint
Documentation
• spines API
• Axis container
• Transformations tutorial
Tip
Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They
Hint can be placed at arbitrary positions and until now, they were on the border of the axis. We’ll change
Documentation 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
• Working with text to coordinate 0 in data space coordinates.
• xticks() command
• yticks() command
• set_xticklabels() ...
ax = plt.gca() # gca stands for 'get current axis'
• set_yticklabels()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
Tip ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
Ticks are now properly placed but their label is not very explicit. We could guess that 3.142 is 𝜋 but ax.spines['left'].set_position(('data',0))
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],
(continues on next page)
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.
...
Hint t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
Documentation
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
• Legend guide
plt.annotate(r'$cos(\frac{2\pi}{3} )=-\frac{1} {2} $',
• legend() command
xy=(t, np.cos(t)), xycoords='data',
• legend API xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.legend(loc='upper left')
...
Hint
Documentation
• artist API
• set_bbox() method
Hint
Documentation
Tip
• Annotating axis
The tick labels are now hardly visible because of the blue and red lines. We can make them bigger the current figure (no argument), (2) a specific figure (figure number or figure instance as argument),
and we can also adjust their properties such that they’ll be rendered on a semi-transparent white or (3) all figures ("all" as argument).
background. This will allow us to see both the data and the labels.
...
for label in ax.get_xticklabels() + ax.get_yticklabels():
4.3.2 Subplots
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) 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
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.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:
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)
4.3. Figures, Subplots, Axes and Ticks 118 4.3. Figures, Subplots, Axes and Ticks 119
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.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))
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.3. Figures, Subplots, Axes and Ticks 120 4.4. Other Types of Plots: examples and exercises 121
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
4.4. Other Types of Plots: examples and exercises 122 4.4. Other Types of Plots: examples and exercises 123
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Starting from the code below, try to reproduce the graphic taking care of filled areas: Starting from the code below, try to reproduce the graphic by adding labels for red bars.
Hint Hint
You need to use the fill_between() command. You need to take care of text alignment.
n = 256
X = np.linspace(-np.pi, np.pi, n)
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)
Starting from the code below, try to reproduce the graphic taking care of marker size, color and trans-
parency.
Hint
n = 1024 Starting from the code below, try to reproduce the graphic taking care of the colormap (see Colormaps
rng = np.random.default_rng() below).
X = rng.normal(0,1,n)
Y = rng.normal(0,1,n)
Hint
plt.scatter(X,Y)
You need to use the clabel() command.
Click on figure for 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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Starting from the code below, try to reproduce the graphic taking care of colors and slices size.
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2)
Hint
n = 256
x = np.linspace(-3, 3, n) You need to modify Z.
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
rng = np.random.default_rng()
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap='jet') Z = rng.uniform(0, 1, 20)
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5) plt.pie(Z)
Click on figure for solution. Click on the figure for the solution.
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
Hint
You need to draw arrows twice.
You need to take care of the origin of the image in the imshow command and use a colorbar()
n = 8
X, Y = np.mgrid[0:n, 0:n]
def f(x, y):
plt.quiver(X, Y)
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
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)
(continues on next page)
4.4. Other Types of Plots: examples and exercises 126 4.4. Other Types of Plots: examples and exercises 127
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
4.4.11 3D Plots
Hint
plt.subplot(2, 2, 1)
Hint
plt.subplot(2, 2, 3)
plt.subplot(2, 2, 4) You need to use contourf()
4.4.12 Text
Hint
N = 20
theta = np.arange(0., 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
(continues on next page)
4.4. Other Types of Plots: examples and exercises 128 4.4. Other Types of Plots: examples and exercises 129
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, plot([x], y, [fmt], *, data=None, **kwargs)
you can directly skip to the next chapter: SciPy : high-level scientific computing. plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
...
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.4 Galleries
The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each
4.5 Beyond this tutorial example comes with its source.
Matplotlib benefits from extensive documentation as well as a large community of users and developers.
Here are some links of interest: 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
4.5.1 Tutorials technical.
Pie chart
A simple pie chart example with matplotlib.
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.pie(Z, explode=Z * 0.05, colors=[f"{ i / float(n): f} " for i in range(n)]) Total running time of the script: (0 minutes 0.052 seconds)
plt.axis("equal")
plt.xticks([])
plt.yticks() Plotting a scatter of points
plt.show() A simple example showing how to plot a scatter of points with matplotlib.
4.7. Full code examples 134 4.7. Full code examples 135
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Subplots
Show multiple subplots in matplotlib.
import numpy as np
import matplotlib.pyplot as plt
plt.show()
4.7. Full code examples 136 4.7. Full code examples 137
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import matplotlib
4.7. Full code examples 138 4.7. Full code examples 139
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.figure(figsize=(6, 4))
plt.subplot(1, 2, 1) import matplotlib.pyplot as plt
plt.xticks([])
plt.yticks([]) plt.axes((0.1, 0.1, 0.8, 0.8))
plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5) plt.xticks([])
plt.yticks([])
plt.subplot(1, 2, 2) plt.text(
plt.xticks([]) 0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20,␣
plt.yticks([]) ˓→alpha=0.5
plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5) )
)
Simple axes example
This example shows a couple of simple usage of axes. plt.show()
3D plotting
A simple example of 3D plotting.
4.7. Full code examples 140 4.7. Full code examples 141
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
4.7. Full code examples 142 4.7. Full code examples 143
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
n = 8
X, Y = np.mgrid[0:n, 0:n] def f(x, y):
T = np.arctan2(Y - n / 2.0, X - n / 2.0) return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)
U, V = R * np.cos(T), R * np.sin(T)
n = 256
plt.axes((0.025, 0.025, 0.95, 0.95)) x = np.linspace(-3, 3, n)
plt.quiver(X, Y, U, V, R, alpha=0.5) y = np.linspace(-3, 3, n)
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) X, Y = np.meshgrid(x, y)
4.7. Full code examples 144 4.7. Full code examples 145
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import matplotlib import numpy as np
import matplotlib.pyplot as plt
matplotlib.use("Agg")
import matplotlib.pyplot as plt n = 256
X = np.linspace(-np.pi, np.pi, n)
matplotlib.rc("grid", color="black", linestyle="-", linewidth=1) Y = np.sin(2 * X)
4.7. Full code examples 146 4.7. Full code examples 147
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
n = 12
jet = matplotlib.colormaps["jet"] X = np.arange(n)
rng = np.random.default_rng()
ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True) Y1 = (1 - X / n) * rng.uniform(0.5, 1.0, n)
Y2 = (1 - X / n) * rng.uniform(0.5, 1.0, n)
N = 20
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) plt.axes((0.025, 0.025, 0.95, 0.95))
rng = np.random.default_rng() plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white")
radii = 10 * rng.random(N) plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0) for x, y in zip(X, Y1):
plt.text(x, y + 0.05, f"{ y: .2f} ", ha="center", va="bottom")
for r, bar in zip(radii, bars, strict=True):
bar.set_facecolor(jet(r / 10.0)) for x, y in zip(X, Y2):
bar.set_alpha(0.5) plt.text(x, -y - 0.05, f"{ y: .2f} ", ha="center", va="top")
ax.set_xticklabels([]) plt.xlim(-0.5, n)
ax.set_yticklabels([]) plt.xticks([])
plt.show() plt.ylim(-1.25, 1.25)
plt.yticks([])
Total running time of the script: (0 minutes 0.078 seconds) (continues on next page)
4.7. Full code examples 148 4.7. Full code examples 149
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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)
import matplotlib.pyplot as plt
plt.subplot(2, 2, 2)
plt.xticks([]) plt.axes((0.1, 0.1, 0.5, 0.5))
plt.yticks([]) plt.xticks([])
plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5) plt.yticks([])
plt.text(
plt.subplot(2, 2, 3) 0.1, 0.1, "axes((0.1, 0.1, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5
plt.xticks([]) )
plt.yticks([])
plt.axes((0.2, 0.2, 0.5, 0.5))
plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5) plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 4) plt.text(
plt.xticks([]) 0.1, 0.1, "axes((0.2, 0.2, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5
(continues on next page) (continues on next page)
4.7. Full code examples 150 4.7. Full code examples 151
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.show() plt.show()
Total running time of the script: (0 minutes 0.044 seconds) Total running time of the script: (0 minutes 0.093 seconds)
Grid 3D plotting
Displaying a grid on the axes in matploblib. Demo 3D plotting with matplotlib and style the figure.
4.7. Full code examples 152 4.7. Full code examples 153
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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, import matplotlib.pyplot as plt
0.975, from matplotlib import gridspec
" Plot 2D or 3D data",
horizontalalignment="left", plt.figure(figsize=(6, 4))
verticalalignment="top", G = gridspec.GridSpec(3, 3)
family="DejaVu Sans",
size="medium", axes_1 = plt.subplot(G[0, :])
transform=plt.gca().transAxes, plt.xticks([])
) plt.yticks([])
plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5)
plt.show()
axes_2 = plt.subplot(G[1, :-1])
Total running time of the script: (0 minutes 0.050 seconds) plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5)
plt.tight_layout()
plt.show()
4.7. Full code examples 154 4.7. Full code examples 155
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.069 seconds) (continued from previous page)
rng = np.random.default_rng()
for i in range(24):
Demo text printing
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()
˓→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}$")
4.7. Full code examples 156 4.7. Full code examples 157
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import matplotlib.pyplot as plt
4.7. Full code examples 158 4.7. Full code examples 159
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Exercise 5
Exercise 6
Exercise 5 with matplotlib.
Exercise 6 with matplotlib.
4.7. Full code examples 160 4.7. Full code examples 161
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Exercise 2
import numpy as np
import matplotlib.pyplot as plt
# Set x limits
plt.xlim(-4.0, 4.0)
# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))
# Set y limits
(continues on next page)
4.7. Full code examples 162 4.7. Full code examples 163
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Exercise 8
import numpy as np
import matplotlib.pyplot as plt
4.7. Full code examples 164 4.7. Full code examples 165
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.058 seconds) plt.ylim(C.min() * 1.1, C.max() * 1.1)
plt.yticks([-1, +1], [r"$-1$", r"$+1$"])
t = 2 * np.pi / 3
Exercise 9
plt.plot([t, t], [0, np.cos(t)], color="blue", linewidth=1.5, linestyle="--")
Exercise 9 with matplotlib. 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"},
)
4.7. Full code examples 166 4.7. Full code examples 167
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
4.7. Full code examples 168 4.7. Full code examples 169
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.013 seconds) Total running time of the script: (0 minutes 0.016 seconds)
4.7. Full code examples 170 4.7. Full code examples 171
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
This example demonstrates aliased versus anti-aliased text. Demo the marker size control in matplotlib.
plt.show()
import matplotlib.pyplot as plt
Total running time of the script: (0 minutes 0.014 seconds)
size = 128, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi) Marker edge width
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0) Demo the marker edge widths of matplotlib’s markers.
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") import matplotlib.pyplot as plt
Total running time of the script: (0 minutes 0.010 seconds) for i in range(1, 11):
plt.plot(
[
(continues on next page)
4.7. Full code examples 172 4.7. Full code examples 173
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.xlim(0, 12)
plt.ylim(-1, 2)
plt.xticks([])
plt.yticks([])
plt.show()
import numpy as np
Total running time of the script: (0 minutes 0.011 seconds)
import matplotlib
import matplotlib.pyplot as plt
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 matplotlib.colormaps if not m.endswith("_r")]
(continues on next page)
4.7. Full code examples 174 4.7. Full code examples 175
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.plot( plt.show()
10 + np.arange(4),
np.ones(4), Total running time of the script: (0 minutes 0.015 seconds)
color="blue",
linewidth=8,
solid_capstyle="projecting",
Marker face color
)
Demo the marker face color of matplotlib’s markers.
plt.xlim(0, 14)
plt.xticks([])
plt.yticks([])
import numpy as np
plt.show() import matplotlib.pyplot as plt
Total running time of the script: (0 minutes 0.011 seconds) size = 256, 16
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
Marker edge color fig.patch.set_alpha(0)
plt.axes((0, 0, 1, 1), frameon=False)
Demo the marker edge color of matplotlib’s markers.
rng = np.random.default_rng()
4.7. Full code examples 176 4.7. Full code examples 177
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.014 seconds) Example demoing the dash join style.
plt.show()
4.7. Full code examples 178 4.7. Full code examples 179
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
n_markers = len(markers)
for i, m in enumerate(markers):
import numpy as np marker(m, i)
import matplotlib.pyplot as plt
plt.xlim(-0.2, 0.2 + 0.5 * n_markers)
plt.xticks([])
def marker(m, i): plt.yticks([])
X = i * 0.5 * np.ones(11)
Y = np.arange(11) plt.show()
plt.plot(X, Y, lw=1, marker=m, ms=10, mfc=(0.75, 0.75, 1, 1), mec=(0, 0, 1, 1)) Total running time of the script: (0 minutes 0.060 seconds)
plt.text(0.5 * i, 10.25, repr(m), rotation=90, fontsize=15, va="bottom")
markers = [ Linestyles
0,
1, Plot the different line styles.
2,
3,
4,
5,
6,
7,
"o",
"h",
"_",
"1",
"2",
"3",
"4",
"8",
"p",
"^",
"v",
"<",
">",
"|",
(continues on next page)
4.7. Full code examples 180 4.7. Full code examples 181
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
for i, ls in enumerate(linestyles):
import numpy as np linestyle(ls, i)
import matplotlib.pyplot as plt
plt.xlim(-0.2, 0.2 + 0.5 * n_lines)
plt.xticks([])
def linestyle(ls, i): plt.yticks([])
X = i * 0.5 * np.ones(11)
Y = np.arange(11) plt.show()
plt.plot(
X, Total running time of the script: (0 minutes 0.040 seconds)
Y,
ls,
color=(0.0, 0.0, 1, 1),
Locators for tick on axis
lw=3,
ms=8, An example demoing different locators to position ticks on axis for matplotlib.
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 182 4.7. Full code examples 183
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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(ticker.MultipleLocator(0.1))
ax.plot(np.arange(11), np.zeros(11))
return ax
locators = [
"ticker.NullLocator()",
"ticker.MultipleLocator(1.0)",
"ticker.FixedLocator([0, 2, 8, 9, 10])",
"ticker.IndexLocator(3, 1)",
"ticker.LinearLocator(5)",
"ticker.LogLocator(2, [1.0])",
"ticker.AutoLocator()",
]
n_locators = len(locators)
import numpy as np
size = 512, 40 * n_locators import matplotlib.pyplot as plt
dpi = 72.0 from mpl_toolkits.mplot3d import Axes3D
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi) x = np.arange(-4, 4, 0.25)
(continues on next page) (continues on next page)
4.7. Full code examples 184 4.7. Full code examples 185
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
fig = plt.figure()
ax: Axes3D = fig.add_subplot(111, projection="3d")
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, import numpy as np
0.87,
" Plot 2D or 3D data", import matplotlib
horizontalalignment="left", import matplotlib.pyplot as plt
verticalalignment="top",
size="large",
transform=plt.gca().transAxes, plt.subplot(1, 1, 1, polar=True)
)
N = 20
plt.show() theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
Total running time of the script: (0 minutes 0.110 seconds) radii = 10 * rng.random(N)
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)
jet = matplotlib.colormaps["jet"]
Plotting in polar, decorated
for r, bar in zip(radii, bars, strict=True):
An example showing how to plot in polar coordinate, and some decorations.
bar.set_facecolor(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",
(continues on next page)
4.7. Full code examples 186 4.7. Full code examples 187
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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()
import numpy as np
import matplotlib.pyplot as plt
(continues on next page)
4.7. Full code examples 188 4.7. Full code examples 189
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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()
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,
)
)
4.7. Full code examples 190 4.7. Full code examples 191
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.xticks([])
plt.yticks([])
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 192 4.7. Full code examples 193
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
import matplotlib.pyplot as plt Total running time of the script: (0 minutes 0.060 seconds)
n = 1024
rng = np.random.default_rng()
X = rng.normal(0, 1, n) Pie chart vignette
Y = rng.normal(0, 1, n)
Demo pie chart with matplotlib and style the figure.
T = np.arctan2(Y, X)
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 194 4.7. Full code examples 195
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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,
)
Demoing imshow
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([])
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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
import matplotlib.pyplot as plt plt.show()
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 198 4.7. Full code examples 199
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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()
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 200 4.7. Full code examples 201
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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,
)
import numpy as np
import matplotlib.pyplot as plt plt.show()
An example demoing how to plot the contours of a function, with additional layout tweaks.
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([])
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 202 4.7. Full code examples 203
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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,
/home/runner/work/scientific-python-lectures/scientific-python-lectures/intro/ )
˓→matplotlib/examples/pretty_plots/plot_contour_ext.py:24: UserWarning: The following␣
def f(x, y): Total running time of the script: (0 minutes 0.077 seconds)
return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)
4.7. Full code examples 204 4.7. Full code examples 205
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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(
Text(-0.05, 1.01, '\n\n Draw ticks and grid ') -0.05,
1.01,
"\n\n Draw ticks and grid ",
horizontalalignment="left",
verticalalignment="top",
size="large",
transform=axes.transAxes,
import matplotlib.pyplot as plt )
from matplotlib.ticker import MultipleLocator
Total running time of the script: (0 minutes 0.095 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) Text printing decorated
axes.xaxis.set_major_locator(MultipleLocator(1.0)) An example showing text printing and decorating the resulting figure.
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([])
axes.set_yticklabels([])
4.7. Full code examples 206 4.7. Full code examples 207
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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,
import numpy as np facecolor="white",
import matplotlib.pyplot as plt alpha=1.0,
transform=plt.gca().transAxes,
fig = plt.figure() )
plt.xticks([]) )
plt.yticks([])
plt.text(
eqs = [] -0.05,
eqs.append( 1.02,
r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1} " Text: plt.text(...)\n",
˓→ {8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\ horizontalalignment="left",
˓→delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \ verticalalignment="top",
˓→sigma_2}}\right]$" size="xx-large",
) transform=plt.gca().transAxes,
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} $" plt.text(
) -0.05,
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$") 1.01,
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") "\n\n Draw any kind of text ",
eqs.append(r"$F_G = G\frac{m_1m_2} {r^2}$") horizontalalignment="left",
verticalalignment="top",
rng = np.random.default_rng() size="large",
transform=plt.gca().transAxes,
for i in range(24): )
index = rng.integers(0, len(eqs))
eq = eqs[index] plt.show()
size = rng.uniform(12, 32)
(continues on next page) Total running time of the script: (0 minutes 0.629 seconds)
4.7. Full code examples 208 4.7. Full code examples 209
Scientific Python Lectures, Edition 2025.1rc0.dev0
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
implemented 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
. Warning
. Warning Python / Matlab mismatch: The Matlab file format does not support 1D arrays.
This tutorial is far from an introduction to numerical computing. As enumerating the different >>> a = np.ones(3)
submodules and functions in SciPy would be very boring, we concentrate instead on a few examples >>> a
to give a general idea of how to use scipy for scientific computing. array([1., 1., 1.])
>>> a.shape
(3,)
scipy is composed of task-specific sub-modules: >>> sp.io.savemat('file.mat', {'a': a})
>>> a2 = sp.io.loadmat('file.mat')['a']
scipy.cluster Vector quantization / Kmeans >>> a2
scipy.constants Physical and mathematical constants array([[1., 1., 1.]])
scipy.fft Fourier transform >>> a2.shape
scipy.integrate Integration routines (1, 3)
scipy.interpolate Interpolation
Notice that the original array was a one-dimensional array, whereas the saved and reloaded array is
scipy.io Data input and output
a two-dimensional array with a single row.
scipy.linalg Linear algebra routines
scipy.ndimage n-dimensional image package For other formats, see the scipy.io documentation.
scipy.odr Orthogonal distance regression
scipy.optimize Optimization
scipy.signal Signal processing
scipy.sparse Sparse matrices ã See also
scipy.spatial Spatial data structures and algorithms
scipy.special Any special mathematical functions • Load text files: numpy.loadtxt()/numpy.savetxt()
scipy.stats Statistics • 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.
Tip pyplot.imsave()
They all depend on numpy, but are mostly independent of each other. The standard way of importing • More advanced input/output of images: imageio
NumPy and these SciPy modules is:
>>> import numpy as np
>>> import scipy as sp 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 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.
• elliptic functions, such as scipy.special.ellipj() (Jacobi elliptic functions).
Combining the identities log(𝑎/𝑏) = log(𝑎) − log(𝑏) and exp(log(𝑥)) = 𝑥, we get:
Other special functions are combinations of familiar elementary functions, but they offer better accuracy
or robustness than their naive implementations would. >>> log_a = sp.special.gammaln(500)
>>> log_b = sp.special.gammaln(499)
Most of these function are computed elementwise and follow standard NumPy broadcasting rules when >>> log_res = log_a - log_b
the input arrays have different shapes. For example, scipy.special.xlog1py() is mathematically >>> res = np.exp(log_res)
equivalent to 𝑥 log(1 + 𝑦). >>> res
np.float64(499.0000000...)
>>> import scipy as sp
>>> x = np.asarray([1, 2])
>>> y = np.asarray([[3], [4], [5]]) Similarly, suppose we wish to compute the difference log(Γ(500) − Γ(499)). For this, we use scipy.
>>> res = sp.special.xlog1py(x, y) special.logsumexp(), which computes log(exp(𝑥)+exp(𝑦)) using a numerical trick that avoids overflow.
>>> res.shape >>> res = sp.special.logsumexp([log_a, log_b],
(3, 2) ... b=[1, -1]) # weights the terms of the sum
>>> ref = x * np.log(1 + y) >>> res
>>> np.allclose(res, ref) np.float64(2605.113844343...)
True
For more information about these and many other special functions, see the documentation of scipy.
However, scipy.special.xlog1py() is numerically favorable for small 𝑦, when explicit addition of 1 special.
would lead to loss of precision due to floating point truncation error.
5.2. Special functions: scipy.special 214 5.3. Linear algebra operations: scipy.linalg 215
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
scipy.linalg also features matrix factorizations/decompositions such as the singular value decomposi-
tion.
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,
>>> i = (measured_time > np.pi/2) & (measured_time < 3*np.pi/2) ... x[1] - x[0]]
>>> inverse_spline = sp.interpolate.make_interp_spline(np.flip(function[i]), >>> res = sp.optimize.root(f, x0=[0, 0])
... np.flip(measured_time[i])) >>> np.allclose(f(res.x), 0, atol=1e-10)
>>> inverse_spline(0) True
array(3.14159265) >>> np.allclose(res.x, np.sqrt(2)/2)
True
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 Over-constrained problems can be solved in the least-squares sense using scipy.optimize.root() with
documentation for much more information. method='lm' (Levenberg-Marquardt).
. Warning
None of the functions in scipy.optimize that accept a guess are guaranteed to converge for all Suppose we have data that is sinusoidal but noisy:
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 >>> x = np.linspace(-5, 5, num=50) # 50 values between -5 and 5
shown below), or consider whether SciPy offers a more appropriate method for the problem. >>> noise = 0.01 * np.cos(100 * x)
>>> a, b = 2.9, 1.5
>>> y = a * np.cos(b * x) + noise
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 We can approximate the underlying amplitude, frequency, and phase from the data by least squares
that contains only the root we seek. 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:
>>> res = sp.optimize.root_scalar(f, bracket=(1.5, 10))
>>> res.root >>> def f(x, a, b, c):
2.0 ... return a * np.sin(b * x + c)
5.5. Optimization and fit: scipy.optimize 218 5.5. Optimization and fit: scipy.optimize 219
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Suppose we wish to minimize the scalar-valued function of a single variable 𝑓 (𝑥) = 𝑥2 + 10 sin(𝑥):
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
the approximate locations of the minima, we will provide bounds that restrict the search to the vicinity
We then use scipy.optimize.curve_fit() to find 𝑎 and 𝑏:
of the global minimum.
>>> params, _ = sp.optimize.curve_fit(f, x, y, p0=[2, 1, 3])
>>> res = sp.optimize.minimize_scalar(f, bounds=(-2, -1))
>>> params
>>> res
array([2.900026 , 1.50012043, 1.57079633])
message: Solution found.
>>> ref = [a, b, np.pi/2] # what we'd expect
success: True
>>> np.allclose(params, ref, rtol=1e-3)
status: 0
True
fun: -7.9458233756...
x: -1.306440997...
nit: 8
Exercise: Curve fitting of temperature data nfev: 8
The temperature extremes in Alaska for each month, starting in January, are given by >>> res.fun == f(res.x)
(in degrees Celsius): np.True_
max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18 If we did not already know the approximate location of the global minimum, we could use one of
min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58 SciPy’s global minimizers, such as scipy.optimize.differential_evolution(). We are required to
pass bounds, but they do not need to be tight.
1. Plot these temperature extremes.
2. Define a function that can describe min and max temperatures. Hint: this function >>> bounds=[(-5, 5)] # list of lower, upper bound for each variable
has to have a period of 1 year. Hint: include a time offset. >>> res = sp.optimize.differential_evolution(f, bounds=bounds)
>>> res
3. Fit this function to the data with scipy.optimize.curve_fit(). message: Optimization terminated successfully.
4. Plot the result. Is the fit reasonable? If not, why? success: True
fun: -7.9458233756...
5. Is the time offset for min and max temperatures the same within the fit accuracy? x: [-1.306e+00]
solution nit: 6
nfev: 111
jac: [ 9.948e-06]
5.5.3 Optimization
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 .
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 .)
5.5. Optimization and fit: scipy.optimize 220 5.5. Optimization and fit: scipy.optimize 221
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
(continued from previous page) 5.6 Statistics and random numbers: scipy.stats
nit: 2
jac: [ 3.219e-09 -8.462e-09] scipy.stats contains fundamental tools for statistics in Python.
hess_inv: [[ 9.000e-01 -2.000e-01]
[-2.000e-01 6.000e-01]] 5.6.1 Statistical Distributions
nfev: 9
njev: 3 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):
Maximization? >>> dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution
>>> sample = dist.rvs(size=100000) # "random variate sample"
Is scipy.optimize.minimize() restricted to the solution of minimization problems? Nope! To solve
>>> plt.hist(sample, bins=50, density=True, label='normalized histogram')
a maximization problem, simply minimize the negative of the original objective function.
>>> x = np.linspace(-5, 5)
>>> plt.plot(x, dist.pdf(x), label='PDF')
This barely scratches the surface of SciPy’s optimization features, which include mixed integer linear [<matplotlib.lines.Line2D object at ...>]
programming, constrained nonlinear programming, and the solution of assignment problems. For much >>> plt.legend()
more information, see the documentation of scipy.optimize and the advanced chapter Mathematical <matplotlib.legend.Legend object at ...>
optimization: finding minima of functions.
𝑥4 2
𝑓 (𝑥, 𝑦) = (4 − 2.1𝑥2 + )𝑥 + 𝑥𝑦 + (4𝑦 2 − 4)𝑦 2
3
Distribution objects and frozen distributions
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. 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
Hints:
a frozen distribution: a particular element of a distribution family with all parameters fixed. The
• Variables can be restricted to −2 < 𝑥 < 2 and −1 < 𝑦 < 1. frozen distribution object has methods to compute essential functions of the particular distribution.
• numpy.meshgrid() and matplotlib.pyplot.imshow() can help with visualization.
Suppose we knew that the sample had been drawn from a distribution belonging to the family of normal
• Try minimizing with scipy.optimize.minimize() with an initial guess of (𝑥, 𝑦) = distributions, but we did not know the particular distribution’s location (mean) and scale (standard
(0, 0). Does it find the global minimum, or converge to a local minimum? What deviation). We perform maximum likelihood estimation of the unknown parameters using the distribution
about other initial guesses? family’s fit method:
• Try minimizing with scipy.optimize.differential_evolution().
>>> loc, scale = sp.stats.norm.fit(sample)
solution >>> loc
np.float64(0.0015767005...)
See the summary exercise on Non linear least squares curve fitting: application to point extraction in >>> scale
topographical lidar data for another, more advanced example. np.float64(0.9973396878...)
5.5. Optimization and fit: scipy.optimize 222 5.6. Statistics and random numbers: scipy.stats 223
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Since we know the true parameters of the distribution from which the sample was drawn, we are not (continued from previous page)
surprised that these estimates are similar. >>> abs(integral - 1) < error_estimate # actual error < estimated error
True
Exercise: Probability distributions
Other functions for numerical quadrature, including integration of multivariate functions and approxi-
Generate 1000 random variates from a gamma distribution with a shape parameter of 1. Hint: the mating integrals from samples, are available in scipy.integrate.
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 5.7.2 Initial Value Problems
using the fit method.
scipy.integrate also features routines for integrating Ordinary Differential Equations (ODE). For
Extra: the distributions have many useful methods. Explore them using tab completion. Plot the example, scipy.integrate.solve_ivp() integrates ODEs of the form:
cumulative density function of the distribution, and compute the variance.
𝑑𝑦
= 𝑓 (𝑡, 𝑦(𝑡))
𝑑𝑡
5.6.2 Sample Statistics and Hypothesis Tests
from an initial time 𝑡0 and initial state 𝑦(𝑡 = 𝑡0 ) = 𝑡0 to a final time 𝑡𝑓 or until an event occurs (e.g. a
The sample mean is an estimator of the mean of the distribution from which the sample was drawn: specified state is reached).
>>> np.mean(sample) As an introduction, consider the initial value problem given by 𝑑𝑦 𝑑𝑡 = −2𝑦 and the initial condition
np.float64(0.001576700508...) 𝑦(𝑡 = 0) = 1 on the interval 𝑡 = 0 . . . 4. We begin by defining a callable that computes 𝑓 (𝑡, 𝑦(𝑡)) given
the current time and state.
NumPy includes some of the most fundamental sample statistics (e.g. numpy.mean(), numpy.var(),
>>> def f(t, y):
numpy.percentile()); scipy.stats includes many more. For instance, the geometric mean is a common
... return -2 * y
measure of central tendency for data that tends to be distributed over many orders of magnitude.
5.7. Numerical integration: scipy.integrate 224 5.7. Numerical integration: scipy.integrate 225
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Before using scipy.integrate.solve_ivp(), the 2nd order ODE needs to be transformed into a system 5.8 Fast Fourier transforms: scipy.fft
of first-order ODEs. Note that
𝑑𝑦 𝑑𝑦˙ The scipy.fft module computes fast Fourier transforms (FFTs) and offers utilities to handle them.
= 𝑦˙ = 𝑦¨ = −(2𝜁𝜔0 𝑦˙ + 𝜔02 𝑦)
𝑑𝑡 𝑑𝑡 Some important functions are:
If we define 𝑧 = [𝑧0 , 𝑧1 ] where 𝑧0 = 𝑦 and 𝑧1 = 𝑦,˙ then the first order equation: • scipy.fft.fft() to compute the FFT
[︂ 𝑑𝑧0 ]︂ [︂ ]︂
𝑑𝑧 𝑧1 • scipy.fft.fftfreq() to generate the sampling frequencies
= 𝑑𝑧 𝑑𝑡 = 2
𝑑𝑡 1
−(2𝜁𝜔 𝑧
0 1 + 𝜔 𝑧
0 0 )
𝑑𝑡 • scipy.fft.ifft() to compute the inverse FFT, from frequency space to signal space
is equivalent to the original second order equation.
We set:
>>> m = 0.5 # kg
>>> k = 4 # N/m
>>> c = 0.4 # N s/m As an illustration, a (noisy) input signal (sig), and its FFT:
>>> zeta = c / (2 * m * np.sqrt(k/m)) >>> sig_fft = sp.fft.fft(sig)
>>> omega = np.sqrt(k / m) >>> freqs = sp.fft.fftfreq(sig.size, d=time_step)
Signal FFT
Integration of the system follows:
>>> t_span = (0, 10) As the signal comes from a real-valued function, the Fourier transform is symmetric.
>>> t_eval = np.linspace(*t_span, 100) The peak signal frequency can be found with freqs[power.argmax()]
>>> z0 = [1, 0]
>>> res = sp.integrate.solve_ivp(f, t_span, z0, t_eval=t_eval,
... args=(zeta, omega), method='LSODA')
Tip
ã See also
5.7. Numerical integration: scipy.integrate 226 5.8. Fast Fourier transforms: scipy.fft 227
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Setting the Fourier component above this frequency to zero and inverting the FFT with scipy.fft.
ifft(), gives a filtered signal.
ò Note
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.
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?
Fully worked examples:
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).
Crude periodicity finding (link) Gaussian image blur (link)
5. Apply the inverse Fourier transform to see the resulting image.
Solution
Tip
5.8. Fast Fourier transforms: scipy.fft 228 5.9. Signal processing: scipy.signal 229
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> 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.
Resampling scipy.signal.resample(): resample a signal to n points using FFT.
>>> t = np.linspace(0, 5, 100) Spectral analysis: scipy.signal.spectrogram() compute a spectrogram –frequency spectrums over
>>> x = np.sin(t) consecutive time windows–, while scipy.signal.welch() comptes a power spectrum density (PSD).
>>> 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.
5.9. Signal processing: scipy.signal 230 5.10. Image manipulation: scipy.ndimage 231
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Exercise
>>> # etc.
• Erosion scipy.ndimage.binary_erosion()
5.10. Image manipulation: scipy.ndimage 232 5.10. Image manipulation: scipy.ndimage 233
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> a = np.zeros((5, 5), dtype=int) Check that the area of the reconstructed square is smaller than the area of the initial
>>> a[1:4, 1:4] = 1 square. (The opposite would occur if the closing step was performed before the opening).
>>> a[4, 4] = 1
>>> a For gray-valued images, eroding (resp. dilating) amounts to replacing a pixel by the minimal (resp.
array([[0, 0, 0, 0, 0], maximal) value among pixels covered by the structuring element centered on the pixel of interest.
[0, 1, 1, 1, 0],
[0, 1, 1, 1, 0], >>> a = np.zeros((7, 7), dtype=int)
[0, 1, 1, 1, 0], >>> a[1:6, 1:6] = 3
[0, 0, 0, 0, 1]]) >>> a[4, 4] = 2; a[2, 3] = 1
>>> # Opening removes small objects >>> a
(continues on next page) (continues on next page)
5.10. Image manipulation: scipy.ndimage 234 5.10. Image manipulation: scipy.ndimage 235
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
See the summary exercise on Image processing application: counting bubbles and unmolten grains for a
more advanced example.
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
scipy.ndimage.label() assigns a different label to each connected component: 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
>>> labels, nb = sp.ndimage.label(mask)
it. In the current model, it is supposed that the maximum wind speed occurring every 50 years is defined
>>> nb
as the upper 2% quantile.
8
By definition, the quantile function is the inverse of the cumulative distribution function. The latter
Now compute measurements on each connected component: describes the probability distribution of an annual maxima. In the exercise, the cumulative probability
5.10. Image manipulation: scipy.ndimage 236 5.11. Summary exercises on scientific computing 237
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
Following the cumulative probability definition p_i from the previous section, the corresponding values
will be:
The quantile function is now going to be evaluated from the full range of probabilities:
In the current model, the maximum wind speed occurring every 50 years is defined as the upper 2% Fig. 1: Solution: Python source file
quantile. As a result, the cumulative probability value will be:
So the storm wind speed occurring every 50 years can be guessed by:
5.11. Summary exercises on scientific computing 238 5.11. Summary exercises on scientific computing 239
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• 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 Fig. 3: Solution: Python source file
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.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.
5.11. Summary exercises on scientific computing 240 5.11. Summary exercises on scientific computing 241
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
As shown below, this waveform is a 80-bin-length signal with a single peak with an amplitude of ap- where
proximately 30 in the 15 nanosecond bin. Additionally, the base level of noise is approximately 3. These • coeffs[0] is 𝐵 (noise)
values can be used in the initial solution.
• coeffs[1] is 𝐴 (amplitude)
Fitting a waveform with a simple Gaussian model • coeffs[2] is 𝜇 (center)
The signal is very simple and can be modeled as a single Gaussian function and an offset corresponding • coeffs[3] is 𝜎 (width)
to the background noise. To fit the signal with the function, we must:
• define the model Initial solution
• propose an initial solution One possible initial solution that we determine by inspection is:
• call scipy.optimize.leastsq >>> x0 = np.array([3, 30, 15, 1], dtype=float)
Model
Fit
A Gaussian function defined by
{︃ (︂ scipy.optimize.leastsq minimizes the sum of squares of the function given as an argument. Basically,
)︂2 }︃
𝑡−𝜇 the function to minimize is the residuals (the difference between the data and the model):
𝐵 + 𝐴 exp −
𝜎
>>> def residuals(coeffs, y, t):
can be defined in python by: ... return y - model(t, coeffs)
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 So let’s get our solution by calling scipy.optimize.leastsq() with the following arguments:
2 The data used for this tutorial are part of the demonstration data available for the FullAnalyze software and were
5.11. Summary exercises on scientific computing 242 5.11. Summary exercises on scientific computing 243
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• an initial solution
• the additional arguments to pass to the function
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
5.11. Summary exercises on scientific computing 244 5.11. Summary exercises on scientific computing 245
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
5.11.3 Image processing application: counting bubbles and unmolten grains 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
5.11. Summary exercises on scientific computing 246 5.11. Summary exercises on scientific computing 247
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are
4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand smaller than 10 pixels. To do so, use sp.ndimage.sum or np.bincount to compute the grain sizes.
pixels, glass pixels and bubble pixels. Other option (homework): write a function that determines
automatically the thresholds from the minima of the histogram. >>> sand_labels, sand_nb = sp.ndimage.label(sand_op)
>>> sand_areas = np.array(sp.ndimage.sum(sand_op, sand_labels, np.arange(sand_
>>> void = filtdat <= 50 ˓→labels.max()+1)))
>>> sand = np.logical_and(filtdat > 50, filtdat <= 114) >>> mask = sand_areas > 100
>>> glass = filtdat > 114 >>> remove_small_sand = mask[sand_labels.ravel()].reshape(sand_labels.shape)
5. Display an image in which the three phases are colored with three different colors.
5.11. Summary exercises on scientific computing 248 5.11. Summary exercises on scientific computing 249
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
def f(x):
return x**2 + 10 * np.sin(x) plt.show()
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
Plot
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 5.12. Full code examples for the SciPy chapter 251
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.249 seconds) Total running time of the script: (0 minutes 0.052 seconds)
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
plt.figure(figsize=(5, 4))
plt.plot(t, x, label="x")
plt.plot(t, x_detrended, label="x_detrended") import numpy as np
plt.legend(loc="best") import scipy as sp
plt.show() import matplotlib.pyplot as plt
5.12. Full code examples for the SciPy chapter 252 5.12. Full code examples for the SciPy chapter 253
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
t_span = (0, 4) # time interval dist = sp.stats.norm(loc=0, scale=1) # standard normal distribution
t_eval = np.linspace(*t_span) # times at which to evaluate `y` sample = dist.rvs(size=100000) # "random variate sample"
y0 = [ plt.hist(
1, sample,
] # initial state bins=51, # group the observations into 50 bins
res = sp.integrate.solve_ivp(f, t_span=t_span, y0=y0, t_eval=t_eval) density=True, # normalize the frequencies
label="normalized histogram",
plt.figure(figsize=(4, 3)) )
plt.plot(res.t, res.y[0])
plt.xlabel("t") x = np.linspace(-5, 5) # possible values of the random variable
plt.ylabel("y") plt.plot(x, dist.pdf(x), label="PDF")
plt.title("Solution of Initial Value Problem") plt.legend()
plt.tight_layout() plt.show()
plt.show()
Total running time of the script: (0 minutes 0.098 seconds)
Total running time of the script: (0 minutes 0.077 seconds)
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
5.12. Full code examples for the SciPy chapter 254 5.12. Full code examples for the SciPy chapter 255
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
f, t_span, z0, t_eval=t_eval, args=(zeta, omega), method="LSODA" plt.hist(samples2, bins=bins, density=True, label="Samples 2") # type: ignore[arg-
) ˓→type]
plt.legend(loc="best")
plt.figure(figsize=(4, 3)) plt.show()
plt.plot(res.t, res.y[0], label="y")
plt.plot(res.t, res.y[1], label="dy/dt") Total running time of the script: (0 minutes 0.093 seconds)
plt.legend(loc="best")
plt.show()
Total running time of the script: (0 minutes 0.050 seconds) 5.12.8 Curve fitting
Demos a simple curve fitting
First generate some data
5.12.7 Comparing 2 sets of samples from Gaussians
import numpy as np
# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)
import numpy as np
import matplotlib.pyplot as plt
5.12. Full code examples for the SciPy chapter 256 5.12. Full code examples for the SciPy chapter 257
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
<matplotlib.collections.PathCollection object at 0x7f24a22ca2d0> Total running time of the script: (0 minutes 0.101 seconds)
plt.legend(loc="best")
plt.show()
5.12. Full code examples for the SciPy chapter 258 5.12. Full code examples for the SciPy chapter 259
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Compute and plot the spectrogram The power of the signal per frequency band
The spectrum of the signal on consecutive time windows freqs, psd = sp.signal.welch(sig)
5.12. Full code examples for the SciPy chapter 260 5.12. Full code examples for the SciPy chapter 261
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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="gray")
plt.axis("off")
plt.title("a")
plt.subplot(142)
plt.imshow(mask, cmap="gray")
plt.axis("off")
plt.title("mask")
plt.subplot(143)
plt.imshow(opened_mask, cmap="gray")
plt.axis("off")
plt.title("opened_mask")
plt.subplot(144)
plt.show() plt.imshow(closed_mask, cmap="gray")
plt.title("closed_mask")
Total running time of the script: (0 minutes 0.327 seconds) plt.axis("off")
5.12. Full code examples for the SciPy chapter 262 5.12. Full code examples for the SciPy chapter 263
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.subplot(152)
plt.imshow(shifted_face2, cmap="gray")
plt.axis("off")
plt.subplot(153)
plt.imshow(rotated_face, cmap="gray")
plt.axis("off")
plt.subplot(154)
plt.imshow(cropped_face, cmap="gray")
plt.axis("off")
plt.subplot(155)
plt.imshow(zoomed_face, cmap="gray")
plt.axis("off")
Label connected components
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)
import scipy as sp
plt.show()
labels, nb = sp.ndimage.label(mask)
Total running time of the script: (0 minutes 1.012 seconds)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(labels)
plt.title("label")
5.12.12 Demo connected components plt.axis("off")
Extracting and labeling connected components in a 2D array
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)
import numpy as np
import matplotlib.pyplot as plt
x, y = np.indices((100, 100))
sig = (
np.sin(2 * np.pi * x / 50.0)
* np.sin(2 * np.pi * y / 50.0)
* (1 + x * y / 50.0**2) ** 2
(continues on next page)
5.12. Full code examples for the SciPy chapter 264 5.12. Full code examples for the SciPy chapter 265
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
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} ")
Extract the 4th connected component, and crop the array around it
# Constrain optimization
sl = sp.ndimage.find_objects(labels == 4) xmin_local = sp.optimize.fminbound(f, 0, 10)
plt.figure(figsize=(3.5, 3.5)) print(f"Local minimum found { xmin_local} ")
plt.imshow(sig[sl[0]])
plt.title("Cropped connected component")
plt.axis("off") Global minima found [-1.30641113]
Local minimum found 3.8374671194983834
plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9)
Root finding
plt.show()
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.100 seconds) # Plot the roots
roots = np.array([root.x, root2.x])
(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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.figure(figsize=(12, 3.5))
plt.subplot(141)
plt.imshow(noisy_face, cmap="gray")
plt.axis("off")
plt.title("noisy")
plt.subplot(142)
plt.imshow(blurred_face, cmap="gray")
plt.axis("off")
plt.title("Gaussian filter")
plt.subplot(143)
plt.imshow(median_face, cmap="gray")
plt.axis("off")
plt.title("median filter")
plt.subplot(144)
plt.imshow(wiener_face, cmap="gray")
plt.title("Wiener filter")
Total running time of the script: (0 minutes 0.064 seconds) plt.axis("off")
5.12. Full code examples for the SciPy chapter 268 5.12. Full code examples for the SciPy chapter 269
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.colorbar()
5.12. Full code examples for the SciPy chapter 270 5.12. Full code examples for the SciPy chapter 271
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.393 seconds) [<matplotlib.lines.Line2D object at 0x7f24a2a07110>]
This example demonstrate scipy.fft.fft(), scipy.fft.fftfreq() and scipy.fft.ifft(). It imple- # And the power (sig_fft is of complex dtype)
ments a basic filter that is very suboptimal, and should not be used. power = np.abs(sig_fft) ** 2
import numpy as np
# The corresponding frequencies
import scipy as sp
sample_freq = sp.fft.fftfreq(sig.size, d=time_step)
import matplotlib.pyplot as plt
(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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages/matplotlib/cbook.
˓→py:1719: ComplexWarning: Casting complex values to real discards the imaginary part
return math.isfinite(val)
/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages/matplotlib/cbook.
˓→py:1355: ComplexWarning: Casting complex values to real discards the imaginary part
5.12. Full code examples for the SciPy chapter 274 5.12. Full code examples for the SciPy chapter 275
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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()
# 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
(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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.legend()
plt.show()
plt.legend()
plt.show()
5.12. Full code examples for the SciPy chapter 278 5.12. Full code examples for the SciPy chapter 279
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.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, Text(35.472222222222214, 0.5, 'Min and max temperature')
there’s not enough data to say much more.
Total running time of the script: (0 minutes 0.124 seconds) Fitting it to a periodic function
import scipy as sp
5.12. Full code examples for the SciPy chapter 280 5.12. Full code examples for the SciPy chapter 281
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.show()
5.12. Full code examples for the SciPy chapter 282 5.12. Full code examples for the SciPy chapter 283
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
# plot output
plt.figure()
plt.imshow(img2)
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()
5.12. Full code examples for the SciPy chapter 284 5.12. Full code examples for the SciPy chapter 285
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
# In the lines following, we'll make a copy of the original spectrum and
Compute the 2d FFT of the input image # truncate coefficients.
import scipy as sp # Define the fraction of coefficients (in each direction) we keep
keep_fraction = 0.1
im_fft = sp.fft.fft2(im)
# Call ff a copy of the original transform. NumPy arrays have a copy
# Show the results # method for this purpose.
im_fft2 = im_fft.copy()
def plot_spectrum(im_fft): # Set r and c to be the number of rows and columns of the array.
from matplotlib.colors import LogNorm r, c = im_fft2.shape
# A logarithmic colormap # Set to zero all rows with indices between r*keep_fraction and
plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5)) # r*(1-keep_fraction):
(continues on next page) (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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.figure()
plot_spectrum(im_fft2)
plt.title("Filtered Spectrum")
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()
Text(0.5, 1.0, 'Filtered Spectrum') plt.imshow(im_blur, "gray")
plt.title("Blurred image")
Reconstruct the final image plt.show()
# 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, "gray")
plt.title("Reconstructed Image")
5.12. Full code examples for the SciPy chapter 288 5.12. Full code examples for the SciPy chapter 289
Scientific Python Lectures, Edition 2025.1rc0.dev0
CHAPTER 6
Getting help and finding documentation
Total running time of the script: (0 minutes 0.731 seconds) 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.
ã See also
In [1]: help(np.van<TAB>
References to go further
• Some chapters of the advanced and the packages and applications parts of the SciPy lectures In [2]: help(np.vander)
Help on _ArrayFunctionDispatcher in module numpy:
• The SciPy cookbook
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)
5.12. Full code examples for the SciPy chapter 290 291
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
See Also • 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
polynomial.polynomial.polyvander learning by example. More standard documentation is also available.
• In Ipython, the magical function %psearch search for objects matching patterns. This is useful if,
Examples for example, one does not know the exact name of a function.
--------
>>> import numpy as np In [3]: import numpy as np
>>> x = np.array([1, 2, 3, 5])
>>> N = 3 • If everything listed above fails (and Google doesn’t have the answer). . . don’t despair! There is
>>> np.vander(x, N) a vibrant Scientific Python community. Scientific Python is present on various platform. https:
array([[ 1, 1, 1], //scientific-python.org/community/
[ 4, 2, 1],
[ 9, 3, 1], Packages like SciPy and NumPy also have their own channels. Have a look at their respective
[25, 5, 1]]) websites to find out how to engage with users and maintainers.
>>> 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://
numpy.org. The search button is quite useful inside the reference documentation of the two
292 293
Scientific Python Lectures, Edition 2025.1rc0.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.
Part II
Advanced topics
294 295
Scientific Python Lectures, Edition 2025.1rc0.dev0
7
– Examples in the standard library
– Deprecation of functions
– A while-loop removing decorator
– A plugin registration system
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
Author Zbigniew Jędrzejewski-Szmek
An iterator is an object adhering to the iterator protocol — basically this means that it has a next
This section covers some features of the Python language which can be considered advanced — in method, which, when called, returns the next item in the sequence, and when there’s nothing to return,
the sense that not every language has them, and also in the sense that they are more useful in more raises the StopIteration exception.
complicated programs or libraries, but not in the sense of being particularly specialized, or particularly
complicated. 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
It is important to underline that this chapter is purely about the language itself — about features over the same sequence more than once concurrently. Separating the iteration logic from the sequence
supported through special syntax complemented by functionality of the Python stdlib, which could not allows us to have more than one way of iteration.
be implemented through clever external modules.
Calling the __iter__ method on a container to create an iterator object is the most straightforward way
The process of developing the Python programming language, its syntax, is very transparent; proposed to get hold of an iterator. The iter function does that for us, saving a few keystrokes.
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 >>> nums = [1, 2, 3] # note that ... varies: these are different objects
problems and that their use is as simple as possible. >>> iter(nums)
<...iterator object at ...>
>>> nums.__iter__()
Chapter contents <...iterator object at ...>
>>> nums.__reversed__()
• Iterators, generator expressions and generators <...reverseiterator object at ...>
– Iterators
>>> it = iter(nums)
– Generator expressions >>> next(it)
– Generators 1
>>> next(it)
– Bidirectional communication 2
– Chaining generators >>> next(it)
3
• Decorators >>> next(it)
Traceback (most recent call last):
(continues on next page)
(continued from previous page) A third way to create iterator objects is to call a generator function. A generator is a function containing
File "<stdin>", line 1, in <module> the keyword yield. It must be noted that the mere presence of this keyword completely changes the
StopIteration 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
When used in a loop, StopIteration is swallowed and causes the loop to finish. But with explicit the body start to be executed. When a generator is called, the execution stops before the first instruction
invocation, we can see that once the iterator is exhausted, accessing it raises an exception. 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.
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 When next is called, the function is executed until the first yield. Each encountered yield statement
the same way. In order to achieve this, iterators in addition to next are also required to have a method gives a value becomes the return value of next. After executing the yield statement, the execution of
called __iter__ which returns the iterator (self). this function is suspended.
Support for iteration is pervasive in Python: all sequences and unordered containers in the standard >>> def f():
library allow this. The concept is also stretched to other things: e.g. file objects support iteration over ... yield 1
lines. ... yield 2
>>> f()
>>> with open("/etc/fstab") as f: <generator object f at 0x...>
... f is f.__iter__() >>> gen = f()
... >>> next(gen)
True 1
>>> next(gen)
The file is an iterator itself and it’s __iter__ method doesn’t create a separate object: only a single 2
thread of sequential access is allowed. >>> next(gen)
Traceback (most recent call last):
7.1.2 Generator expressions File "<stdin>", line 1, in <module>
StopIteration
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 Let’s go over the life of the single invocation of the generator function.
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. >>> def f():
... print("-- start --")
>>> (i for i in nums) ... yield 3
<generator object <genexpr> at 0x...> ... print("-- finish --")
>>> [i for i in nums] ... yield 4
[1, 2, 3] >>> gen = f()
>>> list(i for i in nums) >>> next(gen)
[1, 2, 3] -- start --
3
The list comprehension syntax also extends to dictionary and set comprehensions. A set is cre- >>> next(gen)
ated when the generator expression is enclosed in curly braces. A dict is created when the generator -- finish --
expression contains “pairs” of the form key:value: 4
>>> next(gen)
>>> {i for i in range(3)}
Traceback (most recent call last):
{0, 1, 2}
...
>>> {i:i**2 for i in range(3)}
StopIteration
{0: 0, 1: 1, 2: 4}
Contrary to a normal function, where executing f() would immediately cause the first print to be
One gotcha should be mentioned: in old Pythons the index variable (i) would leak, and in versions >=
executed, gen is assigned without executing any statements in the function body. Only when gen.
3 this is fixed.
__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.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
Generators 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
A generator is a function that produces a sequence of results instead of a single value. single-threaded, but the interpreter keeps and restores the state in between the requests for the next
David Beazley — A Curious Course on Coroutines and Concurrency 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
7.1. Iterators, generator expressions and generators 298 7.1. Iterators, generator expressions and generators 299
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
done with next methods. Nevertheless, using a function and having the interpreter perform its magic (continued from previous page)
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 >>> it = g()
generator to understand the state which is kept in local variables, as opposed to instance attributes, >>> next(it)
which have to be used to pass data between consecutive invocations of next on an iterator object. --start--
A broader question is why are iterators useful? When an iterator is used to power a loop, the loop --yielding 0--
becomes very simple. The code to initialise the state, to decide if the loop is finished, and to find the 0
next value is extracted into a separate place. This highlights the body of the loop — the interesting >>> it.send(11)
part. In addition, it is possible to reuse the iterator code in other places. --yield returned 11--
--yielding 1--
1
7.1.4 Bidirectional communication >>> it.throw(IndexError)
Each yield statement causes a value to be passed to the caller. This is the reason for the introduction --yield raised IndexError()--
of generators by PEP 255. But communication in the reverse direction is also useful. One obvious way --yielding 2--
would be some external state, either a global variable or a shared mutable object. Direct communication 2
is possible thanks to PEP 342. It is achieved by turning the previously boring yield statement into an >>> it.close()
expression. When the generator resumes execution after a yield statement, the caller can call a method --closing--
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.
7.1.5 Chaining generators
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. ò Note
The second of the new methods is throw(type, value=None, traceback=None) which is equivalent to: This is a preview of PEP 380 (not yet implemented, but accepted for Python 3.3).
raise type, value, traceback
Let’s say we are writing a generator and we want to yield a number of values generated by a second
at the point of the yield statement. generator, a subgenerator. If yielding of values is the only concern, this can be performed without
Unlike raise (which immediately raises an exception from the current execution point), throw() first much difficulty using a loop such as
resumes the generator, and only then raises the exception. The word throw was picked because it subgen = some_other_generator()
is suggestive of putting the exception in another location, and is associated with exceptions in other for v in subgen:
languages. yield v
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 However, if the subgenerator is to interact properly with the caller in the case of calls to send(), throw()
the throw() method. In either case, such an exception propagates in the standard manner: it can and close(), things become considerably more difficult. The yield statement has to be guarded by a
be intercepted by an except or finally clause, or otherwise it causes the execution of the generator try..except..finally structure similar to the one defined in the previous section to “debug” the generator
function to be aborted and propagates in the caller. 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:
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 yield from some_other_generator()
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. 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.
>>> import itertools
>>> def g():
... print('--start--') 7.2 Decorators
... for i in itertools.count():
... print('--yielding %i --' % i)
... try: Summary
... ans = yield i
... except GeneratorExit: This amazing feature appeared in the language almost apologetically and with concern that it might
... print('--closing--') not be that useful.
... raise
Bruce Eckel — An Introduction to Python Decorators
... except Exception as e:
... print('--yield raised %r --' % e)
... else: Since functions and classes are objects, they can be passed around. Since they are mutable objects, they
... print('--yield returned %s --' % ans) can be modified. The act of altering a function or class object after it has been constructed but before
(continues on next page) is is bound to its name is called decorating.
7.1. Iterators, generator expressions and generators 300 7.2. Decorators 301
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
There are two things hiding behind the name “decorator” — one is the function which does the work of 7.2.2 Decorators implemented as classes and as functions
decorating, i.e. performs the real work, and the other one is the expression adhering to the decorator
The only requirement on decorators is that they can be called with a single argument. This means that
syntax, i.e. an at-symbol and the name of the decorating function.
decorators can be implemented as normal functions, or as classes with a __call__ method, or in theory,
Function can be decorated by using the decorator syntax for functions: even as lambda functions.
@decorator # ❷ Let’s compare the function and class approaches. The decorator expression (the part after @) can be
def function(): # ❶ either just a name, or a call. The bare-name approach is nice (less to type, looks cleaner, etc.), but is
pass only possible when no arguments are needed to customise the decorator. Decorators written as functions
can be used in those two cases:
• A function is defined in the standard way. ❶ >>> def simple_decorator(function):
• An expression starting with @ placed before the function definition is the decorator ❷. The part ... print("doing decoration")
after @ must be a simple expression, usually this is just the name of a function or class. This part is ... return function
evaluated first, and after the function defined below is ready, the decorator is called with the newly >>> @simple_decorator
defined function object as the single argument. The value returned by the decorator is attached to ... def function():
the original name of the function. ... print("inside function")
doing decoration
Decorators can be applied to functions and to classes. For classes the semantics are identical — the >>> function()
original class definition is used as an argument to call the decorator and whatever is returned is assigned inside function
under the original name.
Before the decorator syntax was implemented (PEP 318), it was possible to achieve the same effect by >>> def decorator_with_arguments(arg):
assigning the function or class object to a temporary variable and then invoking the decorator explicitly ... print("defining the decorator")
and then assigning the return value to the name of the function. This sounds like more typing, and it ... def _decorator(function):
is, and also the name of the decorated function doubling as a temporary variable must be used at least ... # in this inner function, arg is available too
three times, which is prone to errors. Nevertheless, the example above is equivalent to: ... print("doing decoration, %r " % arg)
... return function
def function(): # ❶ ... return _decorator
pass >>> @decorator_with_arguments("abc")
function = decorator(function) # ❷ ... def function():
... print("inside function")
Decorators can be stacked — the order of application is bottom-to-top, or inside-out. The semantics defining the decorator
are such that the originally defined function is used as an argument for the first decorator, whatever is doing decoration, 'abc'
returned by the first decorator is used as an argument for the second decorator, . . . , and whatever is >>> function()
returned by the last decorator is attached under the name of the original function. inside 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 The two trivial decorators above fall into the category of decorators which return the original function.
operate on the whole function. Because the expression is prefixed with @ is stands out and is hard to If they were to return a new function, an extra level of nestedness would be required. In the worst case,
miss (“in your face”, according to the PEP :) ). When more than one decorator is applied, each one is three levels of nested functions.
placed on a separate line in an easy to read way. >>> def replacing_decorator_with_args(arg):
... print("defining the decorator")
7.2.1 Replacing or tweaking the original object ... def _decorator(function):
... # in this inner function, arg is available too
Decorators can either return the same function or class object or they can return a completely different
... print("doing decoration, %r " % arg)
object. In the first case, the decorator can exploit the fact that function and class objects are mutable
... def _wrapper(*args, **kwargs):
and add attributes, e.g. add a docstring to a class. A decorator might do something useful even without
... print("inside wrapper, %r %r " % (args, kwargs))
modifying the object, for example register the decorated class in a global registry. In the second case,
... return function(*args, **kwargs)
virtually anything is possible: when something different is substituted for the original function or class,
... return _wrapper
the new object can be completely different. Nevertheless, such behaviour is not the purpose of decorators:
... return _decorator
they are intended to tweak the decorated object, not do something unpredictable. Therefore, when a
>>> @replacing_decorator_with_args("abc")
function is “decorated” by replacing it with a different function, the new function usually calls the original
... def function(*args, **kwargs):
function, after doing some preparatory work. Likewise, when a class is “decorated” by replacing if with
... print("inside function, %r %r " % (args, kwargs))
a new class, the new class is usually derived from the original class. When the purpose of the decorator
... return 14
is to do something “every time”, like to log every call to a decorated function, only the second type of
defining the decorator
decorators can be used. On the other hand, if the first type is sufficient, it is better to use it, because it
doing decoration, 'abc'
is simpler.
>>> function(11, 12)
inside wrapper, (11, 12) {}
inside function, (11, 12) {}
(continues on next page)
First, it should be mentioned that there’s a number of useful decorators available in the standard library. def area(self, area):
There are three decorators which really form a part of the language: self.edge = area ** 0.5
• classmethod causes a method to become a “class method”, which means that it can be invoked The way that this works, is that the property decorator replaces the getter method with a property
without creating an instance of the class. When a normal method is invoked, the interpreter inserts object. This object in turn has three methods, getter, setter, and deleter, which can be used
the instance object as the first positional parameter, self. When a class method is invoked, the as decorators. Their job is to set the getter, setter and deleter of the property object (stored as
class itself is given as the first parameter, often called cls. attributes fget, fset, and fdel). The getter can be set like in the example above, when creating
Class methods are still accessible through the class’ namespace, so they don’t pollute the module’s the object. When defining the setter, we already have the property object under area, and we add
namespace. Class methods can be used to provide alternative constructors: 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
class Array(object):
interpreter executes attribute access, assignment, or deletion, the job is delegated to the methods
def __init__(self, data):
of the property object.
self.data = data
To make everything crystal clear, let’s define a “debug” example:
@classmethod
def fromfile(cls, file): >>> class D(object):
data = numpy.load(file) ... @property
return cls(data) ... def a(self):
... print("getting 1")
This is cleaner than using a multitude of flags to __init__. ... return 1
... @a.setter
• staticmethod is applied to methods to make them “static”, i.e. basically a normal function, but ... def a(self, value):
accessible through the class namespace. This can be useful when the function is only needed inside ... print("setting %r " % value)
this class (its name would then be prefixed with _), or when we want the user to think of the ... @a.deleter
method as connected to the class, despite an implementation which doesn’t require this. ... def a(self):
• property is the pythonic answer to the problem of getters and setters. A method decorated with ... print("deleting")
property becomes a getter which is automatically called on attribute access. >>> D.a
<property object at 0x...>
>>> class A(object): >>> D.a.fget
... @property <function ...>
... def a(self): >>> D.a.fset
... "an important attribute" <function ...>
... return "a value" >>> D.a.fdel
>>> A.a <function ...>
<property object at 0x...> >>> d = D() # ... varies, this is not the same `a` function
>>> A().a >>> d.a
'a value' getting 1
1
In this example, A.a is an read-only attribute. It is also documented: help(A) includes the >>> d.a = 2
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
deleting
To have a setter and a getter, two methods are required, obviously: >>> 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
(continues on next page)
7.2.5 Deprecation of functions statements, but then the user would have to explicitly call list(find_answers()).
Let’s say we want to print a deprecation warning on stderr on the first invocation of a function we don’t We can define a decorator which constructs the list for us:
like anymore. If we don’t want to modify the function, we can use a decorator:
def vectorized(generator_func):
class deprecated(object): def wrapper(*args, **kwargs):
"""Print a deprecation warning once on first use of the function. return list(generator_func(*args, **kwargs))
return functools.update_wrapper(wrapper, generator_func)
>>> @deprecated() # doctest: +SKIP
... def f(): Our function then becomes:
... pass
>>> f() # doctest: +SKIP @vectorized
f is deprecated def find_answers():
""" while True:
def __call__(self, func): ans = look_for_next_answer()
self.func = func if ans is None:
self.count = 0 break
return self._wrapper yield ans
def _wrapper(self, *args, **kwargs):
self.count += 1
if self.count == 1: 7.2.7 A plugin registration system
print(self.func.__name__, 'is deprecated') This is a class decorator which doesn’t modify the class, but just puts it in a global registry. It falls into
return self.func(*args, **kwargs) the category of decorators returning the original object:
7.2.6 A while-loop removing decorator 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
Let’s say we have function which returns a lists of things, and this list created by running a loop. If we database (“EM DASH”). If the Unicode character was inserted directly, it would be impossible to
don’t know how many objects will be needed, the standard way to do this is something like: distinguish it from an en-dash in the source of a program.
def find_answers():
answers = [] ã See also
while True:
ans = look_for_next_answer() More examples and reading
if ans is None:
• PEP 318 (function and method decorator syntax)
break
answers.append(ans) • PEP 3129 (class decorator syntax)
return answers
• https://wiki.python.org/moin/PythonDecoratorLibrary
This is fine, as long as the body of the loop is fairly compact. Once it becomes more complicated, as • https://docs.python.org/dev/library/functools.html
often happens in real code, this becomes pretty unreadable. We could simplify this by using yield
exception, if thrown, is propagated. As with files, there’s often a natural operation to perform after the
• https://pypi.org/project/decorator object has been used and it is most convenient to have the support built in. With each release, Python
• Bruce Eckel provides support in more places:
– Decorators I: Introduction to Python Decorators • all file-like objects:
– Python Decorators II: Decorator Arguments – file ➥ automatically closed
– Python Decorators III: A Decorator-Based Build System – fileinput, tempfile
– bz2.BZ2File, gzip.GzipFile, tarfile.TarFile, zipfile.ZipFile
– ftplib, nntplib ➥ close connection
7.3 Context managers
• locks
A context manager is an object with __enter__ and __exit__ methods which can be used in the with
– multiprocessing.RLock ➥ lock and unlock
statement:
– multiprocessing.Semaphore
with manager as var:
do_something(var) – memoryview ➥ automatically release
• decimal.localcontext ➥ modify precision of computations temporarily
is in the simplest case equivalent to
• _winreg.PyHKEY ➥ open and close hive key
var = manager.__enter__()
• warnings.catch_warnings ➥ kill warnings temporarily
try:
do_something(var) • contextlib.closing ➥ the same as the example above, call close
finally:
• parallel programming
manager.__exit__()
– concurrent.futures.ThreadPoolExecutor ➥ invoke in parallel then kill thread pool
In other words, the context manager protocol defined in PEP 343 permits the extraction of the boring
– concurrent.futures.ProcessPoolExecutor ➥ invoke in parallel then kill process pool
part of a try..except..finally structure into a separate class leaving only the interesting do_something
block. – nogil ➥ solve the GIL problem temporarily (cython only :( )
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. 7.3.1 Catching exceptions
2. The block of code underneath with is executed. Just like with try clauses, it can either execute When an exception is thrown in the with-block, it is passed as arguments to __exit__. Three arguments
successfully to the end, or it can break, continue or return, or it can throw an exception. Either are used, the same as returned by sys.exc_info(): type, value, traceback. When no exception is thrown,
way, after the block is finished, the __exit__ method is called. If an exception was thrown, None is used for all three arguments. The context manager can “swallow” the exception by returning a
the information about the exception is passed to __exit__, which is described below in the next true value from __exit__. Exceptions can be easily ignored, because if __exit__ doesn’t use return
subsection. In the normal case, exceptions can be ignored, just like in a finally clause, and will and just falls of the end, None is returned, a false value, and therefore the exception is rethrown after
be rethrown after __exit__ is finished. __exit__ is finished.
Let’s say we want to make sure that a file is closed immediately after we are done writing to it: 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 closing(object):
... def __init__(self, obj): class assert_raises(object):
... self.obj = obj # based on pytest and unittest.TestCase
... def __enter__(self): def __init__(self, type):
... return self.obj self.type = type
... def __exit__(self, *args): def __enter__(self):
... self.obj.close() pass
>>> with closing(open('/tmp/file', 'w')) as f: def __exit__(self, type, value, traceback):
... f.write('the contents\n') if type is None:
raise AssertionError('exception expected')
Here we have made sure that the f.close() is called when the with block is exited. Since closing files is if issubclass(type, self.type):
such a common operation, the support for this is already present in the file class. It has an __exit__ return True # swallow the expected exception
method which calls close and can be used as a context manager itself: 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
8
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: CHAPTER
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. Advanced NumPy
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):
try:
yield obj Author: Pauli Virtanen
finally:
obj.close() 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
Let’s rewrite the assert_raises example as a generator: of its flexibility, taking useful shortcuts.
This section covers:
@contextlib.contextmanager
def assert_raises(type): • Anatomy of NumPy arrays, and its consequences. Tips and tricks.
try:
• Universal functions: what, why, and what to do if you want a new one.
yield
except type: • Integration with other tools: NumPy offers several ways to wrap any data in an ndarray, without
return unnecessary copies.
except Exception as value:
• Recently added features, and what’s in them: PEP 3118 buffers, generalized ufuncs, . . .
raise AssertionError('wrong exception type')
else:
raise AssertionError('exception expected') Prerequisites
Here we use a decorator to turn generator functions into context managers! • NumPy
• Cython
• Pillow (Python imaging library, used in a couple of examples)
Chapter contents
• Life of ndarray
– It’s. . .
– 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 {
PyObject_HEAD
– Generalized ufuncs
• Interoperability features /* Block of memory */
char *data;
– Sharing multidimensional, typed data
– The old buffer protocol /* Data type descriptor */
PyArray_Descr *descr;
– The old buffer protocol
– Array interface protocol /* Indexing scheme */
int nd;
• Array siblings: chararray, maskedarray
npy_intp *dimensions;
– chararray: vectorized string operations npy_intp *strides;
– masked_array missing data
/* Other stuff */
– recarray: purely convenience PyObject *base;
int flags;
• Summary
PyObject *weakreflist;
• Contributing to NumPy/SciPy } PyArrayObject;
– Why
– Reporting bugs 8.1.2 Block of memory
– Contributing to documentation >>> x = np.array([1, 2, 3], dtype=np.int32)
– Contributing features >>> x.data
<... at ...>
– How to help, in general >>> bytes(x.data)
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'
>>> x.__array_interface__
8.1 Life of ndarray {'data': (..., False), 'strides': None, 'descr': [('', '<i4')], 'typestr': '<i4',
˓→'shape': (3,), 'version': 3}
8.1.1 It’s. . . Reminder: two ndarrays may share the same memory:
ndarray =
>>> x = np.array([1, 2, 3, 4])
block of memory + indexing scheme + data type descriptor >>> y = x[:-1]
• raw data >>> x[0] = 9
>>> y
• how to locate an element array([9, 2, 3])
• how to interpret an element
wavreader.py
>>> np.dtype(int).type
<class 'numpy.int64'>
>>> np.dtype(int).itemsize >>> wav_header_dtype['format']
8 dtype('S4')
>>> np.dtype(int).byteorder >>> 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
>>> wav_header_dtype.fields['format']
(dtype('S4'), 8)
• The first element is the sub-dtype in the structured data, corresponding to the name format
• The second one is its offset (in bytes) from the beginning of the item Casting
... 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)
Traceback (most recent call last):
[ ('RIFF', 17402L, 'WAVE', 'fmt ', 16L, 1, 1, 16000L, 32000L, 2, 16, [['d', 'a'], ['t
File "<stdin>", line 1, in <module>
˓→', 'a']], 17366L)]
OverflowError: Python integer 256 out of bounds for int8
>>> wav_header['sample_rate']
>>> y + 256.0
array([16000], dtype=uint32)
array([257., 258., 259., 260.])
>>> y + np.array([256], dtype=np.int32)
Let’s try accessing the sub-array: array([257, 258, 259, 260], dtype=int32)
>>> wav_header['data_id']
array([[['d', 'a'], • Casting on setitem: dtype of the array is not changed on item assignment:
['t', 'a']]],
>>> y[:] = y + 1.5
dtype='|S1')
>>> y
>>> wav_header.shape
array([2, 3, 4, 5], dtype=int8)
(1,)
>>> wav_header['data_id'].shape
(1, 2, 2)
ò Note
When accessing sub-arrays, the dimensions get added to the end! Exact rules: see NumPy documentation
ò Note
Re-interpretation / viewing
There are existing modules such as wavfile, audiolab, etc. for loading sound data. . .
• Data block in memory (4 bytes)
Solution
0x01 0x02 || 0x03 0x04
>>> y = x.view([('r', 'i1'),
... ('g', 'i1'),
... ('b', 'i1'),
ò Note
... ('a', 'i1')]
little-endian: least significant byte is on the left in memory ... )[:, :, 0]
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?
8.1.4 Indexing scheme: strides – C: last dimensions vary fastest (= smaller strides)
ò Note
ò 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 In-place operations with views
the C or F ordering of the bytes in memory.
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
>>> x = np.array([[1, 2, 3], consistent with the non in-place version (e.g. a = a + a.T produces the same result as a += a.T).
... [4, 5, 6]], dtype=np.int16, order='C') Note however that this may result in the data being copied (as if using a += a.T.copy()), ultimately
>>> x.strides resulting in more memory being used than might otherwise be expected for in-place operations!
(6, 2)
>>> x.tobytes('A')
b'\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x00' Slicing with integers
• Everything can be represented by changing only shape, strides, and possibly adjusting the data
• Need to jump 6 bytes to find the next row
pointer!
• Need to jump 2 bytes to find the next column
• Never makes copies of the data
>>> y = np.array(x, order='F')
>>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32)
>>> y.strides
>>> y = x[::-1]
(2, 4)
>>> y
>>> y.tobytes('A')
array([6, 5, 4, 3, 2, 1], dtype=int32)
b'\x01\x00\x04\x00\x02\x00\x05\x00\x03\x00\x06\x00'
>>> y.strides
(-4,)
• Need to jump 2 bytes to find the next row
• Need to jump 4 bytes to find the next column >>> y = x[2:]
>>> y.__array_interface__['data'][0] - x.__array_interface__['data'][0]
• Similarly to higher dimensions: (continues on next page)
. Warning >>> x2 * y2
array([[ 5, 10, 15, 20],
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, )) . . . seems somehow familiar . . .
array([1, 3], dtype=int16)
>>> x[::2] >>> x = np.array([1, 2, 3, 4], dtype=np.int16)
array([1, 3], dtype=int16) >>> y = np.array([5, 6, 7], dtype=np.int16)
(continues on next page)
Using np.diag
>>> y = np.diag(x, k=1)
>>> y
array([2, 6], dtype=int32)
However,
>>> y.flags.owndata
False
• 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): (continued from previous page)
• numexpr is designed to mitigate cache effects when evaluating array expressions. for (i = 0; i < dimensions[0]; ++i) {
*output = elementwise_function(*input_1, *input_2);
• numba is a compiler for Python code, that is aware of numpy arrays. input_1 += steps[0];
input_2 += steps[1];
output += steps[2];
8.1.5 Findings in dissection }
}
char types[3]
where 𝑐 = 𝑥 + 𝑖𝑦 is a complex number. This iteration is repeated – if 𝑧 stays finite no matter how long (continued from previous page)
the iteration runs, 𝑐 belongs to the Mandelbrot set. #
• Make ufunc called mandel(z0, c) that computes:
cdef double complex z = z_in[0]
z = z0 cdef double complex c = c_in[0]
for k in range(iterations): cdef int k # the integer we use in the for loop
z = z*z + c
#
say, 100 iterations or until z.real**2 + z.imag**2 > 1000. Use it to determine which c are in # TODO: write the Mandelbrot iteration for one point here,
the Mandelbrot set. # as you would write it in Python.
#
• Our function is a simple one, so make use of the PyUFunc_* helpers.
# Say, use 100 as the maximum number of iterations, and 1000
• Write it in Cython # as the cutoff for z.real**2 + z.imag**2.
#
import_array()
import_ufunc()
loop_func[0] = PyUFunc_DD_D
input_output_types[0] = NPY_CDOUBLE
input_output_types[1] = NPY_CDOUBLE ò Note
input_output_types[2] = NPY_CDOUBLE
Most of the boilerplate could be automated by these Cython modules:
elementwise_funcs[0] = <void*>mandel_single_point https://github.com/cython/cython/wiki/MarkLodato-CreatingUfuncs
mandel = PyUFunc_FromFuncAndData(
loop_func, Several accepted input types
elementwise_funcs,
input_output_types, E.g. supporting both single- and double-precision versions
1, # number of supported input types cdef void mandel_single_point(double complex *z_in,
2, # number of input args double complex *c_in,
1, # number of output args double complex *z_out) nogil:
0, # `identity` element, never mind this ...
"mandel", # function name
"mandel(z, c) -> computes iterated z*z + c", # docstring cdef void mandel_single_point_singleprec(float complex *z_in,
0 # unused float complex *c_in,
) float complex *z_out) nogil:
...
"""
Plot Mandelbrot cdef PyUFuncGenericFunction loop_funcs[2]
================ cdef char input_output_types[3*2]
cdef void *elementwise_funcs[1*2]
Plot the Mandelbrot ensemble.
(continues on next page) (continues on next page)
mandel = PyUFunc_FromFuncAndData( • matrix multiplication this way could be useful for operating on many small matrices at once
loop_func,
elementwise_funcs, • Also see tensordot and einsum
input_output_types,
2, # number of supported input types <---------------- Generalized ufunc loop
2, # number of input args Matrix multiplication (m,n),(n,p) -> (m,p)
1, # number of output args
0, # `identity` element, never mind this void gufunc_loop(void **args, int *dimensions, int *steps, void *data)
"mandel", # function name {
"mandel(z, c) -> computes iterated z*z + c", # docstring char *input_1 = (char*)args[0]; /* these are as previously */
0 # unused char *input_2 = (char*)args[1];
) char *output = (char*)args[2];
• This is called the “signature” of the generalized ufunc 8.3 Interoperability features
• The dimensions on which the g-ufunc acts, are “core dimensions”
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. (continued from previous page)
ã See also
pilbuffer.py
Q:
Check what happens if data is now modified, and img saved again.
::
The masked_array returns a view to the original array:
>>> from PIL import Image
>>> img = Image.open('data/test.png') >>> mx[1] = 9
>>> img.__array_interface__ >>> x
{'version': 3, array([ 1, 9, 3, -99, 5])
'data': ...,
'shape': (200, 200, 4),
The mask
'typestr': '|u1'}
>>> x = np.asarray(img) You can modify the mask by assigning:
>>> x.shape
(200, 200, 4) >>> mx[1] = np.ma.masked
>>> mx
masked_array(data=[1, --, 3, --, 5],
ò Note mask=[False, True, False, True, False],
fill_value=999999)
A more C-friendly variant of the array interface is also defined.
The mask is cleared on assignment:
>>> mx[1] = 9
8.4 Array siblings: chararray, maskedarray >>> mx
masked_array(data=[1, 9, 3, --, 5],
8.4.1 chararray: vectorized string operations mask=[False, False, False, True, False],
fill_value=999999)
>>> x = np.char.asarray(['a', ' bbb', ' ccc'])
>>> x The mask is also available directly:
chararray(['a', ' bbb', ' ccc'], dtype='<U5')
>>> x.upper() >>> mx.mask
chararray(['A', ' BBB', ' CCC'], dtype='<U5') array([False, False, False, True, False])
The masked entries can be filled with a given value to get an usual array back:
8.4.2 masked_array missing data
>>> x2 = mx.filled(-1)
Masked arrays are arrays that may have missing or invalid entries.
>>> x2
For example, suppose we have an array where the fourth entry is invalid: array([ 1, 9, 3, -1, 5])
One way to describe this is to create a masked array: >>> mx.mask = np.ma.nomask
>>> mx
>>> mx = np.ma.masked_array(x, mask=[0, 0, 0, 1, 0]) masked_array(data=[1, 9, 3, -99, 5],
>>> mx mask=[False, False, False, False, False],
masked_array(data=[1, 2, 3, --, 5], fill_value=999999)
mask=[False, False, False, True, False],
fill_value=999999)
Domain-aware functions
Masked mean ignores masked data:
The masked array package also contains domain-aware functions:
>>> mx.mean()
>>> np.ma.log(np.array([1, 2, -1, -2, 3, -5]))
np.float64(2.75)
masked_array(data=[0.0, 0.693147180559..., --, --, 1.098612288668..., --],
>>> np.mean(mx)
mask=[False, False, True, True, False, True],
np.float64(2.75)
fill_value=1e+20)
8.4. Array siblings: chararray, maskedarray 340 8.4. Array siblings: chararray, maskedarray 341
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> populations.mean(axis=0)
8.6.1 Why
masked_array(data=[40472.72727272727, 18627.272727272728, 42400.0], • “There’s a bug?”
mask=[False, False, False],
fill_value=1e+20) • “I don’t understand what this is supposed to do?”
• “I have this fancy code. Would you like to have it?”
>>> populations.std(axis=0)
masked_array(data=[21087.656489006717, 15625.799814240254, 3322.5062255844787], • “I’d like to help! What can I do?”
mask=[False, False, False],
fill_value=1e+20) 8.6.2 Reporting bugs
Note that Matplotlib knows about masked arrays: • Bug tracker (prefer this)
>>> rng.permutation(12)
8.4.3 recarray: purely convenience array([ 2, 6, 4, 1, 8, 11, 10, 5, 9, 3, 7, 0])
>>> rng.permutation(12.) #doctest: +SKIP
>>> arr = np.array([('a', 1), ('b', 2)], dtype=[('x', 'S1'), ('y', int)]) Traceback (most recent call last):
>>> arr2 = arr.view(np.recarray) File "<stdin>", line 1, in <module>
>>> arr2.x File "_generator.pyx", line 4844, in numpy.random._generator.Generator.permutation
(continues on next page) (continues on next page)
If unsure, try to remove existing NumPy installations, and reinstall. . . • Ask on communication channels:
– numpy-discussion list
8.6.3 Contributing to documentation – scipy-dev list
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: scipy-dev@scipy.org
Hi,
9
9.1 Avoiding bugs
9.1.1 Coding best practices to avoid getting in trouble
“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?”
Debugging code – 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)
Author: Gaël Varoquaux • Give your variables, functions and modules meaningful names (not mathematics names)
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 9.1.2 pyflakes: fast static analysis
to its needs. They are several static analysis tools in Python; to name a few:
• pylint
Prerequisites
• pychecker
• NumPy • pyflakes
• IPython • flake8
• nosetests Here we focus on pyflakes, which is the simplest tool.
• pyflakes • Fast, simple
• gdb for the C-debugging part. • 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
Chapter contents
PEP8 style guide.
• Avoiding bugs Integrating pyflakes (or flake8) in your editor or IDE is highly recommended, it does yield productivity
gains.
– Coding best practices to avoid getting in trouble
– pyflakes: fast static analysis Running pyflakes on the current edited file
• Debugging workflow You can bind a key to run pyflakes in the current buffer.
• Using the Python debugger • In kate Menu: ‘settings -> configure kate
– Invoking the debugger – In plugins enable ‘external tools’
• In TextMate
Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a shell variable:
TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes
autocmd FileType python let &mp = 'echo "*** running % ***" ; pyflakes %' • In emacs
autocmd FileType tex,mp,rst,python imap <Esc>[15~ <C-O>:make!^M Use the flymake mode with pyflakes, documented on https://www.emacswiki.org/emacs/FlyMake
autocmd FileType tex,mp,rst,python map <Esc>[15~ :make!^M and included in Emacs 26 and more recent. To activate it, use M-x (meta-key then x) and enter
autocmd FileType tex,mp,rst,python set autowrite flymake-mode at the prompt. To enable it automatically when opening a Python file, add the
following line to your .emacs file:
• In emacs In your .emacs (binds F5 to pyflakes):
(add-hook 'python-mode-hook '(lambda () (flymake-mode)))
(defun pyflakes-thisfile () (interactive)
(compile (format "pyflakes %s " (buffer-file-name)))
)
9.2 Debugging workflow
(define-minor-mode pyflakes-mode
If you do have a non trivial bug, this is when debugging strategies kick in. There is no silver bullet. Yet,
"Toggle pyflakes mode.
strategies help:
With no argument, this command toggles the mode.
Non-null prefix argument turns on the mode. For debugging a given problem, the favorable situation is when the problem is
Null prefix argument turns off the mode." isolated in a small number of lines of code, outside framework or application
;; The initial value. code, with short modify-run-fail cycles
nil
1. Make it fail reliably. Find a test case that makes the code fail every time.
;; The indicator for the mode line.
" Pyflakes" 2. Divide and Conquer. Once you have a failing test case, isolate the failing code.
;; The minor mode bindings.
• Which module.
'( ([f5] . pyflakes-thisfile) )
) • Which function.
• Which line of code.
(add-hook 'python-mode-hook (lambda () (pyflakes-mode t)))
=> isolate a small reproducible failure: a test case
A type-as-go spell-checker like integration 3. Change one thing at a time and re-run the failing test case.
– Use the pyflakes.vim plugin: 5. Take notes and be patient. It may take a while.
• Walk up and down the call stack. (continued from previous page)
Situation: You’re working in IPython and you get a traceback. -> """Small snippet to raise an IndexError."""
(Pdb) continue
Here we debug the file index_error.py. When running it, an IndexError is raised. Type %debug and
Traceback (most recent call last):
drop into the debugger.
File "/usr/lib64/python3.11/pdb.py", line 1793, in main
In [1]: %run index_error.py pdb._run(target)
--------------------------------------------------------------------------- File "/usr/lib64/python3.11/pdb.py", line 1659, in _run
IndexError Traceback (most recent call last) self.run(target.code)
File ~/src/scientific-python-lectures/advanced/debugging/index_error.py:10 File "/usr/lib64/python3.11/bdb.py", line 600, in run
6 print(lst[len(lst)]) exec(cmd, globals, locals)
9 if __name__ == "__main__": File "<string>", line 1, in <module>
---> 10 index_error() File "/home/jarrod/src/scientific-python-lectures/advanced/debugging/index_error.
˓→py", line 10, in <module>
9.3. Using the Python debugger 350 9.3. Using the Python debugger 351
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• Continue execution to next breakpoint with c(ont(inue)): Raising exception on numerical errors
ipdb> c When we run the wiener_filtering.py file, the following warnings are raised:
> /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_
˓→filtering.py(29)iterated_wiener()
In [2]: %run wiener_filtering.py
27 Do not use this: this is crappy code to demo bugs! /home/jarrod/src/scientific-python-lectures/advanced/debugging/wiener_filtering.
˓→py:35: RuntimeWarning: divide by zero encountered in divide
28 """
1--> 29 noisy_img = noisy_img noise_level = 1 - noise / l_var
30 denoised_img = local_mean(noisy_img, size=size)
We can turn these warnings in exception, which enables us to do post-mortem debugging on them,
31 l_var = local_var(noisy_img, size=size)
and find our problem more quickly:
• Step into code with n(ext) and s(tep): next jumps to the next statement in the current execution In [3]: np.seterr(all='raise')
context, while step will go across execution contexts, i.e. enable exploring inside function calls: Out[3]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
9.3. Using the Python debugger 352 9.3. Using the Python debugger
FloatingPointError: divide by zero encountered in divide 353
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
9.3. Using the Python debugger 354 9.4. Debugging segmentation faults using gdb 355
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
(continued from previous page) Thus the segfault happens when printing big_array[-10:]. The reason is simply that big_array has
src=<value optimized out>, myfunc=0x496780 <_strided_byte_copy>, been allocated with its end outside the program memory.
swap=0)
at numpy/core/src/multiarray/ctors.c:748
ò Note
748 myfunc(dit->dataptr, dest->strides[maxaxis],
For a list of Python-specific commands defined in the gdbinit, read the source of this file.
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= Wrap up exercise
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␣ The following script is well documented and hopefully legible. It seeks to answer a problem of actual
˓→0x85371b0>, _nc=<module at remote 0xb7f93a64>), throwflag=0) interest for numerical computing, but it does not work. . . Can you debug it?
at ../Python/ceval.c:3750 Python source code: to_debug.py
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␣
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
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
9.4. Debugging segmentation faults using gdb 356 9.4. Debugging segmentation faults using gdb 357
Scientific Python Lectures, Edition 2025.1rc0.dev0
10
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.
CHAPTER
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.1 Timeit
In IPython, use timeit (https://docs.python.org/3/library/timeit.html) to time elementary operations:
Donald Knuth In [1]: import numpy as np
“Premature optimization is the root of all evil”
In [2]: a = np.arange(1000)
Author: Gaël Varoquaux In [3]: %timeit a ** 2
This chapter deals with strategies to make Python code go faster. 950 ns +- 1.49 ns per loop (mean +- std. dev. of 7 runs, 1,000,000 loops each)
• Optimization workflow
ò Note
• Profiling Python code
For long running calls, using %time instead of %timeit; it is less precise but faster
– Timeit
– Profiler
– Line-profiler
10.2.2 Profiler
• Making code go faster Useful when you have a large program to profile, for example the following file:
– Algorithmic optimization # For this example to run, you also need the 'ica.py' file
∗ Example of the SVD import numpy as np
(continues on next page)
Similar profiling can be done outside of IPython, simply calling the built-in Python profilers cProfile
ò Note and profile.
This is a combination of two unsupervised learning techniques, principal component analysis (PCA) $ python -m cProfile -o demo.prof demo.py
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 Using the -o switch will output the profiler results to the file demo.prof to view with an external
separation technique, for example to unmix multiple signals that have been recorded through multiple tool. This can be useful if you wish to process the profiler output with a visualization tool.
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.
10.2.3 Line-profiler
To run it, you also need to download the ica module. In IPython we can time the script: 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
In [6]: %run -t demo.py with @profile (no need to import it)
IPython CPU timings (estimated):
User : 14.3929 s. @profile
System: 0.256016 s. def test():
rng = np.random.default_rng()
and profile it: data = rng.random((5000, 100))
u, s, v = linalg.svd(data)
In [7]: %run -p demo.py pca = u[:, :10] @ data
916 function calls in 14.551 CPU seconds results = fastica(pca.T, whiten=False)
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno (function) Then we run the script using the kernprof command, with switches -l, --line-by-line and -v,
1 14.457 14.457 14.479 14.479 decomp.py:849 (svd) --view to use the line-by-line profiler and view the results in addition to saving them:
1 0.054 0.054 0.054 0.054 {method 'random_sample' of 'mtrand.
˓→RandomState' objects} $ kernprof -l -v demo.py
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} Wrote profile results to demo.py.lprof
2 0.005 0.002 0.005 0.002 {method 'any' of 'numpy.ndarray' objects} Timer unit: 1e-06 s
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) Total time: 1.27874 s
14 0.001 0.000 0.001 0.000 {numpy.linalg.lapack_lite.dsyevd} File: demo.py
19 0.001 0.000 0.001 0.000 twodim_base.py:204 (diag) Function: test at line 9
1 0.001 0.001 0.008 0.008 ica.py:69 (_ica_par)
1 0.001 0.001 14.551 14.551 {execfile} Line # Hits Time Per Hit % Time Line Contents
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) 9 @profile
7 0.000 0.000 0.002 0.000 linalg.py:841 (eigh) 10 def test():
172 0.000 0.000 0.000 0.000 {isinstance} 11 1 69.0 69.0 0.0 rng = np.random.default_rng()
(continues on next page) (continues on next page)
10.2. Profiling Python code 360 10.2. Profiling Python code 361
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
10.3. Making code go faster 362 10.4. Writing faster numerical code 363
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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 [32]: c = np.ascontiguousarray(a.T)
In [33]: %timeit b @ c
10.1 ms +- 158 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:
Using numexpr can be useful to automatically optimize code for such effects.
• Use compiled code
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 consid-
erations.
10.4. Writing faster numerical code 364 10.4. Writing faster numerical code 365
Scientific Python Lectures, Edition 2025.1rc0.dev0
11
Text(...'memory [MB]')
CHAPTER • 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.
Author: Robert Cimrman – nonzero at (i, j) means that the document i contains the word j
• ...
11.1.4 Prerequisites
• numpy
11.1 Introduction • scipy
– positive offset = above with 9 stored elements (3 diagonals) and shape (4, 4)>
Coords Values
• fast matrix * vector (sparsetools) (0, 0) 1
• fast and easy item-wise operations (1, 1) 2
(2, 2) 3
– manipulate data array directly (fast NumPy machinery) (3, 3) 4
• constructor accepts: (1, 0) 5
(2, 1) 6
– dense array/matrix (3, 2) 7
– sparse array/matrix (0, 2) 11
(1, 3) 12
– shape tuple (create empty array) >>> mtx.toarray()
– (data, offsets) tuple array([[ 1, 0, 11, 0],
[ 5, 2, 0, 12],
• no slicing, no individual item access [ 0, 6, 3, 0],
• use: [ 0, 0, 7, 4]])
(continued from previous page) ∗ facilitates efficient construction of finite element matrices
<Dictionary Of Keys sparse array of dtype 'float64'
with 20 stored elements and shape (5, 5)> Examples
>>> mtx.toarray()
array([[0., 1., 1., 1., 1.], • create empty COO array:
[1., 0., 1., 1., 1.],
>>> mtx = sp.sparse.coo_array((3, 4), dtype=np.int8)
[1., 1., 0., 1., 1.],
>>> mtx.toarray()
[1., 1., 1., 0., 1.],
array([[0, 0, 0, 0],
[1., 1., 1., 1., 0.]])
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
• slicing and indexing:
– three NumPy arrays: row, col, data. >>> row = np.array([0, 0, 1, 3, 1, 0, 0])
>>> col = np.array([0, 2, 1, 3, 1, 0, 0])
– attribute coords is the tuple (row, col)
>>> data = np.array([1, 1, 1, 1, 1, 1, 1])
– data[i] is value at (row[i], col[i]) position >>> mtx = sp.sparse.coo_array((data, (row, col)), shape=(4, 4))
>>> mtx.toarray()
– permits duplicate entries
array([[3, 0, 1, 0],
– subclass of _data_matrix (sparse matrix classes with .data attribute) [0, 2, 0, 0],
[0, 0, 0, 0],
• fast format for constructing sparse arrays
[0, 0, 0, 1]])
• constructor accepts:
– dense array/matrix • no slicing. . . :
• no slicing, no arithmetic (directly, converts to CSR) – three NumPy arrays: indices, indptr, data
– facilitates fast conversion among sparse formats ∗ data is array of corresponding nonzero values
– when converting to other format (usually CSR or CSC), duplicate entries are summed ∗ indptr points to row starts in indices and data
together ∗ 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
>>> data = np.array([1, 2, 3, 4, 5, 6])
indices[indptr[i]:indptr[i + 1]]
>>> indices = np.array([0, 2, 2, 0, 1, 2])
∗ item (i, j) can be accessed as data[indptr[i] + k], where k is position of j in in- >>> indptr = np.array([0, 2, 3, 6])
dices[indptr[i]:indptr[i + 1]] >>> mtx = sp.sparse.csr_array((data, indices, indptr), shape=(3, 3))
>>> mtx.toarray()
– subclass of _cs_matrix (common CSR/CSC functionality)
array([[1, 0, 2],
∗ subclass of _data_matrix (sparse array classes with .data attribute) [0, 0, 3],
[4, 5, 6]])
• fast matrix vector products and other arithmetic (sparsetools)
• constructor accepts:
– dense array/matrix
Compressed Sparse Column Format (CSC)
– sparse array/matrix
• column oriented
– shape tuple (create empty array)
– three NumPy arrays: indices, indptr, data
– (data, coords) tuple
∗ indices is array of row indices
– (data, indices, indptr) tuple
∗ data is array of corresponding nonzero values
• efficient row slicing, row-oriented operations
∗ indptr points to column starts in indices and data
• slow column slicing, expensive changes to the sparsity structure
∗ length is n_col + 1, last item = number of values = length of both indices and
• use: data
– actual computations (most linear solvers support this format) ∗ nonzero values of the i-th column are data[indptr[i]:indptr[i+1]] with row indices
indices[indptr[i]:indptr[i+1]]
Examples
∗ item (i, j) can be accessed as data[indptr[j]+k], where k is position of i in in-
• create empty CSR array: dices[indptr[j]:indptr[j+1]]
– subclass of _cs_matrix (common CSR/CSC functionality)
>>> mtx = sp.sparse.csr_array((3, 4), dtype=np.int8)
>>> mtx.toarray() ∗ subclass of _data_matrix (sparse array classes with .data attribute)
array([[0, 0, 0, 0],
• fast matrix vector products and other arithmetic (sparsetools)
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8) • constructor accepts:
– dense array/matrix
• create using (data, coords) tuple:
– sparse array/matrix
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2]) – shape tuple (create empty array)
>>> data = np.array([1, 2, 3, 4, 5, 6]) – (data, coords) tuple
>>> mtx = sp.sparse.csr_array((data, (row, col)), shape=(3, 3))
>>> mtx – (data, indices, indptr) tuple
<Compressed Sparse Row sparse array of dtype 'int64' • efficient column slicing, column-oriented operations
with 6 stored elements and shape (3, 3)>
>>> mtx.toarray() • slow row slicing, expensive changes to the sparsity structure
array([[1, 0, 2], • use:
[0, 0, 3],
[4, 5, 6]]...) – actual computations (most linear solvers support this format)
>>> mtx.data
array([1, 2, 3, 4, 5, 6]...) Examples
>>> mtx.indices
array([0, 2, 2, 0, 1, 2]) • create empty CSC array:
>>> 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)
• create using (data, coords) tuple: • many arithmetic operations considerably more efficient than CSR for sparse matrices with dense
sub-matrices
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2]) • use:
>>> data = np.array([1, 2, 3, 4, 5, 6]) – like CSR
>>> mtx = sp.sparse.csc_array((data, (row, col)), shape=(3, 3))
>>> mtx – vector-valued finite element discretizations
<Compressed Sparse Column sparse array of dtype 'int64'
with 6 stored elements and shape (3, 3)> Examples
>>> mtx.toarray()
array([[1, 0, 2], • create empty BSR array with (1, 1) block size (like CSR. . . ):
[0, 0, 3],
>>> mtx = sp.sparse.bsr_array((3, 4), dtype=np.int8)
[4, 5, 6]]...)
>>> mtx
>>> mtx.data
<Block Sparse Row sparse array of dtype 'int8'
array([1, 4, 5, 2, 3, 6]...)
with 0 stored elements (blocksize=1x1) and shape (3, 4)>
>>> mtx.indices
>>> mtx.toarray()
array([0, 2, 2, 0, 1, 2])
array([[0, 0, 0, 0],
>>> mtx.indptr
[0, 0, 0, 0],
array([0, 2, 3, 6])
[0, 0, 0, 0]], dtype=int8)
• create using (data, indices, indptr) tuple:
• create empty BSR array with (3, 2) block size:
>>> data = np.array([1, 4, 5, 2, 3, 6])
>>> mtx = sp.sparse.bsr_array((3, 4), blocksize=(3, 2), dtype=np.int8)
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> mtx
>>> indptr = np.array([0, 2, 3, 6])
<Block Sparse Row sparse array of dtype 'int8'
>>> mtx = sp.sparse.csc_array((data, indices, indptr), shape=(3, 3))
with 0 stored elements (blocksize=3x2) and shape (3, 4)>
>>> mtx.toarray()
>>> mtx.toarray()
array([[1, 0, 2],
array([[0, 0, 0, 0],
[0, 0, 3],
[0, 0, 0, 0],
[4, 5, 6]])
[0, 0, 0, 0]], dtype=int8)
– a bug?
Block Compressed Row Format (BSR) • create using (data, coords) tuple with (1, 1) block size (like CSR. . . ):
• basically a CSR with dense sub-matrices of fixed shape instead of scalar items >>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
– block size (R, C) must evenly divide the shape of the matrix (M, N)
>>> data = np.array([1, 2, 3, 4, 5, 6])
– three NumPy arrays: indices, indptr, data >>> mtx = sp.sparse.bsr_array((data, (row, col)), shape=(3, 3))
>>> mtx
∗ indices is array of column indices for each block
<Block Sparse Row sparse array of dtype 'int64'
∗ data is array of corresponding nonzero values of shape (nnz, R, C) with 6 stored elements (blocksize=1x1) and shape (3, 3)>
>>> mtx.toarray()
∗ ...
array([[1, 0, 2],
– subclass of _cs_matrix (common CSR/CSC functionality) [0, 0, 3],
[4, 5, 6]]...)
∗ subclass of _data_matrix (sparse matrix classes with .data attribute)
>>> mtx.data
• fast matrix vector products and other arithmetic (sparsetools) array([[[1]],
• constructor accepts:
[[2]],
– dense array/matrix
[[3]],
– sparse array/matrix
– shape tuple (create empty array) [[4]],
– (data, coords) tuple
[[5]],
– (data, indices, indptr) tuple
[[6]]]...)
(continues on next page)
[[2, 2],
[2, 2]],
[[3, 3],
11.3 Linear System Solvers
[3, 3]], • sparse matrix/eigenvalue problem solvers live in scipy.sparse.linalg
[[4, 4], • the submodules:
[4, 4]], – dsolve: direct factorization methods for solving linear systems
[[5, 5], – isolve: iterative methods for solving linear systems
[5, 5]], – eigen: sparse eigenvalue problem solvers
[[6, 6], • all solvers are accessible from:
[6, 6]]])
>>> import scipy as sp
>>> sp.sparse.linalg.__all__
['ArpackError', 'ArpackNoConvergence', ..., 'use_solver']
Examples
"""
• import the whole module, and see its docstring: Solve a linear system
=======================
>>> help(sp.sparse.linalg.spsolve)
Help on function spsolve in module scipy.sparse.linalg._dsolve.linsolve: 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.
• both superlu and umfpack can be used (if the latter is installed) as follows: """
– prepare a linear system:
import numpy as np
>>> import numpy as np import scipy as sp
>>> mtx = sp.sparse.spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5,␣ import matplotlib.pyplot as plt
˓→5, "csc")
11.3. Linear System Solvers 382 11.3. Linear System Solvers 383
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
x0
"""
[{array, matrix}] Starting guess for the solution.
Compute eigenvectors and eigenvalues using a preconditioned eigensolver
tol =======================================================================
[float] Relative tolerance to achieve before terminating.
In this example Smoothed Aggregation (SA) is used to precondition
maxiter
the LOBPCG eigensolver on a two-dimensional Poisson problem with
[integer] Maximum number of iterations. Iteration will stop after maxiter steps even if the
Dirichlet boundary conditions.
specified tolerance has not been achieved.
"""
M
[{sparse array/matrix, dense array/matrix, LinearOperator}] Preconditioner for A. The pre- import numpy as np
conditioner should approximate the inverse of A. Effective preconditioning dramatically im- import scipy as sp
proves the rate of convergence, which implies that fewer iterations are needed to reach a given import matplotlib.pyplot as plt
error tolerance.
from pyamg import smoothed_aggregation_solver
callback
from pyamg.gallery import poisson
[function] User-supplied function to call after each iteration. It is called as callback(xk), where
xk is the current solution vector.
N = 100
K = 9
LinearOperator Class A = poisson((N, N), format="csr")
• common interface for performing matrix vector products
# create the AMG hierarchy
• useful abstraction that enables using dense and sparse matrices within the solvers, as well as ml = smoothed_aggregation_solver(A)
matrix-free solutions
• has shape and matvec() (+ some optional parameters) # initial approximation to the K eigenvectors
X = np.random.random((A.shape[0], K))
• example:
# preconditioner based on ml
>>> import numpy as np
M = ml.aspreconditioner()
>>> import scipy as sp
>>> def mv(v):
# compute eigenvalues and eigenvectors with LOBPCG
... return np.array([2 * v[0], 3 * v[1]])
W, V = sp.sparse.linalg.lobpcg(A, X, M=M, tol=1e-8, largest=False)
...
>>> A = sp.sparse.linalg.LinearOperator((2, 2), matvec=mv)
>>> A
# plot the eigenvectors
<2x2 _CustomLinearOperator with dtype=int8>
plt.figure(figsize=(9, 9))
>>> A.matvec(np.ones(2))
array([2., 3.])
for i in range(K):
>>> A * np.ones(2)
plt.subplot(3, 3, i + 1)
array([2., 3.])
plt.title(f"Eigenvector { i} ")
plt.pcolor(V[:, i].reshape(N, N))
A Few Notes on Preconditioning plt.axis("equal")
plt.axis("off")
• problem specific plt.show()
• often hard to develop
– examples/pyamg_with_lobpcg.py
• if not sure, try ILU
• example by Nils Wagner:
– available in scipy.sparse.linalg as spilu()
– 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
• lobpcg (Locally Optimal Block Preconditioned Conjugate Gradient Method) * works very well in [ 0.06250083 0.06250028 0.06250007]
combination with PyAMG * example by Nathan Bell:
Exact eigenvalues
(continues on next page)
11.3. Linear System Solvers 384 11.3. Linear System Solvers 385
Scientific Python Lectures, Edition 2025.1rc0.dev0
CHAPTER 12
Image manipulation and processing
using NumPy and SciPy
– https://github.com/pyamg/pyamg
• Pysparse Image = 2-D numerical array
– own sparse matrix classes
(or 3-D: CT, MRI, 2D + time; 4-D, . . . )
– matrix and eigenvalue problem solvers
Here, image == NumPy array np.array
– https://pysparse.sourceforge.net/
Tools used in this tutorial:
• numpy: basic array manipulation
• scipy: scipy.ndimage submodule dedicated to image processing (n-dimensional images). See the
documentation:
Chapters contents
• Measuring objects properties: scipy.ndimage.measurements dtype is uint8 for 8-bit images (0-255)
• Full code examples Opening raw files (camera, 3-D images)
• Examples for the image processing chapter
>>> face.tofile('face.raw') # Create raw file
>>> face_from_raw = np.fromfile('face.raw', dtype=np.uint8)
>>> face_from_raw.shape
(2359296,)
12.1 Opening and writing to image files >>> face_from_raw.shape = (768, 1024, 3)
Writing an array to a file: Need to know the shape and dtype of the image (how to separate data bytes).
import scipy as sp For large data, use np.memmap for memory mapping:
import imageio.v3 as iio
>>> face_memmap = np.memmap('face.raw', dtype=np.uint8, shape=(768, 1024, 3))
f = sp.datasets.face()
iio.imwrite("face.png", f) # uses the Image module (PIL) (data are read from the file, and not loaded into memory)
Working on a list of image files
import matplotlib.pyplot as plt
>>> rng = np.random.default_rng(27446968)
plt.imshow(f) >>> for i in range(10):
plt.show() ... im = rng.integers(0, 256, 10000, dtype=np.uint8).reshape((100, 100))
(continues on next page)
12.1. Opening and writing to image files 388 12.1. Opening and writing to image files 389
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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]
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='bilinear') np.uint8(127)
<matplotlib.image.AxesImage object at 0x...> >>> # Slicing
>>> plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest') >>> face[10:13, 20:23]
<matplotlib.image.AxesImage object at 0x...> array([[141, 153, 145],
[133, 134, 125],
[ 96, 92, 94]], dtype=uint8)
>>> face[100:120] = 255
ã See also
>>>
More interpolation methods are in Matplotlib’s examples. >>> lx, ly = face.shape
>>> X, Y = np.ogrid[0:lx, 0:ly]
>>> mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4
(continues on next page)
Exercise
• Save the array to two different file formats (png, jpg, tiff) Uniform filter
Exercise: denoising
12.4.3 Denoising
• Create a binary image (of 0s and 1s) with several objects (circles, ellipses, squares, or random
Noisy face:
shapes).
>>> f = sp.datasets.face(gray=True) • Add some noise (e.g., 20% of noise)
>>> f = f[230:290, 220:320]
>>> rng = np.random.default_rng() • Try two different denoising methods for denoising the image: gaussian filtering and median
>>> noisy = f + 0.4 * f.std() * rng.random(f.shape) filtering.
• Compare the histograms of the two different denoised images. Which one is the closest to the
A Gaussian filter smoothes the noise out. . . and the edges as well: histogram of the original (noise-free) image?
>>> gauss_denoised = sp.ndimage.gaussian_filter(noisy, 2)
Most local linear isotropic filters blur the image (scipy.ndimage.uniform_filter) ã See also
A median filter preserves better the edges: More denoising filters are available in skimage.denoising, see the scikit-image: image processing
tutorial.
>>> 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]])
>>> 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]])
>>> # 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],
(continues on next page)
Check that reconstruction operations (erosion + propagation) produce a better result than open-
>>> l = 100
>>> x, y = np.indices((l, l))
>>> # 4 circles
>>> img = circle1 + circle2 + circle3 + circle4
>>> mask = img.astype(bool)
>>> img = img.astype(float)
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
processing.
ã See also
12.6 Measuring objects properties: scipy.ndimage.measurements
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. Synthetic data:
>>> from sklearn.feature_extraction import image
12.5. Feature extraction 400 12.6. Measuring objects properties: scipy.ndimage.measurements 401
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> 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()
12.6. Measuring objects properties: scipy.ndimage.measurements 402 12.6. Measuring objects properties: scipy.ndimage.measurements 403
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> 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)
12.6. Measuring objects properties: scipy.ndimage.measurements 404 12.7. Full code examples 405
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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="gray")
plt.axis("off")
plt.subplot(1, 2, 2)
plt.imshow(f[320:340, 510:530], cmap="gray", interpolation="nearest")
plt.axis("off")
import scipy as sp
import imageio.v3 as iio 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.
f = sp.datasets.face()
iio.imwrite("face.png", f) # uses the Image module (PIL)
plt.imshow(f)
plt.show()
12.8. Examples for the image processing chapter 406 12.8. Examples for the image processing chapter 407
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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="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.200 seconds)
block_mean.shape = (sx // 4, sy // 6)
plt.figure(figsize=(5, 5))
plt.imshow(block_mean, cmap="gray") 12.8.5 Radial mean
plt.axis("off") This example shows how to do a radial mean with scikit-image.
plt.show()
12.8. Examples for the image processing chapter 408 12.8. Examples for the image processing chapter 409
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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="gray")
plt.subplot(132)
plt.imshow(f, cmap="gray", vmin=30, vmax=200)
plt.axis("off")
import numpy as np
import scipy as sp plt.subplot(133)
import matplotlib.pyplot as plt plt.imshow(f, cmap="gray")
plt.contour(f, [50, 200])
f = sp.datasets.face(gray=True) plt.axis("off")
sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy] plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.05, right=0.
˓→99)
plt.show()
r = np.hypot(X - sx / 2, Y - sy / 2)
Total running time of the script: (0 minutes 0.411 seconds)
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))
12.8.7 Image sharpening
plt.axes((0, 0, 1, 1)) This example shows how to sharpen an image in noiseless situation by applying the filter inverse to the
plt.imshow(rbin, cmap="nipy_spectral") blur.
plt.axis("off")
plt.show()
12.8. Examples for the image processing chapter 410 12.8. Examples for the image processing chapter 411
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.axis("off")
plt.show()
plt.tight_layout()
plt.show() Total running time of the script: (0 minutes 0.361 seconds)
12.8. Examples for the image processing chapter 412 12.8. Examples for the image processing chapter 413
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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]
12.8. Examples for the image processing chapter 414 12.8. Examples for the image processing chapter 415
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.215 seconds) 12.8.13 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
import numpy as np
import scipy as sp
from skimage.restoration import denoise_tv_chambolle
import matplotlib.pyplot as plt
rng = np.random.default_rng(27446968)
face = sp.datasets.face(gray=True)
lx, ly = face.shape
f = sp.datasets.face(gray=True)
# Cropping
f = f[230:290, 220:320]
crop_face = face[lx // 4 : -lx // 4, ly // 4 : -ly // 4]
# up <-> down flip
noisy = f + 0.4 * f.std() * rng.random(f.shape)
flip_ud_face = np.flipud(face)
# rotation
tv_denoised = denoise_tv_chambolle(noisy, weight=10)
rotate_face = sp.ndimage.rotate(face, 45)
rotate_face_noreshape = sp.ndimage.rotate(face, 45, reshape=False)
plt.figure(figsize=(12, 2.8))
plt.figure(figsize=(12.5, 2.5))
plt.subplot(131)
plt.imshow(noisy, cmap="gray", vmin=40, vmax=220)
plt.subplot(151)
plt.axis("off")
plt.imshow(face, cmap="gray")
plt.title("noisy", fontsize=20)
plt.axis("off")
plt.subplot(132)
plt.subplot(152)
plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220)
plt.imshow(crop_face, cmap="gray")
plt.axis("off")
plt.axis("off")
(continues on next page)
(continues on next page)
12.8. Examples for the image processing chapter 416 12.8. Examples for the image processing chapter 417
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1)) # Find the largest connected component
mask_size = sizes < 1000 sizes = sp.ndimage.sum(mask, label_im, range(nb_labels + 1))
remove_pixel = mask_size[label_im] mask_size = sizes < 1000
(continues on next page) (continues on next page)
12.8. Examples for the image processing chapter 418 12.8. Examples for the image processing chapter 419
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(27446968) import scipy as sp
import matplotlib.pyplot as plt
im = np.zeros((20, 20))
im[5:-5, 5:-5] = 1 rng = np.random.default_rng(27446968)
im = sp.ndimage.distance_transform_bf(im) n = 10
im_noise = im + 0.2 * rng.normal(size=im.shape) l = 256
im = np.zeros((l, l))
im_med = sp.ndimage.median_filter(im_noise, 3) points = l * rng.random((2, n**2))
im[(points[0]).astype(int), (points[1]).astype(int)] = 1
plt.figure(figsize=(16, 5)) im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n))
12.8. Examples for the image processing chapter 420 12.8. Examples for the image processing chapter 421
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.subplot(133) plt.show()
plt.imshow(binary_img, cmap="gray", interpolation="nearest")
plt.axis("off") Total running time of the script: (0 minutes 0.049 seconds)
import numpy as np
import scipy as sp
import numpy as np import matplotlib.pyplot as plt
import scipy as sp
import matplotlib.pyplot as plt rng = np.random.default_rng(27446968)
12.8. Examples for the image processing chapter 422 12.8. Examples for the image processing chapter 423
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.subplot(144) plt.subplot(141)
plt.imshow(sob) plt.imshow(binary_img[:l, :l], cmap="gray")
plt.axis("off") plt.axis("off")
plt.title("Sobel for noisy image", fontsize=20) plt.subplot(142)
plt.imshow(open_img[:l, :l], cmap="gray")
plt.axis("off")
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=0.9) plt.subplot(143)
plt.imshow(close_img[:l, :l], cmap="gray")
plt.show() plt.axis("off")
plt.subplot(144)
Total running time of the script: (0 minutes 0.196 seconds) plt.imshow(mask[:l, :l], cmap="gray")
plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r")
plt.axis("off")
12.8.20 Cleaning segmentation with mathematical morphology plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)
An example showing how to clean segmentation with mathematical morphology: removing small regions
and holes. plt.show()
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))
(continues on next page)
12.8. Examples for the image processing chapter 424 12.8. Examples for the image processing chapter 425
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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)) import numpy as np
from skimage.segmentation import watershed
mask = (im > im.mean()).astype(float) from skimage.feature import peak_local_max
import matplotlib.pyplot as plt
import scipy as sp
img = mask + 0.3 * rng.normal(size=mask.shape)
# Generate an initial image with two overlapping circles
hist, bin_edges = np.histogram(img, bins=60) x, y = np.indices((80, 80))
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) x1, y1, x2, y2 = 28, 28, 44, 52
r1, r2 = 16, 20
classif = GaussianMixture(n_components=2) mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2
classif.fit(img.reshape((img.size, 1))) mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2
image = np.logical_or(mask_circle1, mask_circle2)
threshold = np.mean(classif.means_) # Now we want to separate the two objects in image
binary_img = img > threshold # Generate the markers as local maxima of the distance
# to the background
distance = sp.ndimage.distance_transform_edt(image)
plt.figure(figsize=(11, 4)) peak_idx = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image)
peak_mask = np.zeros_like(distance, dtype=bool)
plt.subplot(131) peak_mask[tuple(peak_idx.T)] = True
plt.imshow(img) markers = sp.ndimage.label(peak_mask)[0]
plt.axis("off") labels = watershed(-distance, markers, mask=image)
plt.subplot(132)
plt.plot(bin_centers, hist, lw=2) plt.figure(figsize=(9, 3.5))
plt.axvline(0.5, color="r", ls="--", lw=2) plt.subplot(131)
plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) plt.imshow(image, cmap="gray", interpolation="nearest")
plt.yticks([]) plt.axis("off")
plt.subplot(133) plt.subplot(132)
plt.imshow(binary_img, cmap="gray", interpolation="nearest") plt.imshow(-distance, interpolation="nearest")
plt.axis("off") plt.axis("off")
plt.subplot(133)
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) (continues on next page)
(continues on next page)
12.8. Examples for the image processing chapter 426 12.8. Examples for the image processing chapter 427
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.subplot(121)
12.8.23 Granulometry plt.imshow(mask, cmap="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.show()
import numpy as np
import scipy as sp 12.8.24 Segmentation with spectral clustering
import matplotlib.pyplot as plt This example uses spectral clustering to do segmentation.
import numpy as np
def disk_structure(n): import matplotlib.pyplot as plt
struct = np.zeros((2 * n + 1, 2 * n + 1))
x, y = np.indices((2 * n + 1, 2 * n + 1)) from sklearn.feature_extraction import image
mask = (x - n) ** 2 + (y - n) ** 2 <= n**2 from sklearn.cluster import spectral_clustering
struct[mask] = 1
return struct.astype(bool) l = 100
x, y = np.indices((l, l))
12.8. Examples for the image processing chapter 428 12.8. Examples for the image processing chapter 429
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.figure(figsize=(6, 3))
plt.subplot(121)
plt.imshow(img, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.imshow(label_im, cmap="nipy_spectral", interpolation="nearest")
plt.axis("off")
plt.show()
12.8. Examples for the image processing chapter 430 12.8. Examples for the image processing chapter 431
Scientific Python Lectures, Edition 2025.1rc0.dev0
Chapters contents
13
• Knowing your problem
– Convex versus non-convex optimization
– Smooth and non-smooth problems
– Noisy versus exact cost functions
CHAPTER
– Constraints
• A review of the different optimizers
– Getting started: 1D optimization
– Gradient based methods
– Newton and quasi-newton methods
• Full code examples
Mathematical optimization: finding • Examples for the mathematical optimization chapter
minima of functions
– Gradient-less methods
– Global optimizers
• Practical guide to optimization with SciPy
– Choosing a method
– Making your optimizer faster
– Computing gradients
Authors: Gaël Varoquaux – Synthetic exercises
Mathematical optimization deals with the problem of finding numerically minimums (or maximums or • Special case: non-linear least-squares
zeros) of a function. In this context, the function is called cost function, or objective function, or energy.
– Minimizing the norm of a vector function
Here, we are interested in using scipy.optimize for black-box optimization: we do not rely on the
– Curve fitting
mathematical expression of the function that we are optimizing. Note that this expression can often be
used for more efficient, non black-box, optimization. • Optimization with constraints
– Box bounds
Prerequisites – General constraints
• NumPy • Full code examples
• SciPy • Examples for the mathematical optimization chapter
• Matplotlib
13.1.1 Convex versus non-convex optimization 13.1.3 Noisy versus exact cost functions
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. Knowing your problem 434 13.2. A review of the different optimizers 435
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
A well-conditioned
quadratic function.
We can see that very anisotropic (ill-conditioned) functions are harder to optimize.
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
ò Note
line search.
You can use different solvers using the parameter method.
ò Note
13.2. A review of the different optimizers 436 13.2. A review of the different optimizers 437
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
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:
An ill-conditioned very non- >>> def jacobian(x):
quadratic function. ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))
The more a function looks like a quadratic function (elliptic iso-curves), the easier it is to optimize. >>> sp.optimize.minimize(f, [2, 1], method="CG", jac=jacobian)
message: Optimization terminated successfully.
success: True
Conjugate gradient descent
status: 0
The gradient descent algorithms above are toys not to be used on real problems. fun: 2.95786...e-14
x: [ 1.000e+00 1.000e+00]
As can be seen from the above experiments, one of the problems of the simple gradient descent algorithms,
nit: 8
is that it tends to oscillate across a valley, each time following the direction of the gradient, that makes
jac: [ 7.183e-07 -2.990e-07]
it cross the valley. The conjugate gradient solves this problem by adding a friction term: each step
nfev: 16
depends on the two last values of the gradient and sharp turns are reduced.
njev: 16
13.2. A review of the different optimizers 438 13.2. A review of the different optimizers 439
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Note that the function has only been evaluated 27 times, compared to 108 without the gradient. (continued from previous page)
>>> def jacobian(x):
13.2.3 Newton and quasi-newton methods ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→x[0]**2)))
Newton methods: using the Hessian (2nd differential) >>> sp.optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian)
Newton methods use a local quadratic approximation to compute the jump direction. For this purpose, message: Optimization terminated successfully.
they rely on the 2 first derivative of the function: the gradient and the Hessian. success: True
status: 0
fun: 1.5601357400786612e-15
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
An ill-conditioned and pass it to the algorithm:
quadratic function:
Note that, as the quadratic ap- >>> def hessian(x): # Computed with sympy
proximation is exact, the New- ... return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
ton method is blazing fast >>> 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
An ill-conditioned non- nhev: 10
quadratic function:
Here we are optimizing a Gaus-
sian, which is always below its ò Note
quadratic approximation. As a
result, the Newton method over- At very high-dimension, the inversion of the Hessian can be costly and unstable (large scale > 250).
shoots and leads to oscillations.
ò Note
Newton optimizers should not to be confused with Newton’s root finding method, based on the same
principles, scipy.optimize.newton().
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
13.2. A review of the different optimizers 440 13.2. A review of the different optimizers 441
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.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) •
import numpy as np
def f(x): import matplotlib.pyplot as plt
return -np.exp(-(x**2))
x = np.linspace(-1.5, 1.5, 101)
plt.ylim(ymin=-1.3) plt.ylim(ymin=-0.2)
plt.axis("off") plt.axis("off")
plt.tight_layout() plt.tight_layout()
plt.show()
# A non-smooth function
Total running time of the script: (0 minutes 0.015 seconds) plt.figure(2, figsize=(3, 2.5))
plt.clf()
plt.plot(x, np.abs(x), linewidth=2)
plt.text(-1, 0, "$f$", size=20)
13.4.2 Smooth vs non-smooth
plt.ylim(ymin=-0.2)
Draws a figure to explain smooth versus non smooth optimization. plt.axis("off")
plt.tight_layout()
plt.show()
13.3. Full code examples 442 13.4. Examples for the mathematical optimization chapter 443
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.037 seconds) (continued from previous page)
t = np.linspace(0, 3, 1000)
plt.figure(1)
13.4.3 Curve fitting plt.clf()
A curve fitting example plt.plot(x, y, "bx")
plt.plot(t, f(t, *params), "r-")
plt.show()
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
rng = np.random.default_rng(27446968)
13.4. Examples for the mathematical optimization chapter 444 13.4. Examples for the mathematical optimization chapter 445
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.show()
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
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]])
13.4. Examples for the mathematical optimization chapter 446 13.4. Examples for the mathematical optimization chapter 447
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
contours = plt.contour(
np.sqrt((x - 3) ** 2 + (y - 2) ** 2),
extent=[-2.03, 4.2, -1.6, 3.2],
cmap="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")
def f(x):
# Store the list of function calls
• accumulator.append(x)
return np.sqrt((x[0] - 3) ** 2 + (x[1] - 2) ** 2)
Total running time of the script: (0 minutes 0.117 seconds)
13.4. Examples for the mathematical optimization chapter 448 13.4. Examples for the mathematical optimization chapter 449
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.050 seconds)
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)
13.4. Examples for the mathematical optimization chapter 450 13.4. Examples for the mathematical optimization chapter 451
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
# A convex function
plt.plot(x, f(x), linewidth=2)
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),
str(iter + 1),
size=12,
) •
import numpy as np
plt.plot(all_x[:10], all_y[:10], "k+", markersize=12, markeredgewidth=2) import matplotlib.pyplot as plt
import scipy as sp
plt.plot(all_x[-1], all_y[-1], "rx", markersize=12)
plt.axis("off") x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] # type: ignore[misc]
plt.ylim(ymin=-1, ymax=8) x = x.T
y = y.T
plt.figure(figsize=(4, 3))
plt.semilogy(np.abs(all_y - all_y[-1]), linewidth=2) for i in (1, 2):
plt.ylabel("Error on f(x)") # Create 2 figure: only the second one will have the optimization
plt.xlabel("Iteration") # path
plt.tight_layout() plt.figure(i, figsize=(3, 2.5))
plt.clf()
plt.show() plt.axes((0, 0, 1, 1))
Total running time of the script: (0 minutes 0.233 seconds) contours = plt.contour(
np.sqrt((x - 3) ** 2 + (y - 2) ** 2),
extent=[-3, 6, -2.5, 5],
cmap="gnuplot",
13.4.8 Constraint optimization: visualizing the geometry )
A small figure explaining optimization with constraints plt.clabel(contours, inline=1, fmt="%1.1f ", fontsize=14)
plt.plot(
[-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")
(continues on next page)
13.4. Examples for the mathematical optimization chapter 452 13.4. Examples for the mathematical optimization chapter 453
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
t0 = time.time()
13.4.9 Alternating optimization x_l_bfgs = sp.optimize.minimize(f, K[0], method="L-BFGS-B").x
print(
The challenge here is that Hessian of the problem is a very ill-conditioned matrix. This can easily be f" L-BFGS: time { time.time() - t0: .2f} s, x error { np.sqrt(np.sum((x_l_bfgs -
seen, as the Hessian of the first term in simply 2 * K.T @ K. Thus the conditioning of the problem can ˓→ x_ref) ** 2)): .2f} , f error { f(x_l_bfgs) - f_ref: .2f} "
be judged from looking at the conditioning of K. )
import time
13.4. Examples for the mathematical optimization chapter 454 13.4. Examples for the mathematical optimization chapter 455
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.show()
import pickle
import sys
import numpy as np
import matplotlib
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"
nipy_spectral = matplotlib.colormaps["nipy_spectral"]
colors = nipy_spectral(np.linspace(0, 1, n_dims))[:, :3]
13.4. Examples for the mathematical optimization chapter 456 13.4. Examples for the mathematical optimization chapter 457
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
13.4. Examples for the mathematical optimization chapter 458 13.4. Examples for the mathematical optimization chapter 459
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
sp.optimize.minimize(
def gradient_descent_adaptative(x0, f, f_prime, hessian=None): f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-12}
return gradient_descent(x0, f, f_prime, adaptative=True) )
return all_x_i, all_y_i, all_f_i
13.4. Examples for the mathematical optimization chapter 460 13.4. Examples for the mathematical optimization chapter 461
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
13.4. Examples for the mathematical optimization chapter 462 13.4. Examples for the mathematical optimization chapter 463
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
13.4. Examples for the mathematical optimization chapter 464 13.4. Examples for the mathematical optimization chapter 465
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• •
• •
• •
13.4. Examples for the mathematical optimization chapter 466 13.4. Examples for the mathematical optimization chapter 467
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• •
• •
• •
13.4. Examples for the mathematical optimization chapter 468 13.4. Examples for the mathematical optimization chapter 469
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
13.4. Examples for the mathematical optimization chapter 470 13.4. Examples for the mathematical optimization chapter 471
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• •
• •
• •
13.4. Examples for the mathematical optimization chapter 472 13.4. Examples for the mathematical optimization chapter 473
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• •
• •
• •
13.4. Examples for the mathematical optimization chapter 474 13.4. Examples for the mathematical optimization chapter 475
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.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.
/opt/hostedtoolcache/Python/3.12.9/x64/lib/python3.12/site-packages/scipy/optimize/_
˓→linesearch.py:312: LineSearchWarning: The line search algorithm did not converge
step = sp.optimize.line_search(
>>> def f(x): # The rosenbrock function
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
˓→mathematical_optimization/examples/plot_gradient_descent.py:234: RuntimeWarning:␣
>>> def jacobian(x):
˓→More than 20 figures have been opened. Figures created through the pyplot interface␣
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] -␣
˓→(`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume␣
˓→x[0]**2)))
˓→too much memory. (To control this warning, see the rcParam `figure.max_open_
>>> sp.optimize.minimize(f, [2, -1], method="BFGS", jac=jacobian)
˓→warning`). Consider using `matplotlib.pyplot.close()`.
message: Optimization terminated successfully.
plt.figure(index, figsize=(3, 2.5))
success: True
/home/runner/work/scientific-python-lectures/scientific-python-lectures/advanced/
status: 0
˓→mathematical_optimization/examples/plot_gradient_descent.py:179: OptimizeWarning:␣
fun: 2.630637192365927e-16
˓→Unknown solver options: ftol
x: [ 1.000e+00 1.000e+00]
sp.optimize.minimize(
nit: 8
jac: [ 6.709e-08 -3.222e-08]
Total running time of the script: (0 minutes 6.627 seconds)
(continues on next page)
13.4. Examples for the mathematical optimization chapter 476 13.4. Examples for the mathematical optimization chapter 477
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
13.4. Examples for the mathematical optimization chapter 478 13.4. Examples for the mathematical optimization chapter 479
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
A very common source of optimization not converging well is human error in the computation 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])
np.float64(2.384185791015625e-07)
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.5. Practical guide to optimization with SciPy 480 13.5. Practical guide to optimization with SciPy 481
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
ò 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().
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.
13.6 Special case: non-linear least-squares curve_fit():
13.6.1 Minimizing the norm of a vector function >>> def f(t, omega, phi):
Least square problems, minimizing the norm of a vector function, have a specific structure that can be ... return np.cos(omega * t + phi)
used in the Levenberg–Marquardt algorithm implemented in scipy.optimize.leastsq().
>>> x = np.linspace(0, 3, 50)
Lets try to minimize the norm of the following vectorial function: >>> rng = np.random.default_rng(27446968)
>>> 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. ]), ...)
Exercise
This took 67 function evaluations (check it with ‘full_output=True’). What if we compute the norm Do the same with omega = 3. What is the difficulty?
ourselves and use a good generic optimizer (BFGS):
13.6. Special case: non-linear least-squares 482 13.7. Optimization with constraints 483
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
ã 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
• scipy.optimize.fmin_slsqp() Sequential least square programming: equality and inequality con- algorithms available. However, even better options for a given task may be available in other libraries;
straints: please also see IPOPT and PyGMO.
13.7. Optimization with constraints 484 13.8. Full code examples 485
Scientific Python Lectures, Edition 2025.1rc0.dev0
14.1 Introduction
This chapter covers the following techniques:
• Python-C-Api
14
• 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
CHAPTER 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 Each technology is demonstrated by wrapping the cos function from math.h. While this is a mostly a
C/C++) available from Python, a process commonly referred to wrapping. The goal of this chapter is to trivial example, it should serve us well to demonstrate the basics of the wrapping solution. Since each
give you a flavour of what technologies exist and what their respective merits and shortcomings are, so technique also includes some form of NumPy support, this is also demonstrated using an example where
that you can select the appropriate one for your specific needs. In any case, once you do start wrapping, the cosine is computed on some kind of array.
you almost certainly will want to consult the respective documentation for your selected technique.
Last but not least, two small warnings:
• All of these techniques may crash (segmentation fault) the Python interpreter, which is (usually)
Chapters contents
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 14.2 Python-C-Api
• Cython The Python-C-API is the backbone of the standard Python interpreter (a.k.a CPython). Using this API
• Summary 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++.
• Further Reading and References
When using the Python-C-API, one usually writes much boilerplate code, first to parse the arguments
• Exercises 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++
Disadvantages
• Much overhead in the code {"cos_func", cos_func, METH_VARARGS, "evaluate the cosine"},
{NULL, NULL, 0, NULL}
• Must be compiled };
• High maintenance cost
# if PY_MAJOR_VERSION >= 3
• No forward compatibility across Python versions as C-API changes /* module initialization */
• Reference count bugs are easy to create and very hard to track down. /* Python version 3*/
static struct PyModuleDef cModPyDem =
{
ò Note PyModuleDef_HEAD_INIT,
"cos_module", "Some documentation",
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 CosMethods
the 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 return PyModule_Create(&cModPyDem);
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. # 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, setuptools, supports compiling C-extensions via a setup.py file:
double answer;
from setuptools import setup, Extension
/* parse the input, from python float to c double */
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); The setup file is called as follows:
/* 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
(continues on next page) (continues on next page)
˓→temp.linux-x86_64-2.7/cos_module.o ò Note
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/
If you do ever need to use the NumPy C-API refer to the documentation about Arrays and Iterators.
˓→interfacing_with_c/python_c_api/cos_module.so
The following example shows how to pass NumPy arrays as arguments to functions and how to iterate
$ ls over NumPy arrays using the (old) NumPy-C-API. It simply takes an array as argument applies the
build/ cos_module.c cos_module.so setup.py 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>
In [4]: cos_module.cos_func(1.0) arrays[1] = NULL; /* The result will be allocated by the iterator */
Out[4]: 0.5403023058681398
/* Set up and create the iterator */
In [5]: cos_module.cos_func(0.0) iterator_flags = (NPY_ITER_ZEROSIZE_OK |
Out[5]: 1.0 /*
* Enable buffering in case the input is not behaved
In [6]: cos_module.cos_func(3.14159265359) * (native byte order or not aligned),
Out[6]: -1.0 * disabling may speed up some cases when it is known to
* be unnecessary.
*/
Now let’s see how robust this is:
NPY_ITER_BUFFERED |
In [7]: cos_module.cos_func('foo') /* Manually handle innermost iteration for speed: */
--------------------------------------------------------------------------- NPY_ITER_EXTERNAL_LOOP |
TypeError Traceback (most recent call last) NPY_ITER_GROWINNER);
<ipython-input-10-11bee483665d> in <module>()
----> 1 cos_module.cos_func('foo') op_flags[0] = (NPY_ITER_READONLY |
TypeError: a float is required /*
* Required that the arrays are well behaved, since the cos
* call below requires this.
(continues on next page)
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}
} };
To convince ourselves if this does actually works, we run the following test script:
(continued from previous page) As with the previous example, this code is somewhat robust, although the error message is not quite as
assert libm_name is not None, "Cannot find libm (math) on this system :/ That's bad." helpful, since it does not tell us what the type should be.
In [14]: cos_module.cos_func('foo')
libm = ctypes.cdll.LoadLibrary(libm_name)
---------------------------------------------------------------------------
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
$ 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:
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o build/temp.linux-x86_64- NumPy provides support for SWIG with the numpy.i file. This interface file defines various so-called
˓→2.7/cos_module_wrap.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/ typemaps which support conversion between NumPy arrays and C-Arrays. In the following example we
˓→scientific-python-lectures/advanced/interfacing_with_c/swig/_cos_module.so will take a quick look at how such typemaps work in practice.
We have the same cos_doubles function as in the ctypes example:
$ ls
build/ cos_module.c cos_module.h cos_module.i cos_module.py _cos_module.so* cos_ void cos_doubles(double * in_array, double * out_array, int size);
˓→module_wrap.c setup.py
# include <math.h>
We can now load and execute the cos_module as we have done in the previous examples:
(continues on next page)
%module cos_doubles $ ls
%{ cos_doubles.c cos_doubles.h cos_doubles.i numpy.i setup.py test_cos_doubles.py
/* the resulting C file should be built as a python extension */ $ python setup.py build_ext -i
# define SWIG_FILE_WITH_INIT running build_ext
/* Includes the header in the wrapper code */ building '_cos_doubles' extension
# include "cos_doubles.h" 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.
/* include the NumPy typemaps */ cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
%include "numpy.i" cos_doubles.i:24: Warning(490): Fragment 'NumPy_Backward_Compatibility' not found.
/* need this for correct module initialization */ creating build
%init %{ creating build/temp.linux-x86_64-2.7
import_array(); 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/
/* typemaps for the two arrays, the second will be modified in-place */ ˓→x86_64-2.7/cos_doubles.o
%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)} gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-
%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)} ˓→prototypes -fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
void cos_doubles_func(double * in_array, int size_in, double * out_array, int␣ from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
˓→size_out) { ˓→include/numpy/ndarrayobject.h:17,
/* calls the original function, providing only the size of the first */ from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/
cos_doubles(in_array, out_array, size_in); ˓→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
• To use the NumPy typemaps, we need include the numpy.i file. ˓→#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION"
• Since the type maps only support the signature ARRAY, SIZE we need to wrap the cos_doubles ˓→working/scientific-python-lectures/advanced/interfacing_with_c/swig_numpy/_cos_
$ ls
• As opposed to the simple SWIG example, we don’t include the cos_doubles.h header, There
build/ cos_doubles.h cos_doubles.py cos_doubles_wrap.c setup.py
is nothing there that we wish to expose to Python since we expose the functionality through cos_doubles.c cos_doubles.i _cos_doubles.so* numpy.i test_cos_doubles.
cos_doubles_func. ˓→py
(continued from previous page) • Requires an additional library ( but only at build time, at this problem can be overcome by shipping
import matplotlib.pyplot as plt the generated C files)
import cos_doubles
14.5.1 Example
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x) 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. """
cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y) cdef extern from "math.h":
plt.show() 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 setuptools module, but this time we need some additional pieces from
Cython.Build:
˓→temp.linux-x86_64-2.7/cos_module.o
$ ls
Advantages build/ cos_module.c cos_module.pyx cos_module.so* setup.py
˓→x86_64-2.7/cos_doubles.o
˓→scientific-python-lectures/advanced/interfacing_with_c/cython_numpy/cos_doubles.so
Since this is a brand new section, the exercises are considered more as pointers as to what to look at
$ ls next, so pick the ones that you find more interesting. If you have good ideas for exercises, please let us
build/ _cos_doubles.c cos_doubles.c cos_doubles.h _cos_doubles.pyx cos_doubles. know!
˓→so* setup.py test_cos_doubles.py 1. Download the source code for each example and compile and run them on your machine.
And, as before, we convince ourselves that it worked: 2. Make trivial changes to each example and convince yourself that this works. ( E.g. change cos for
sin.)
import numpy as np
3. Most of the examples, especially the ones involving NumPy may still be fragile and respond badly
import matplotlib.pyplot as plt
to input errors. Look for ways to crash the examples, figure what the problem is and devise a
import cos_doubles
potential solution. Here are some ideas:
x = np.arange(0, 2 * np.pi, 0.1) 1. Numerical overflow.
y = np.empty_like(x)
2. Input and output arrays that have different lengths.
cos_doubles.cos_doubles_func(x, y) 3. Multidimensional array.
plt.plot(x, y)
4. Empty array
plt.show()
5. Arrays with non-double types
4. Use the %timeit IPython magic to measure the execution time of the various solutions
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 *.)
This part of the Scientific Python Lectures is dedicated to various scientific packages useful for extended
needs.
CHAPTER 15
Statistics in Python
Requirements
ã 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 program-
ming 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.
512 513
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
columns giving the different attributes of the data, and rows the observations. For instance, the data
Tip contained in examples/brain_size.csv:
Why Python for statistics? "";"Gender";"FSIQ";"VIQ";"PIQ";"Weight";"Height";"MRI_Count"
R is a language dedicated to statistics. Python is a general-purpose language with statistics modules. "1";"Female";133;132;124;"118";"64.5";816932
R has more statistical analysis features than Python, and specialized syntaxes. However, when it "2";"Male";140;150;124;".";"72.5";1001121
comes to building complex analysis pipelines that mix statistics with e.g. image analysis, text mining, "3";"Male";139;123;150;"143";"73.3";1038437
or control of a physical experiment, the richness of Python is an invaluable asset. "4";"Male";133;129;128;"172";"68.8";965353
"5";"Female";137;132;134;"147";"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
Disclaimer: Gender questions (NA = not available) marker, we will not be able to do statistical analysis.
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 514 15.1. Data representation and interaction 515
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Other inputs: pandas can input data from SQL, excel files, or other formats. See the pandas docu-
mentation. 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.
Manipulating data
data is a pandas.DataFrame, that resembles R’s dataframe:
15.1. Data representation and interaction 516 15.1. Data representation and interaction 517
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• What is the average value of MRI counts expressed in log units, for males and females? (continued from previous page)
<Axes: xlabel='FSIQ', ylabel='VIQ'>],
[<Axes: xlabel='PIQ', ylabel='FSIQ'>,
<Axes: xlabel='VIQ', ylabel='FSIQ'>,
ò Note
<Axes: xlabel='FSIQ', ylabel='FSIQ'>]], dtype=object)
groupby_gender.boxplot is used for the plots above (see this example).
Two populations
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:
Exercise
Plot the scatter matrix for males only, and for females only. Do you think that the 2 sub-populations
correspond to gender?
ã 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'>,
(continues on next page)
15.1. Data representation and interaction 518 15.2. Hypothesis testing: comparing two groups 519
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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:
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_ind(data['FSIQ'], data['PIQ'])
TtestResult(statistic=np.float64(0.46563759638...), pvalue=np.float64(0.64277250...),␣
>>> sp.stats.ttest_1samp(data['VIQ'], 0) ˓→df=np.float64(78.0))
TtestResult(statistic=np.float64(30.088099970...), pvalue=np.float64(1.32891964...e-
˓→28), df=np.int64(39))
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
The p-value of 10− 28 indicates that such an extreme value of the statistic is unlikely to be observed confounding, reducing the power of the test. This variability can be removed using a “paired test” or
under the null hypothesis. This may be taken as evidence that the null hypothesis is false and that the “repeated measures test”:
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 >>> sp.stats.ttest_rel(data['FSIQ'], data['PIQ'])
from the population are normally distributed. This condition is exactly satisfied when the population TtestResult(statistic=np.float64(1.784201940...), pvalue=np.float64(0.082172638183...
˓→), df=np.int64(39))
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=np.float64(0.0), pvalue=np.float64(3.4881726...e-08))
15.2. Hypothesis testing: comparing two groups 520 15.2. Hypothesis testing: comparing two groups 521
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
15.3 Linear models, multiple factors, and analysis of variance We can inspect the various statistics derived from the fit:
Terminology:
Statsmodels uses a statistical terminology: the y variable in statsmodels is called ‘endogenous’ while
First, we generate simulated data according to the model: the x variable is called exogenous. This is discussed in more detail here.
>>> import numpy as np To simplify, y (endogenous) is the value you are trying to predict, while x (exogenous) represents the
>>> x = np.linspace(-5, 5, 20) features you are using to make the prediction.
>>> rng = np.random.default_rng(27446968)
>>> # normal distributed noise
>>> y = -5 + 3*x + 4 * rng.normal(size=x.shape) Exercise
>>> # Create a data frame containing all the relevant variables
>>> data = pandas.DataFrame({'x': x, 'y': y}) 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 522 15.3. Linear models, multiple factors, and analysis of variance 523
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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 524 15.3. Linear models, multiple factors, and analysis of variance 525
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.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.
>>> 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
Example: the iris data (examples/iris.csv) Model: OLS Adj. R-squared: 0.468
Method: Least Squares F-statistic: 44.63
Date: ... Prob (F-statistic): 1.58e-20
Tip Time: ... Log-Likelihood: -38.185
No. Observations: 150 AIC: 84.37
Sepal and petal size tend to be related: bigger flowers are bigger! But is there in addition a systematic
Df Residuals: 146 BIC: 96.41
effect of species?
Df Model: 3
Covariance Type: nonrobust
==========================...
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. Linear models, multiple factors, and analysis of variance 526 15.3. Linear models, multiple factors, and analysis of variance 527
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
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. More visualization: seaborn for statistical exploration 528 15.4. More visualization: seaborn for statistical exploration 529
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
A regression capturing the relation between one variable and another, eg wage, and education, can be
plotted using seaborn.lmplot():
Robust 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
Tip OLS by a “Robust Linear Model”, statsmodels.formula.api.rlm().
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 530 15.4. More visualization: seaborn for statistical exploration 531
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
15.5 Testing for interactions • Conditionning (adding factors that can explain all or part of the variation) is an important
modeling aspect that changes the interpretation.
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”.
• 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 532 15.6. Full code for the figures 533
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import pandas
plt.show()
•
•
import pandas
15.6. Full code for the figures 534 15.6. Full code for the figures 535
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.show()
import matplotlib.pyplot as plt Text(0.5, 0.98, 'blue: setosa, green: versicolor, red: virginica')
Plot a scatter matrix # Now formulate a "contrast", to test if the offset for versicolor and
# virginica are identical
# Express the names as categories
categories = pandas.Categorical(data["name"]) print("Testing the difference between effect of versicolor and virginica")
print(model.f_test([0, 1, -1, 0]))
# The parameter 'c' is passed to plt.scatter and will control the color plt.show()
plotting.scatter_matrix(data, c=categories.codes, marker="o")
15.6. Full code for the figures 536 15.6. Full code for the figures 537
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly␣
˓→specified.
15.6. Full code for the figures 538 15.6. Full code for the figures 539
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
import numpy as np
import matplotlib.pyplot as plt
import pandas
x = np.linspace(-5, 5, 21)
# We generate a 2D grid
X, Y = np.meshgrid(x, x)
(continues on next page)
15.6. Full code for the figures 540 15.6. Full code for the figures 541
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
print("\nANOVA results")
print(anova_results)
plt.show()
# Convert the data into a Pandas DataFrame to use the formulas framework Retrieving manually the parameter estimates:
# in statsmodels [-4.43322435 3.08614608 -0.68556194]
# First we need to flatten the data: it's 2D layout is not relevant. ANOVA results
X = X.flatten() df sum_sq mean_sq F PR(>F)
Y = Y.flatten() x 1.0 38501.973182 38501.973182 573.111646 1.365553e-81
Z = Z.flatten() y 1.0 1899.955512 1899.955512 28.281320 1.676135e-07
Residual 438.0 29425.094352 67.180581 NaN NaN
(continues on next page)
15.6. Full code for the figures 542 15.6. Full code for the figures 543
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Total running time of the script: (0 minutes 0.114 seconds) (continued from previous page)
# Plot 2 linear fits for male and female.
seaborn.lmplot(y="wage", x="education", hue="gender", data=data)
15.6.6 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.request
import os
if not os.path.exists("wages.txt"):
# Download the file if it is not present
url = "http://lib.stat.cmu.edu/datasets/CPS_85_Wages"
with urllib.request.urlopen(url) as r, open("wages.txt", "wb") as f:
f.write(r.read())
# Convert genders to strings (this is particularly useful so that the statistical analysis
# statsmodels formulas detects that gender is a categorical variable)
import numpy as np import statsmodels.formula.api as sm
data["gender"] = np.choose(data.gender, ["male", "female"]) # 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
# Log-transform the wages, because they typically are increased with # female. The reason is that a single model enables statistical testing
# multiplicative factors result = sm.ols(formula="wage ~ education + gender", data=data).fit()
data["wage"] = np.log10(data["wage"]) print(result.summary())
15.6. Full code for the figures 544 15.6. Full code for the figures 545
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
15.6. Full code for the figures 546 15.6. Full code for the figures 547
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
data = pandas.read_csv(
"wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python"
)
data.columns = pandas.Index(short_names)
data["WAGE"] = np.log10(data["WAGE"])
import seaborn
15.6. Full code for the figures 548 15.6. Full code for the figures 549
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• •
15.6. Full code for the figures 550 15.6. Full code for the figures 551
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
seaborn.lmplot(y="WAGE", x="EDUCATION", data=data) 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.
plt.show() 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
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
# is not yet distributed
(continues on next page)
15.6. Full code for the figures 552 15.6. Full code for the figures 553
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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'␣
˓→``sep='\s+'`` instead
data = pandas.read_csv(
data_2000 = data_flat[
["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"]
]
# Rename the columns
data_2000.columns = pandas.Index(
["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 554 15.6. Full code for the figures 555
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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 556 15.6. Full code for the figures 557
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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: Thu, 10 Apr 2025
Time: 05:55:39
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
Statistical testing: dependence of fare on distance and number of passengers nb_passengers -35.2686 1.119 -31.526 0.000 -37.461 -33.076
=================================================================================
import statsmodels.formula.api as sm
If the model instance has been used for another fit with different fit parameters,␣
result = sm.ols(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() ˓→then the fit options might not be the correct ones anymore .
print(result.summary())
Statistical testing: regression of fare on distance: 2001/2000 difference
# Using a robust fit
result = sm.rlm(formula="fare ~ 1 + dist + nb_passengers", data=data_flat).fit() result = sm.ols(formula="fare_2001 - fare_2000 ~ 1 + dist", data=data).fit()
print(result.summary()) print(result.summary())
15.6. Full code for the figures 558 15.6. Full code for the figures 559
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import pandas
from statsmodels.formula.api import ols
15.6. Full code for the figures 560 15.7. Solutions to this chapter’s exercises 561
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
# 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, Total running time of the script: (0 minutes 0.232 seconds)
cmap="winter",
)
fig = plt.gcf()
fig.suptitle("blue: male, green: female", size=13)
plt.show()
15.7. Solutions to this chapter’s exercises 562 15.7. Solutions to this chapter’s exercises 563
Scientific Python Lectures, Edition 2025.1rc0.dev0
• Algebraic manipulations
– Expand
– Simplify
16
• Calculus
– Limits
– Differentiation
– Series expansion
CHAPTER – Integration
• Equation solving
• Linear Algebra
– Matrices
– Differential Equations
What is SymPy? SymPy is a Python library for symbolic mathematics. It aims to be an alternative to >>> sym.pi.evalf()
systems such as Mathematica or Maple while keeping the code as simple as possible and easily extensible. 3.14159265358979
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/ >>> (sym.pi + sym.exp(1)).evalf()
5.85987448204884
Chapters contents as you see, evalf evaluates the expression to a floating-point number.
There is also a class representing mathematical infinity, called oo:
• First Steps with SymPy
– Using SymPy as a calculator >>> sym.oo > 99999
True
– Symbols (continues on next page)
16.2.2 Simplify
16.1.2 Symbols
Use simplify if you would like to transform an expression into a simpler form:
In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables
explicitly: >>> sym.simplify((x + x * y) / x)
y + 1
>>> x = sym.Symbol('x')
>>> y = sym.Symbol('y')
Simplification is a somewhat vague term, and more precises alternatives to simplify exists: powsimp
(simplification of exponents), trigsimp (for trigonometric expressions) , logcombine, radsimp, together.
Then you can manipulate them:
>>> x + y + x - y Exercises
2*x
1. Calculate the expanded form of (𝑥 + 𝑦)6 .
>>> (x + y) ** 2
(x + y)**2 2. Simplify the trigonometric expression sin(𝑥)/ cos(𝑥)
Symbols can now be manipulated using some of python operators: +, -, *, ** (arithmetic), &, |, ~, >>,
<< (boolean). 16.3 Calculus
Printing
16.3.1 Limits
Limits are easy to use in SymPy, they follow the syntax limit(function, variable, point), so to
Sympy allows for control of the display of the output. From here we use the following setting for compute the limit of 𝑓 (𝑥) as 𝑥 → 0, you would issue limit(f, x, 0):
printing:
>>> sym.limit(sym.sin(x) / x, x, 0)
>>> sym.init_printing(use_unicode=False, wrap_line=True)
1
>>> sym.series(sym.cos(x), x)
2 4 16.4 Equation solving
x x / 6\
1 - -- + -- + O\x / SymPy is able to solve algebraic equations, in one and several variables using solveset():
2 24
>>> sym.solveset(x ** 4 - 1, x)
>>> sym.series(1/sym.cos(x), x)
{-1, 1, -I, I}
2 4
x 5*x / 6\
As you can see it takes as first argument an expression that is supposed to be equaled to 0. It also has
1 + -- + ---- + O\x /
(limited) support for transcendental equations:
2 24
>>> sym.solveset(sym.exp(x) + 1, x)
{I*(2*n*pi + pi) | n in Integers}
Exercises
Sympy is able to solve a large part of polynomial equations, and is also capable of solving multiple (continued from previous page)
equations with respect to multiple variables giving a tuple as second argument. To do this you use
the solve() command: >>> A**2
>>> solution = sym.solve((x + 5 * y - 2, -3 * x + 6 * y - 15), (x, y)) [x*y + 1 2*x ]
>>> solution[x], solution[y] [ ]
(-3, 1) [ 2*y x*y + 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:
16.5.2 Differential Equations
SymPy is capable of solving (some) Ordinary Differential. To solve differential equations, use dsolve.
>>> f = x ** 4 - 3 * x ** 2 + 1 First, create an undefined function by passing cls=Function to the symbols function:
>>> sym.factor(f)
/ 2 \ / 2 \ >>> f, g = sym.symbols('f g', cls=sym.Function)
\x - x - 1/*\x + x - 1/
f and g are now undefined functions. We can call f(x), and it will represent an unknown function:
>>> sym.factor(f, modulus=5)
2 2 >>> f(x)
(x - 2) *(x + 2) f(x)
SymPy is also able to solve boolean equations, that is, to decide if a certain boolean expression is >>> f(x).diff(x, x) + f(x)
satisfiable or not. For this, we use the function satisfiable: 2
d
>>> sym.satisfiable(x & y) f(x) + ---(f(x))
{x: True, y: True} 2
dx
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.dsolve(f(x).diff(x, x) + f(x), f(x))
f(x) = C1*sin(x) + C2*cos(x)
>>> sym.satisfiable(x & ~x)
False 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:
Exercises
>>> sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x),
1. Solve the system of equations 𝑥 + 𝑦 = 2, 2 · 𝑥 + 𝑦 = 0 ˓→ f(x), hint='separable')
2. Are there boolean values x, y that make (~x | y) & (~y | x) true? / C1 \ / C1 \
[f(x) = - acos|------| + 2*pi, f(x) = acos|------|]
\cos(x)/ \cos(x)/
– Colorspaces
• Image preprocessing / enhancement
– Local filters
17
– Non-local filters
– Mathematical morphology
• Image segmentation
– Binary segmentation: foreground + background
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
17.1.1 scikit-image and the scientific Python ecosystem Restoration algorithms, e.g., deconvolution algorithms, denoising, etc.
scikit-image is packaged in both pip and conda-based Python installations, as well as in most Linux segmentation
distributions. Other Python packages for image processing & visualization that operate on NumPy Partitioning an image into multiple regions.
arrays include: transform
scipy.ndimage Geometric and other transforms, e.g., rotation or the Radon transform.
For N-dimensional arrays. Basic filtering, mathematical morphology, regions properties util
Mahotas Generic utilities.
With a focus on high-speed implementations.
Napari 17.2 Importing
A fast, interactive, multi-dimensional image viewer built in Qt.
We import scikit-image using the convention:
Some powerful C++ image processing libraries also have Python bindings:
>>> import skimage as ski
OpenCV
A highly optimized computer vision library with a focus on real-time applications.
Most functionality lives in subpackages, e.g.:
ITK
The Insight ToolKit, especially useful for registration and working with 3D images. >>> image = ski.data.cat()
To varying degrees, these tend to be less Pythonic and NumPy-friendly.
You can list all submodules with:
Most scikit-image functions take NumPy ndarrays as arguments 17.4.1 Data types
>>> 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 Image ndarrays can be represented either by integers (signed or unsigned) or floats.
To start off, we need example images to work with. The library ships with a few of these: Careful with overflows with integer data types
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
This works with many data formats supported by the ImageIO library. range) of input images.
17.3. Example data 576 17.4. Input/output, data types and colorspaces 577
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> diamond(1)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype=uint8)
1 2 1
0 0 0
-1 -2 -1
Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring
element.:
17.5. Image preprocessing / enhancement 578 17.5. Image preprocessing / enhancement 579
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
camera = ski.data.camera()
val = ski.filters.threshold_otsu(camera)
mask = camera < val
ã See also
Synthetic data: >>> # Generate an initial image with two overlapping circles
>>> x, y = np.indices((80, 80))
>>> n = 20 >>> x1, y1, x2, y2 = 28, 28, 44, 52
>>> l = 256 >>> r1, r2 = 16, 20
>>> im = np.zeros((l, l)) >>> mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2
>>> rng = np.random.default_rng() >>> mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2
>>> points = l * rng.random((2, n ** 2)) >>> image = np.logical_or(mask_circle1, mask_circle2)
>>> im[(points[0]).astype(int), (points[1]).astype(int)] = 1 >>> # Now we want to separate the two objects in image
>>> im = ski.filters.gaussian(im, sigma=l / (4. * n)) >>> # Generate the markers as local maxima of the distance
>>> blobs = im > im.mean() >>> # to the background
>>> import scipy as sp
Label all connected components: >>> distance = sp.ndimage.distance_transform_edt(image)
>>> peak_idx = ski.feature.peak_local_max(
>>> all_labels = ski.measure.label(blobs) ... distance, footprint=np.ones((3, 3)), labels=image
... )
Label only foreground connected components: >>> peak_mask = np.zeros_like(distance, dtype=bool)
>>> peak_mask[tuple(peak_idx.T)] = True
>>> blobs_labels = ski.measure.label(blobs, background=0)
>>> markers = ski.morphology.label(peak_mask)
>>> labels_ws = ski.segmentation.watershed(
... -distance, markers, mask=image
... )
>>> plt.figure()
<Figure size ... with 0 Axes>
>>> plt.imshow(clean_border, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
ã See also
for some properties, functions are available as well in scipy.ndimage.measurements with a different
API (a list is returned).
17.9 Feature extraction for computer vision
Geometric or textural descriptor can be extracted from images in order to
Exercise (continued)
• classify parts of the image (e.g. sky vs. buildings)
• Use the binary image of the coins and background from the previous exercise.
• match parts of different images (e.g. for object detection)
• Compute an image of labels for the different coins.
• and many other applications of Computer Vision
• Compute the size and eccentricity of all coins.
Example: detecting corners using Harris detector
17.7. Measuring regions’ properties 584 17.8. Data visualization and interaction 585
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
)
import numpy as np
import matplotlib.pyplot as plt
17.10. Full code examples 586 17.11. Examples for the scikit-image chapter 587
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
camera = data.camera()
camera_multiply = 3 * camera
import matplotlib.pyplot as plt
from skimage import data plt.figure(figsize=(8, 4))
plt.subplot(121)
camera = data.camera() plt.imshow(camera, cmap="gray", interpolation="nearest")
plt.axis("off")
plt.subplot(122)
plt.figure(figsize=(4, 4)) plt.imshow(camera_multiply, cmap="gray", interpolation="nearest")
plt.imshow(camera, cmap="gray", interpolation="nearest") plt.axis("off")
plt.axis("off")
plt.tight_layout()
plt.tight_layout() plt.show()
plt.show()
Total running time of the script: (0 minutes 0.127 seconds)
Total running time of the script: (0 minutes 0.083 seconds)
17.11. Examples for the scikit-image chapter 588 17.11. Examples for the scikit-image chapter 589
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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()
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()
17.11.5 Computing horizontal gradients with the Sobel filter from skimage import data, segmentation
from skimage import filters
This example illustrates the use of the horizontal Sobel filter, to compute horizontal gradients. 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)
plt.figure(figsize=(8, 3.5))
plt.subplot(121)
plt.imshow(clean_border, cmap="gray")
from skimage import data plt.axis("off")
from skimage import filters plt.subplot(122)
import matplotlib.pyplot as plt plt.imshow(coins_edges)
plt.axis("off")
text = data.text()
hsobel_text = filters.sobel_h(text) (continues on next page)
(continues on next page)
17.11. Examples for the scikit-image chapter 590 17.11. Examples for the scikit-image chapter 591
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.figure(figsize=(9, 4))
tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7, translation=(210,␣
plt.subplot(131)
˓→50))
plt.imshow(camera, cmap="gray", interpolation="nearest")
image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350))
plt.axis("off")
plt.subplot(132)
coords = corner_peaks(corner_harris(image), min_distance=5)
plt.imshow(camera < val, cmap="gray", interpolation="nearest")
coords_subpix = corner_subpix(image, coords, window_size=13)
plt.axis("off")
plt.subplot(133)
plt.gray()
plt.plot(bins_center, hist, lw=2)
plt.imshow(image, interpolation="nearest")
plt.axvline(val, color="k", ls="--")
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], "+r", markersize=15, mew=5)
plt.plot(coords[:, 1], coords[:, 0], ".b", markersize=7)
plt.tight_layout()
plt.axis("off")
plt.show()
plt.show()
Total running time of the script: (0 minutes 0.128 seconds)
Total running time of the script: (0 minutes 1.383 seconds)
17.11. Examples for the scikit-image chapter 592 17.11. Examples for the scikit-image chapter 593
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import filters
from skimage import restoration
from skimage import measure
from skimage import filters coins = data.coins()
import matplotlib.pyplot as plt gaussian_filter_coins = filters.gaussian(coins, sigma=2)
import numpy as np med_filter_coins = filters.median(coins, np.ones((3, 3)))
tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1)
n = 12
l = 256 plt.figure(figsize=(16, 4))
rng = np.random.default_rng(27446968) plt.subplot(141)
im = np.zeros((l, l)) plt.imshow(coins[10:80, 300:370], cmap="gray", interpolation="nearest")
points = l * rng.random((2, n**2)) plt.axis("off")
im[(points[0]).astype(int), (points[1]).astype(int)] = 1 plt.title("Image")
im = filters.gaussian(im, sigma=l / (4.0 * n)) plt.subplot(142)
blobs = im > 0.7 * im.mean() plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap="gray", interpolation="nearest
˓→")
plt.tight_layout()
plt.show()
17.11.11 Watershed and random walker for segmentation
Total running time of the script: (0 minutes 0.076 seconds) 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.
17.11. Examples for the scikit-image chapter 594 17.11. Examples for the scikit-image chapter 595
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.tight_layout()
plt.show()
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
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)
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")
(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 2025.1rc0.dev0
Chapters contents
18
• Introduction: problem settings
• Basic principles of machine learning with scikit-learn
• Supervised Learning: Classification of Handwritten Digits
• Supervised Learning: Regression of Housing Data
CHAPTER
• Measuring prediction performance
• Unsupervised Learning: Dimensionality Reduction and Visualization
• Parameter selection, Validation, and Testing
• Examples for the scikit-learn chapter
Tip
Machine Learning is about building programs with tunable parameters that are adjusted auto-
matically so as to improve their behavior by adapting to previously seen data.
Authors: Gael Varoquaux
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.
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.
By drawing this separating line, we have learned a model which can generalize to new data: if you were A Simple Example: the Iris Dataset
to drop another point onto the plane which is unlabeled, this algorithm could now predict whether it’s
The application problem
a blue or a red point.
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:
18.1. Introduction: problem settings 600 18.1. Introduction: problem settings 601
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
ò Note
Exercise:
Import sklearn Note that scikit-learn is imported as sklearn
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.
The features of each sample flower are stored in the data attribute of the dataset:
>>> print(iris.data.shape)
(150, 4) 18.2 Basic principles of machine learning with scikit-learn
>>> n_samples, n_features = iris.data.shape
>>> print(n_samples) 18.2.1 Introducing the scikit-learn estimator object
150
>>> print(n_features) Every algorithm is exposed in scikit-learn via an ‘’Estimator” object. For instance a linear regression is:
4 sklearn.linear_model.LinearRegression
>>> print(iris.data[0])
>>> from sklearn.linear_model import LinearRegression
[5.1 3.5 1.4 0.2]
Estimator parameters: All the parameters of an estimator can be set when it is instantiated:
The information about the class of each sample is stored in the target attribute of the dataset:
>>> model = LinearRegression(n_jobs=1)
>>> print(iris.target.shape)
>>> print(model)
(150,)
LinearRegression(n_jobs=1)
>>> 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 Fitting on data
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 Let’s create some simple data with numpy:
2 2]
>>> import numpy as np
>>> x = np.array([0, 1, 2])
The names of the classes are stored in the last attribute, namely target_names:
>>> y = np.array([0, 1, 2])
>>> print(iris.target_names)
['setosa' 'versicolor' 'virginica'] >>> X = x[:, np.newaxis] # The input data for sklearn is 2D: (samples == 3 x features␣
˓→== 1)
This data is four-dimensional, but we can visualize two of the dimensions at a time using a scatter plot: >>> 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.1. Introduction: problem settings 602 18.2. Basic principles of machine learning with scikit-learn 603
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• 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:
Regression: The simplest possible regression setting is the linear regression one:
18.2. Basic principles of machine learning with scikit-learn 604 18.2. Basic principles of machine learning with scikit-learn 605
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
In supervised estimators And now, let’s fit a 4th order and a 9th order polynomial to the data.
• 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.
Tip
18.2. Basic principles of machine learning with scikit-learn 606 18.2. Basic principles of machine learning with scikit-learn 607
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
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. Let us visualize the data and remind us what we’re looking at (click on the figure for the full code):
>>> from sklearn.datasets import load_digits # plot the digits: each image is 8x8 pixels
>>> digits = load_digits() 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')
18.3. Supervised Learning: Classification of Handwritten Digits 608 18.3. Supervised Learning: Classification of Handwritten Digits 609
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> # use the model to predict the labels of the test data
>>> predicted = clf.predict(X_test)
>>> expected = y_test
>>> print(predicted)
[6 9 3 7 2 2 5 8 5 2 1 1 7 0 4 8 3 7 8 8 4 3 9 7 5 6 3 5 6 3...]
>>> print(expected)
[6 9 3 7 2 1 5 2 5 2 1 9 4 0 4 2 3 7 8 8 4 3 9 7 5 6 3 5 6 3...]
As above, we plot the digits with the predicted labels to get an idea of how well the classification is
working.
Question
Given these projections of the data, which numbers do you think a classifier might have trouble
distinguishing?
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.
18.3. Supervised Learning: Classification of Handwritten Digits 610 18.3. Supervised Learning: Classification of Handwritten Digits 611
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
One of the most useful metrics is the classification_report, which combines several measures and
prints a table with the results:
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:
We see here that in particular, the numbers 1, 2, 3, and 9 are often being labeled 8.
Question
Why did we split the data into training and validation sets? 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.3.4 Quantitative Measurement of Performance
18.4.1 A quick look at the data
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:
Code and notebook
>>> matches = (predicted == expected)
>>> print(matches.sum()) Python code and Jupyter notebook for this section are found here
385
>>> print(len(matches)) We’ll use the California house prices set, available in scikit-learn. This records measurements of 8
450 attributes of housing markets in California, as well as the median price. The question is: can you predict
>>> matches.sum() / float(len(matches)) the price of a new market given its attributes?:
np.float64(0.8555...)
>>> from sklearn.datasets import fetch_california_housing
We see that more than 80% of the 450 predictions match the input. But there are other more sophisticated >>> data = fetch_california_housing(as_frame=True)
metrics that can be used to judge the performance of a classifier: several are available in the sklearn. >>> print(data.data.shape)
metrics submodule. (continues on next page)
18.3. Supervised Learning: Classification of Handwritten Digits 612 18.4. Supervised Learning: Regression of Housing Data 613
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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:
:Number of Instances: 20640 Let’s have a quick look to see if some features are more relevant than others for our problem:
:Number of Attributes: 8 numeric, predictive attributes and the target >>> for index, feature_name in enumerate(data.feature_names):
... plt.figure()
:Attribute Information: ... plt.scatter(data.data[feature_name], data.target)
- MedInc median income in block group <Figure size...
- 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
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).
.. rubric:: References
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:
18.4. Supervised Learning: Regression of Housing Data 614 18.4. Supervised Learning: Regression of Housing Data 615
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
There are many other types of regressors available in scikit-learn: we’ll try a more powerful one here.
Tip
Use the GradientBoostingRegressor class to fit the housing data.
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 hint You can copy and paste some of the above code, replacing LinearRegression with
of choosing the most informative features. 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 616 18.4. Supervised Learning: Regression of Housing Data 617
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
18.5. Measuring prediction performance 618 18.5. Measuring prediction performance 619
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
We have applied Gaussian Naives, support vectors machines, and K-nearest neighbors classifiers to We can use different splitting strategies, such as random splitting:
the digits dataset. Now that we have these validation tools in place, we can ask quantitatively which
>>> from sklearn.model_selection import ShuffleSplit
of the three estimators works best for this dataset.
>>> cv = ShuffleSplit(n_splits=5)
>>> cross_val_score(clf, X, y, cv=cv)
• With the default hyper-parameters for each estimator, which gives the best f1 score on the valida- array([...])
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)
18.5. Measuring prediction performance 620 18.5. Measuring prediction performance 621
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
Tip Question
There exists many different cross-validation strategies in scikit-learn. They are often useful to take Can we trust our results to be actually useful?
in account non iid datasets.
Automatically Performing Grid Search
18.5.5 Hyperparameter optimization with cross-validation sklearn.grid_search.GridSearchCV is constructed with an estimator, as well as a dictionary of pa-
Consider regularized linear models, such as Ridge Regression, which uses l2 regularization, and Lasso rameter values to be searched. We can find the optimal parameters this way:
Regression, which uses l1 regularization. Choosing their regularization parameter is important. >>> from sklearn.model_selection import GridSearchCV
Let us set these parameters on the Diabetes dataset, a simple regression problem. The diabetes data >>> for Model in [Ridge, Lasso]:
consists of 10 physiological variables (age, sex, weight, blood pressure) measure on 442 patients, and an ... gscv = GridSearchCV(Model(), dict(alpha=alphas), cv=3).fit(X, y)
indication of disease progression after one year: ... print('%s : %s ' % (Model.__name__, gscv.best_params_))
Ridge: {'alpha': np.float64(0.06210169418915616)}
>>> from sklearn.datasets import load_diabetes Lasso: {'alpha': np.float64(0.01268961003167922)}
>>> data = load_diabetes()
>>> X, y = data.data, data.target
>>> print(X.shape) Built-in Hyperparameter Search
(442, 10)
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
With the default hyper-parameters: we compute the cross-validation score: of Ridge and Lasso are RidgeCV and LassoCV, respectively. Parameter search on these estimators can
>>> from sklearn.linear_model import Ridge, Lasso be performed as follows:
Basic Hyperparameter Optimization We see that the results match those returned by GridSearchCV
We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso Nested cross-validation
and Ridge. We choose 20 values of alpha between 0.0001 and 1:
How do we measure the performance of these estimators? We have used data to set the hyperparameters,
>>> alphas = np.logspace(-3, -1, 30) 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 [Lasso, Ridge]:
... scores = [cross_val_score(Model(alpha), X, y, cv=3).mean() for Model in [RidgeCV, LassoCV]:
... for alpha in alphas] scores = cross_val_score(Model(alphas=alphas, cv=3), X, y, cv=3)
... plt.plot(alphas, scores, label=Model.__name__) print(Model.__name__, np.mean(scores))
[<matplotlib.lines.Line2D object at ...
ò 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.5. Measuring prediction performance 622 18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 623
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
>>> X = iris.data
>>> y = iris.target
Tip
PCA computes linear combinations of the original features using a truncated Singular Value Decom-
position of the matrix X, to project the data onto a base of the top singular vectors.
Once fitted, PCA exposes the singular vectors in the components_ attribute:
>>> pca.components_
array([[ 0.3..., -0.08..., 0.85..., 0.3...], Tip
[ 0.6..., 0.7..., -0.1..., -0.07...]])
Note that this projection was determined without any information about the labels (represented by
Other attributes are available as well: 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,
>>> pca.explained_variance_ratio_ iris setosa is much more distinct than the other two species.
array([0.92..., 0.053...])
Let us project the iris dataset along those first two dimensions:: 18.6.2 Visualization with a non-linear embedding: tSNE
>>> X_pca = pca.transform(X) For visualization, more complex embeddings can be useful (for statistical analysis, they are harder to
>>> X_pca.shape control). sklearn.manifold.TSNE is such a powerful manifold learning method. We apply it to the digits
(150, 2) 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
PCA normalizes and whitens the data, which means that the data is now centered on both components >>> X = digits.data[:500]
with unit variance: >>> y = digits.target[:500]
>>> X_pca.mean(axis=0)
array([...e-15, ...e-15]) >>> # Fit and transform with a TSNE
>>> X_pca.std(axis=0, ddof=1) >>> from sklearn.manifold import TSNE
array([1., 1.]) >>> tsne = TSNE(n_components=2, learning_rate='auto', init='random', random_state=0)
>>> X_2d = tsne.fit_transform(X)
Furthermore, the samples components do no longer carry any linear correlation:
>>> # Visualize the data
>>> np.corrcoef(X_pca.T) >>> plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y)
array([[1.00000000e+00, 0.0], <matplotlib.collections.PathCollection object at ...>
[0.0, 1.00000000e+00]])
18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 624 18.6. Unsupervised Learning: Dimensionality Reduction and Visualization 625
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
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
fit_transform y = [0.5, 1]
X_test = np.c_[0, 2].T
As TSNE cannot be applied to new data, we need to use its fit_transform method.
Without noise, as linear regression fits the data perfectly
regr = linear_model.LinearRegression()
regr.fit(X, y)
sklearn.manifold.TSNE separates quite well the different classes of digits even though it had no access plt.plot(X, y, "o")
to the class information. plt.plot(X_test, regr.predict(X_test))
sklearn.manifold has many other non-linear embeddings. Try them out on the digits dataset.
Could you judge their quality without knowing the labels y?
>>> from sklearn.datasets import load_digits
>>> digits = load_digits()
>>> # ...
In real life situation, we have noise (e.g. measurement noise) in our data:
ã See also
rng = np.random.default_rng(27446968)
This section is adapted from Andrew Ng’s excellent Coursera course
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape)
The issues associated with validation and cross-validation are some of the most important aspects of the plt.plot(noisy_X, y, "o")
practice of machine learning. Selecting the optimal model for your data is vital, and is a piece of the regr.fit(noisy_X, y)
problem that is not often appreciated by machine learning practitioners. plt.plot(X_test, regr.predict(X_test))
18.7. Parameter selection, Validation, and Testing 626 18.7. Parameter selection, Validation, and Testing 627
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
On a given data, let us fit a simple polynomial regression model with varying degrees:
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)
Tip
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y) In the above figure, we see fits for three different values of d. For d = 1, the data is under-fit. This
plt.plot(X_test, regr.predict(X_test)) 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
plt.show() 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.
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.
Given a particular dataset and a model (e.g. a polynomial), we’d like to understand whether bias >>> # randomly sample more data
(underfit) or variance limits prediction, and how to tune the hyperparameter (here d, the degree of >>> rng = np.random.default_rng(27446968)
(continues on next page)
18.7. Parameter selection, Validation, and Testing 628 18.7. Parameter selection, Validation, and Testing 629
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
Central to quantify bias and variance of a model is to apply it on test data, sampled from the same on the validation set, it is low. Choosing d around 4 or 5 gets us the best tradeoff.
distribution as the train, but that will capture independent noise:
The astute reader will realize that something is amiss here: in the above plot, d = 4 gives the best
Validation curve A validation curve consists in varying a model parameter that controls its complexity results. But in the previous plot, we found that d = 6 vastly over-fits the data. What’s going on
(here the degree of the polynomial) and measures both error of the model on training data, and on test here? The difference is the number of training points used. In the previous example, there were
data (eg with cross-validation). The model parameter is then adjusted so that the test error is minimized: only eight training points. In this example, we have 100. As a general rule of thumb, the more
We use sklearn.model_selection.validation_curve() to compute train and test error, and plot it: 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
>>> from sklearn.model_selection import validation_curve curves.
>>> # Plot the mean train score and validation score across folds • As the number of training samples are increased, what do you expect to see for the training
>>> plt.plot(degrees, validation_scores.mean(axis=1), label='cross-validation') score? For the validation score?
[<matplotlib.lines.Line2D object at ...>] • Would you expect the training score to be higher or lower than the validation score? Would
>>> plt.plot(degrees, train_scores.mean(axis=1), label='training') you 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 ...>]
18.7. Parameter selection, Validation, and Testing 630 18.7. Parameter selection, Validation, and Testing 631
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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.
Fig. 5: For a degree=1 model In particular, gathering more features for each sample will not help the results.
Note that the validation score generally increases with a growing training set, while the training score 18.7.3 Summary on model selection
generally decreases with a growing training set. As the training size increases, they will converge to a We’ve seen above that an under-performing algorithm can be due to two possible situations: high
single value. bias (under-fitting) and high variance (over-fitting). In order to evaluate our algorithm, we set aside
From the above discussion, we know that d = 1 is a high-bias estimator which under-fits the data. This a portion of our training data for cross-validation. Using the technique of learning curves, we can
is indicated by the fact that both the training and validation scores are low. When confronted with this train on progressively larger subsets of the data, evaluating the training error and cross-validation error
type of learning curve, we can expect that adding more training data will not help: both lines converge to determine whether our algorithm has high variance or high bias. But what do we do with this
to a relatively low score. information?
High Bias
When the learning curves have converged to a low score, we have a high bias model.
If a model shows high bias, the following actions might help:
A high-bias model can be improved by:
• Add more features. In our example of predicting home prices, it may be helpful to make use of
• Using a more sophisticated model (i.e. in this case, increase d) 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
• Gather more features for each sample.
• Use a more sophisticated model. Adding complexity to the model can help improve on bias.
• Decrease regularization in a regularized model.
For a polynomial fit, this can be accomplished by increasing the degree d. Each learning technique
Increasing the number of samples, however, does not improve a high-bias model. has its own methods of adding complexity.
Now let’s look at a high-variance (i.e. over-fit) model: • 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.
Fig. 6: For a degree=15 model
• Increase Regularization. Regularization is designed to prevent over-fitting. In a high-variance
model, increasing regularization can lead to better results.
18.7. Parameter selection, Validation, and Testing 632 18.7. Parameter selection, Validation, and Testing 633
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
These choices become very important in real-world situations. For example, due to limited telescope (continued from previous page)
time, astronomers must seek a balance between observing a large number of objects, and observing a plt.legend()
large number of features for each object. Determining which is more important for a particular learning plt.show()
task can inform the observing strategy that the astronomer employs.
iris = datasets.load_iris()
X = iris.data
y = iris.target Total running time of the script: (0 minutes 0.102 seconds)
Fit a PCA
18.8. Examples for the scikit-learn chapter 634 18.8. Examples for the scikit-learn chapter 635
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.axis("tight")
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. plt.show()
The results are not valid Total running time of the script: (0 minutes 0.048 seconds)
Total running time of the script: (0 minutes 1.459 seconds)
18.8. Examples for the scikit-learn chapter 636 18.8. Examples for the scikit-learn chapter 637
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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]
X_2d = tsne.fit_transform(X)
target_ids = range(len(digits.target_names))
plt.figure(figsize=(6, 5))
# Load the data colors = "r", "g", "b", "c", "m", "y", "k", "w", "orange", "purple"
from sklearn.datasets import load_iris 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)
iris = load_iris() plt.legend()
plt.show()
from matplotlib import ticker
import matplotlib.pyplot as plt
# this formatter will label the colorbar with the correct target names
formatter = ticker.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()
18.8. Examples for the scikit-learn chapter 638 18.8. Examples for the scikit-learn chapter 639
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
plt.figure(figsize=(5, 3))
plt.legend(loc="lower left")
plt.xlabel("alpha")
plt.ylabel("cross validation score")
plt.tight_layout()
plt.show()
18.8.6 Use the RidgeCV and LassoCV to set the regularization parameter
Load the diabetes dataset
Compute the cross-validation score with the default hyper-parameters # Smaller figures
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import Ridge, Lasso plt.rcParams["figure.figsize"] = (3, 2)
for Model in [Ridge, Lasso]: We consider the situation where we have only 2 data point
model = Model()
print(f"{ Model.__name__} : { cross_val_score(model, X, y).mean()} ") X = np.c_[0.5, 1].T
y = [0.5, 1]
X_test = np.c_[0, 2].T
Ridge: 0.410174971340889
Lasso: 0.3375593674654274
Without noise, as linear regression fits the data perfectly
18.8. Examples for the scikit-learn chapter 640 18.8. Examples for the scikit-learn chapter 641
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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
import matplotlib.pyplot as plt
As we can see, our linear model captures and amplifies the noise in the data. It displays a lot of variance. from sklearn.linear_model import SGDClassifier
from sklearn.datasets import make_blobs
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 # we create 50 separable synthetic points
are often spurious. The alpha parameter controls the amount of shrinkage used. X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
regr = linear_model.Ridge(alpha=0.1)
np.random.seed(0) # fit the model
for _ in range(6): clf = SGDClassifier(loss="hinge", alpha=0.01, fit_intercept=True)
noisy_X = X + np.random.normal(loc=0, scale=0.1, size=X.shape) clf.fit(X, Y)
plt.plot(noisy_X, y, "o")
regr.fit(noisy_X, y) # plot the line, the points, and the nearest vectors to the plane
plt.plot(X_test, regr.predict(X_test)) xx = np.linspace(-1, 5, 10)
yy = np.linspace(-1, 5, 10)
(continues on next page)
(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 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
ax.axis("tight") print("------------------")
LinearSVC(loss='hinge'): 0.9294570108037394 )
LinearSVC(loss='squared_hinge'): 0.9344942114287969
------------------- Total running time of the script: (0 minutes 0.261 seconds)
KNeighbors(n_neighbors=1): 0.9913675218842191
KNeighbors(n_neighbors=2): 0.9848442068835102
KNeighbors(n_neighbors=3): 0.9867753449543099
KNeighbors(n_neighbors=4): 0.9803719053818863 18.8.10 Plot fitting a 9th order polynomial
KNeighbors(n_neighbors=5): 0.9804562804949924
Fits data generated from a 9th order polynomial with model of 4th order and 9th order polynomials, to
KNeighbors(n_neighbors=6): 0.9757924194139573
demonstrate that often simpler models are to be preferred
KNeighbors(n_neighbors=7): 0.9780645792142071
KNeighbors(n_neighbors=8): 0.9780645792142071 import numpy as np
KNeighbors(n_neighbors=9): 0.9780645792142071 import matplotlib.pyplot as plt
KNeighbors(n_neighbors=10): 0.9755550897728812 from matplotlib.colors import ListedColormap
18.8. Examples for the scikit-learn chapter 644 18.8. Examples for the scikit-learn chapter 645
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
The data
plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)
Ground truth
plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)
plt.plot(x_test, f(x_test), label="truth")
<matplotlib.collections.PathCollection object at 0x7f2463f8a120> plt.axis("tight")
plt.title("Ground truth (9th order polynomial)")
Fitting 4th and 9th order polynomials
plt.show()
For this we need to engineer features: the n_th powers of x:
plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)
18.8. Examples for the scikit-learn chapter 646 18.8. Examples for the scikit-learn chapter 647
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
data = fetch_california_housing(as_frame=True)
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 648 18.8. Examples for the scikit-learn chapter 649
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
• •
• •
• •
18.8. Examples for the scikit-learn chapter 650 18.8. Examples for the scikit-learn chapter 651
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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()
•
Simple prediction
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)") Print the error rate
plt.tight_layout()
import numpy as np
plt.show()
RMS: np.float64(0.5314909993118918)
18.8. Examples for the scikit-learn chapter 652 18.8. Examples for the scikit-learn chapter 653
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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)
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
knn = neighbors.KNeighborsClassifier(n_neighbors=3)
knn.fit(X, y)
Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])
plt.show()
18.8. Examples for the scikit-learn chapter 654 18.8. Examples for the scikit-learn chapter 655
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
from sklearn.datasets import load_digits Plot a projection on the 2 first principal axis
digits = load_digits() plt.figure()
for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(digits.images[i], cmap="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 656 18.8. Examples for the scikit-learn chapter 657
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
# use the model to predict the labels of the test data Quantify the performance
predicted = clf.predict(X_test)
expected = y_test First print the number of correct matches
18.8. Examples for the scikit-learn chapter 658 18.8. Examples for the scikit-learn chapter 659
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
And now, the ration of correct predictions 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.
matches.sum() / float(len(matches))
from sklearn import datasets
np.float64(0.8777777777777778)
faces = datasets.fetch_olivetti_faces()
Print the classification report faces.data.shape
print(metrics.confusion_matrix(expected, predicted))
plt.show()
[[35 0 0 0 1 0 0 1 0 0]
[ 0 35 0 0 0 0 1 1 4 0]
[ 0 1 41 0 0 0 0 0 7 0]
[ 0 0 2 39 0 1 0 2 2 1]
[ 0 1 0 0 38 0 0 2 1 0]
[ 0 0 0 0 1 40 0 1 0 0]
[ 0 0 1 0 1 0 58 0 0 0]
[ 0 0 0 0 0 1 0 46 0 0]
[ 0 2 0 1 0 1 0 1 34 0]
[ 1 3 2 2 0 2 0 3 4 29]]
18.8. Examples for the scikit-learn chapter 660 18.8. Examples for the scikit-learn chapter 661
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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:
print(X_train.shape, X_test.shape)
One interesting part of PCA is that it computes the “mean” face, which can be interesting to examine:
The principal components measure deviations about this mean along orthogonal axes.
print(pca.components_.shape)
(150, 4096)
18.8. Examples for the scikit-learn chapter 662 18.8. Examples for the scikit-learn chapter 663
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.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.
Finally, we can evaluate how well this classification did. First, we might plot a few of the test-cases with The classifier is correct on an impressive number of images given the simplicity of its learning model!
the labels learned from the training set: 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.
import numpy as np
Again, we can quantify this effectiveness using one of several measures from sklearn.metrics. First we
fig = plt.figure(figsize=(8, 6)) can do the classification report, which shows the precision, recall and other measures of the “goodness”
for i in range(15): of the classification:
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap="bone") from sklearn import metrics
y_pred = clf.predict(X_test_pca[i, np.newaxis])[0]
color = "black" if y_pred == y_test[i] else "red" y_pred = clf.predict(X_test_pca)
ax.set_title(y_pred, fontsize="small", color=color) print(metrics.classification_report(y_test, y_pred))
18.8. Examples for the scikit-learn chapter 664 18.8. Examples for the scikit-learn chapter 665
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
18.8. Examples for the scikit-learn chapter 666 18.8. Examples for the scikit-learn chapter 667
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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,
)
<matplotlib.contour.QuadContourSet object at 0x7f2468789c70>
plt.show()
data with a non-linear separation
18.8. Examples for the scikit-learn chapter 668 18.8. Examples for the scikit-learn chapter 669
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
titles = ["d = 1 (under-fit; high bias)", "d = 2", "d = 6 (over-fit; high variance)"]
degrees = [1, 2, 6]
for i, d in enumerate(degrees):
ax = fig.add_subplot(131 + i, xticks=[], yticks=[])
ax.scatter(x, y, marker="x", c="k", s=50)
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])
import numpy as np
import matplotlib.pyplot as plt
18.8. Examples for the scikit-learn chapter 670 18.8. Examples for the scikit-learn chapter 671
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
# The parameter to vary is the "degrees" on the pipeline step train_sizes, train_scores, validation_scores = learning_curve(
# "polynomialfeatures" model, x[:, np.newaxis], y, train_sizes=np.logspace(-1, 0, 20)
train_scores, validation_scores = validation_curve( )
model,
x[:, np.newaxis], # Plot the mean train error and validation error across folds
y, plt.figure(figsize=(6, 4))
param_name="polynomialfeatures__degree", plt.plot(
param_range=degrees, 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")
# Plot the mean train error and validation error across folds plt.ylim(ymin=-0.1, ymax=1)
plt.figure(figsize=(6, 4))
plt.plot(degrees, validation_scores.mean(axis=1), lw=2, label="cross-validation") plt.legend(loc="best")
plt.plot(degrees, train_scores.mean(axis=1), lw=2, label="training") plt.xlabel("number of train samples")
plt.ylabel("explained variance")
plt.legend(loc="best") plt.title(f"Learning curve (degree={ d} )")
plt.xlabel("degree of fit") plt.tight_layout()
(continues on next page) (continues on next page)
18.8. Examples for the scikit-learn chapter 672 18.8. Examples for the scikit-learn chapter 673
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
plt.show()
•
Total running time of the script: (0 minutes 1.779 seconds)
18.8. Examples for the scikit-learn chapter 674 18.8. Examples for the scikit-learn chapter 675
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
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)
18.8. Examples for the scikit-learn chapter 676 18.8. Examples for the scikit-learn chapter 677
Scientific Python Lectures, Edition 2025.1rc0.dev0 Scientific Python Lectures, Edition 2025.1rc0.dev0
18.8. Examples for the scikit-learn chapter 678 18.8. Examples for the scikit-learn chapter 679
Scientific Python Lectures, Edition 2025.1rc0.dev0
Part IV
19
• Michael Boyle • B. Hohl
• Matthew Brett • Tarek Hoteit
• BSGalvan • Gert-Ludwig Ingold
• Lars Buitinck • Zbigniew Jędrzejewski-Szmek
CHAPTER
• Pierre de Buyl • Thouis (Ray) Jones
• Ozan Çağlayan • jorgeprietoarranz
• Lawrence Chan • josephsalmon
• Adrien Chauve • Greg Kiar
• Robert Cimrman • kikocorreoso
I
integration, 568
M
Matrix, 570
P
Python Enhancement Proposals
PEP 255, 300
PEP 3118, 338
PEP 3129, 309
PEP 318, 302, 309
PEP 342, 300
PEP 343, 310
PEP 380, 301
PEP 380#id13, 301
PEP 8, 304
S
solve, 569