Scip y Lectures
Scip y Lectures
SciPy Python
2 The Python language 12
EDITION 2.1 First steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Basic types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4 Defining functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.5 Reusing code: scripts and modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
IP[y]: 2.6 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.7 Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.8 Exception handling in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
47
3.1 The NumPy array object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.2 Numerical operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Scipy
3.3 More elaborate arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
3.4 Advanced operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Edited by 3.5 Some exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Gaël Varoquaux 3.6 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
an d m a n y ot her s...
5.4 Interpolation: scipy.interpolate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 13.5 Practical guide to optimization with scipy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
5.5 Optimization and fit: scipy.optimize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 13.6 Special case: non-linear least-squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
5.6 Statistics and random numbers: scipy.stats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 13.7 Optimization with constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
5.7 Numerical integration: scipy.integrate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 13.8 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
5.8 Fast Fourier transforms: scipy.fftpack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 13.9 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . . . . . . . 438
5.9 Signal processing: scipy.signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
5.10 Image manipulation: scipy.ndimage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 14 Interfacing with C 439
5.11 Summary exercises on scientific computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208 14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
5.12 Full code examples for the scipy chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 14.2 Python-C-Api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
14.3 Ctypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
6 Getting help and finding documentation 259 14.4 SWIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
14.5 Cython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
14.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
II Advanced topics 262 14.7 Further Reading and References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
14.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
7 Advanced Python Constructs 264
7.1 Iterators, generator expressions and generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
7.2 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269 III Packages and applications 460
7.3 Context managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
15 Statistics in Python 462
8 Advanced NumPy 281 15.1 Data representation and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
8.1 Life of ndarray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 15.2 Hypothesis testing: comparing two groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
8.2 Universal functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 15.3 Linear models, multiple factors, and analysis of variance . . . . . . . . . . . . . . . . . . . . . . . . 471
8.3 Interoperability features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304 15.4 More visualization: seaborn for statistical exploration . . . . . . . . . . . . . . . . . . . . . . . . . . 476
8.4 Array siblings: chararray, maskedarray, matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 15.5 Testing for interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
8.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 15.6 Full code for the figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
8.6 Contributing to NumPy/Scipy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 15.7 Solutions to this chapter’s exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
9 Debugging code 314 16 Sympy : Symbolic Mathematics in Python 505
9.1 Avoiding bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 16.1 First Steps with SymPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
9.2 Debugging workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 16.2 Algebraic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
9.3 Using the Python debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 16.3 Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
9.4 Debugging segmentation faults using gdb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 16.4 Equation solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
16.5 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
10 Optimizing code 325
10.1 Optimization workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 17 Scikit-image: image processing 513
10.2 Profiling Python code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 17.1 Introduction and concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
10.3 Making code go faster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328 17.2 Input/output, data types and colorspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
10.4 Writing faster numerical code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 17.3 Image preprocessing / enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
17.4 Image segmentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
11 Sparse Matrices in SciPy 332
17.5 Measuring regions’ properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
17.6 Data visualization and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
11.2 Storage Schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
17.7 Feature extraction for computer vision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
11.3 Linear System Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
17.8 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
11.4 Other Interesting Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
17.9 Examples for the scikit-image chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
12 Image manipulation and processing using Numpy and Scipy 352
18 Traits: building interactive dialogs 538
12.1 Opening and writing to image files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
18.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
12.2 Displaying images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
18.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
12.3 Basic manipulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
18.3 What are Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
12.4 Image filtering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
12.5 Feature extraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364 19 3D plotting with Mayavi 557
12.6 Measuring objects properties: ndimage.measurements . . . . . . . . . . . . . . . . . . . . . . . . 366 19.1 Mlab: the scripting interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
12.7 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 19.2 Interactive work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
12.8 Examples for the image processing chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 19.3 Slicing and dicing data: sources, modules and filters . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
19.4 Animating the data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
13 Mathematical optimization: finding minima of functions 397
19.5 Making interactive dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
13.1 Knowing your problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
19.6 Putting it together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
13.2 A review of the different optimizers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
13.3 Full code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 20 scikit-learn: machine learning in Python 572
13.4 Examples for the mathematical optimization chapter . . . . . . . . . . . . . . . . . . . . . . . . . . 406
ii iii
Scipy lecture notes, Edition 2017.1
Index 652
iv Contents 1
Scipy lecture notes, Edition 2017.1
This part of the Scipy lecture notes 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
Scipy lecture notes, Edition 2017.1
• 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.
CHAPTER Cons
• Painful usage: no interactivity during development, mandatory compilation steps, ver-
bose syntax, manual memory management. These are difficult languages for non pro-
grammers.
Pros
Python scientific computing ecosystem • Very rich collection of libraries with numerous algorithms, for many different domains.
Fast execution because these libraries are often written in a compiled language.
• Pleasant development environment: comprehensive and help, integrated editor, etc.
• Commercial support is available.
Cons
• Base language is quite poor and can become restrictive for advanced users.
Authors: Fernando Perez, Emmanuelle Gouillart, Gaël Varoquaux, Valentin Haenel • Not free.
Pros
1.1.1 The scientist’s needs
• Fast code, yet interactive and simple.
• Get data (simulation, experiment control), • Easily connects to Python or C.
• Manipulate and process data, Cons
• Visualize results, quickly to understand, but also with high quality figures, for reports or publications. • Ecosystem limited to numerical computing.
• Still young.
1.1.2 Python’s strengths
Other scripting languages: Scilab, Octave, R, IDL, etc.
• Batteries included Rich collection of already existing bricks of classic numerical methods, plotting or
data processing tools. We don’t want to re-program the plotting of a curve, a Fourier transform or a fitting
Pros
algorithm. Don’t reinvent the wheel!
• Open-source, free, or at least cheaper than Matlab.
• Easy to learn Most scientists are not payed as programmers, neither have they been trained so. They
need to be able to draw a curve, smooth a signal, do a Fourier transform in a few minutes. • Some features can be very advanced (statistics in R, etc.)
• Easy communication To keep code alive within a lab or a company it should be as readable as a book Cons
by collaborators, students, or maybe customers. Python syntax is simple, avoiding strange symbols or
• Fewer available algorithms than in Matlab, and the language is not more advanced.
lengthy routine specifications that would divert the reader from mathematical or scientific understand-
ing of the code. • Some software are dedicated to one domain. Ex: Gnuplot to draw curves. These pro-
grams are very powerful, but they are restricted to a single type of usage, such as plotting.
• Efficient code Python numerical modules are computationally efficient. But needless to say that a very
fast code becomes useless if too much time is spent writing it. Python aims for quick development times
and quick execution times.
Python • Numpy: numerical computing with powerful numerical arrays objects, and routines to manipulate
them. http://www.numpy.org/
Pros
See also:
• Very rich scientific computing libraries
chapter on numpy
• Well thought out language, allowing to write very readable and well structured code: we
• Scipy : high-level numerical routines. Optimization, regression, interpolation, etc http://www.scipy.org/
“code what we think”.
See also:
• Many libraries beyond scientific computing (web server, serial port access, etc.)
chapter on scipy
• Free and open-source software, widely spread, with a vibrant community.
• Matplotlib : 2-D visualization, “publication-ready” plots http://matplotlib.org/
• A variety of powerful environments to work in, such as IPython, Spyder, Jupyter note-
books, Pycharm See also:
• Not all the algorithms that can be found in more specialized software or toolboxes.
Unlike Matlab, or R, Python does not come with a pre-bundled set of modules for scientific computing. Below
are the basic building blocks that can be combined to obtain a scientific computing environment:
1.2. The Scientific Python ecosystem 6 1.2. The Scientific Python ecosystem 7
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Domain-specific packages,
Under the notebook
• Mayavi for 3-D visualization
• pandas, statsmodels, seaborn for statistics To execute code, press “shift enter”
• sympy for symbolic computing
Start ipython:
• scikit-image for image processing
• scikit-learn for machine learning In [1]: print('Hello world')
Hello world
and much more packages not documented in the scipy lectures.
See also: Getting help by using the ? operator after an object:
Python comes in many flavors, and there are many ways to install it. However, we recommend to install a Prints the values to a stream, or to sys.stdout by default.
scientific-computing distribution, that comes readily with optimized versions of scientific modules. Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
Under Linux sep: string inserted between values, default a space.
If you have a recent distribution, most of the tools are probably packaged, and it is recommended to use your end: string appended after the last value, default a newline.
package manager.
See also:
Other systems
• IPython user manual: http://ipython.org/ipython-doc/dev/index.html
There are several fully-featured Scientific Python distributions:
• Jupyter Notebook QuickStart: http://jupyter.readthedocs.io/en/latest/content-quickstart.html
• Anaconda
• EPD
1.4.2 Elaboration of the work in an editor
• WinPython
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:
Python 3 or Python 2?
• Spyder: integrates an IPython console, a debugger, a profiler. . .
In 2008, Python 3 was released. It is a major evolution of the language that made a few changes. Some old
• PyCharm: integrates an IPython console, notebooks, a debugger. . . (freely available, but commercial)
scientific code does not yet run under Python 3. However, this is infrequent and Python 3 comes with many
benefits. We advise that you install Python 3. • Atom
Some of these are shipped by the various scientific Python distributions, and you can find them in the menus.
As an exercise, create a file my_file.py in a code editor, and add the following lines:
1.4 The workflow: interactive environments and text editors s = 'Hello world'
print(s)
Interactive work to test and understand algorithms: In this section, we describe a workflow combining inter-
active work and consolidation. Now, you can run it in IPython console or a notebook and explore the resulting variables:
Python is a general-purpose language. As such, there is not one blessed environment to work in, and not only In [1]: %run my_file.py
one way of using it. Although this makes it harder for beginners to find their way, it makes it possible for Python Hello world
to be used for programs, in web servers, or embedded devices.
In [2]: s
Out[2]: 'Hello world'
1.4.1 Interactive work
In [3]: %whos
We recommend an interactive work with the IPython console, or its offspring, the Jupyter notebook. They are Variable Type Data/Info
handy to explore and understand algorithms. ----------------------------
s str Hello world
1.3. Before starting: Installing a working environment 8 1.4. The workflow: interactive environments and text editors 9
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• %cpaste allows you to paste code, especially code from websites which has been prefixed with the stan-
From a script to functions dard Python prompt (e.g. >>>) or with an ipython prompt, (e.g. in [3]):
While it is tempting to work only with scripts, that is a file full of instructions following each other, do plan In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
to progressively evolve the script to a set of functions:
:>>> for i in range(3):
• A script is not reusable, functions are. :... print(i)
:--
• Thinking in terms of functions helps breaking the problem in small blocks. 0
1
2
1.4.3 IPython and Jupyter Tips and Tricks • %timeit allows you to time the execution of short snippets using the timeit module from the standard
library:
The user manuals contain a wealth of information. Here we give a quick introduction to four useful features:
history, tab completion, magic functions, and aliases. In [3]: %timeit x = 10
10000000 loops, best of 3: 39 ns per loop
See also:
Chapter on optimizing code
Command history Like a UNIX shell, the IPython console supports command history. Type up and down to • %debug allows you to enter post-mortem debugging. That is to say, if the code you try to execute, raises
navigate previously typed commands: an exception, using %debug will enter the debugger at the point where the exception was thrown.
In [5]: %debug
> /.../IPython/core/compilerop.py (87)ast_parse()
86 and are passed to the built-in compile function."""
---> 87 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
Tab completion Tab completion, is a convenient way to explore the structure of any object you’re dealing 88
with. Simply type object_name.<TAB> to view the object’s attributes. Besides Python objects and keywords,
ipdb>locals()
tab completion also works on file and directory names.*
{'source': u'x === 10\n', 'symbol': 'exec', 'self':
In [1]: x = 10 <IPython.core.compilerop.CachingCompiler instance at 0x2ad8ef0>,
'filename': '<ipython-input-6-12fd421b5f28>'}
In [2]: x.<TAB>
x.bit_length x.denominator x.imag x.real See also:
x.conjugate x.from_bytes x.numerator x.to_bytes
Chapter on debugging
Magic functions The console and the notebooks support so-called magic functions by prefixing a command Aliases Furthermore IPython ships with various aliases which emulate common UNIX command line tools
with the % character. For example, the run and whos functions from the previous section are magic functions. such as ls to list files, cp to copy files and rm to remove files (a full list of aliases is shown when typing alias).
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.
Getting help
Other useful magic functions are:
• The built-in cheat-sheet is accessible via the %quickref magic function.
• %cd to change the current directory.
• A list of all available magic functions is shown when typing %magic.
In [1]: cd /tmp
/tmp
1.4. The workflow: interactive environments and text editors 10 1.4. The workflow: interactive environments and text editors 11
Scipy lecture notes, Edition 2017.1
• a language for which a large variety of high-quality packages are available for various applications, from
web frameworks to scientific computing.
• a language very easy to interface with other languages, in particular C and C++.
• Some other features of the language are illustrated just below. For example, Python is an object-oriented
2
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
2.1 First steps
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.
• a free software released under an open-source license: Python can be used and distributed free of
charge, even for building commercial software. Tip: Two variables a and b have been defined above. Note that one does not declare the type of a variable
• multi-platform: Python is available for all major operating systems, Windows, Linux/Unix, MacOS X, before assigning its value. In C, conversely, one should write:
most likely your mobile phone OS, etc.
int a = 3;
• a very readable language with clear non-verbose syntax
In addition, the type of a variable may change, in the sense that at one point in time it can be equal to a value Type conversion (casting):
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) >>> float(1)
1.0
are coded natively in Python, and so are some operations on strings such as additions and multiplications,
which amount respectively to concatenation and repetition.
>>> a = 1.5 + 0.5j Tip: If you explicitly want integer division use //:
>>> a.real
1.5 >>> 3.0 // 2
>>> a.imag 1.0
0.5
>>> type(1. + 0j) Note: The behaviour of the division operator has changed in Python 3.
<type 'complex'>
Booleans
>>> 3 > 4
False 2.2.2 Containers
>>> test = (3 > 4)
>>> test
False
Tip: Python provides many efficient types of containers, in which collections of objects can be stored.
>>> type(test)
<type 'bool'>
Lists
Tip: A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations +, -, *,
/, % (modulo) natively implemented
Tip: A list is an ordered collection of objects, that may have different types. For example:
>>> 7 * 3.
21.0 >>> colors = ['red', 'blue', 'green', 'black', 'white']
>>> 2**10 >>> type(colors)
1024 <type 'list'>
>>> 8 % 3
2
Indexing: accessing individual objects contained in the list:
NumPy arrays, operations on elements can be faster because elements are regularly spaced in memory and
>>> colors[2]
'green' more operations are performed through specialized C functions instead of Python loops.
>>> colors[-1]
Tip: Python offers a large panel of functions to modify lists, or query them. Here are a few examples; for more
'white'
details, see https://docs.python.org/tutorial/datastructures.html#more-on-lists
>>> colors[-2]
'black'
Add and remove elements:
Reverse:
Slicing syntax: colors[start:stop:stride]
>>> rcolors = colors[::-1]
Tip: All slicing parameters are optional: >>> rcolors
['white', 'black', 'green', 'blue', 'red']
>>> colors >>> rcolors2 = list(colors)
['red', 'blue', 'green', 'black', 'white'] >>> rcolors2
>>> colors[3:] ['red', 'blue', 'green', 'black', 'white']
['black', 'white'] >>> rcolors2.reverse() # in-place
>>> colors[:3] >>> rcolors2
['red', 'blue', 'green'] ['white', 'black', 'green', 'blue', 'red']
>>> colors[::2]
['red', 'green', 'white'] Concatenate and repeat lists:
Tip: For collections of numerical data that all have the same type, it is often more efficient to use the array The notation rcolors.method() (e.g. rcolors.append(3) and colors.pop()) is our first example of
type provided by the numpy module. A NumPy array is a chunk of memory containing fixed-sized items. With
object-oriented programming (OOP). Being a list, the object rcolors owns the method function that is >>> a[::3] # every three characters, from beginning to end
called using the notation .. No further knowledge of OOP than understanding the notation . is necessary for 'hl r!'
going through this tutorial.
Tip: Accents and special characters can also be handled in Unicode strings (see https://docs.python.org/
Discovering methods: tutorial/introduction.html#unicode-strings).
Reminder: in Ipython: tab-completion (press tab) A string is an immutable object and it is not possible to modify its contents. One may however create new
In [28]: rcolors.<TAB> strings from the original one.
rcolors.append rcolors.index rcolors.remove
In [53]: a = "hello, world!"
rcolors.count rcolors.insert rcolors.reverse
In [54]: a[2] = 'z'
rcolors.extend rcolors.pop rcolors.sort
---------------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Strings
In [55]: a.replace('l', 'z', 1)
Different string syntaxes (simple, double or triple quotes): Out[55]: 'hezlo, world!'
In [56]: a.replace('l', 'z')
s = 'Hello, how are you?' Out[56]: 'hezzo, worzd!'
s = "Hi, what's up"
s = '''Hello, # tripling the quotes allows the
how are you''' # string to span more than one line
Tip: Strings have many useful methods, such as a.replace as seen above. Remember the a. object-oriented
s = """Hi,
notation and use tab completion or help(str) to search for new methods.
what's up?"""
The newline character is \n, and the tab character is \t. >>> 'An integer: %i ; a float: %f ; another string: %s ' % (1, 0.1, 'string')
'An integer: 1; a float: 0.100000; another string: string'
Tip: Strings are collections like lists. Hence they can be indexed and sliced, using the same syntax and rules. >>> i = 102
>>> filename = 'processing_of_dataset_%d .txt' % i
>>> filename
Indexing: 'processing_of_dataset_102.txt'
>>> a = "hello"
>>> a[0]
'h' Dictionaries
>>> a[1]
'e'
>>> a[-1] Tip: A dictionary is basically an efficient table that maps keys to values. It is an unordered container
'o'
>>> t = 12345, 54321, 'hello!' • the key concept here is mutable vs. immutable
>>> t[0]
12345 – mutable objects can be changed in place
>>> t – immutable objects cannot be modified once created
(12345, 54321, 'hello!')
>>> u = (0, 2) See also:
A very good and detailed explanation of the above issues can be found in David M. Beazley’s article Types and
Sets: unordered, unique items:
Objects in Python.
>>> s = set(('a', 'b', 'c', 'a'))
>>> s
set(['a', 'c', 'b']) 2.3 Control Flow
>>> s.difference(('a', 'b'))
set(['c'])
Controls the order in which the code is executed.
>>> if 2**2 == 4:
Tip: Python library reference says: ... print('Obvious!')
Assignment statements are used to (re)bind names to values and to modify attributes or items of ...
Obvious!
mutable objects.
In short, it works as follows (simple assignment): Blocks are delimited by indentation
1. an expression on the right hand side is evaluated, the corresponding object is created/obtained
2. a name on the left hand side is assigned, or bound, to the r.h.s. object Tip: Type the following lines in your Python interpreter, and be careful to respect the indentation depth. The
Ipython shell automatically increases the indentation depth after a colon : sign; to decrease the indentation
depth, go four spaces to the left with the Backspace key. Press the Enter key twice to leave the logical block.
Things to note:
• a single object can have several names bound to it: >>> a = 10
In [1]: a = [1, 2, 3]
>>> if a == 1:
In [2]: b = a
... print(1)
In [3]: a
... elif a == 2:
Out[3]: [1, 2, 3]
... print(2)
In [4]: b
... else:
Out[4]: [1, 2, 3]
... print('A lot')
In [5]: a is b
A lot
Out[5]: True
Indentation is compulsory in scripts as well. As an exercise, re-type the previous lines with the same indenta- • any number equal to zero (0, 0.0, 0+0j)
tion in a script condition.py, and execute the script with run condition.py in Ipython.
• an empty container (list, tuple, set, dictionary, . . . )
• False, None
2.3.2 for/range
Evaluates to True:
Iterating with an index: • everything else
>>> z = 1 + 1j You can iterate over any sequence (string, list, keys in a dictionary, lines in a file, . . . ):
Exercise
Tip: Few languages (in particular, languages for scientific computing) allow to loop over anything but in-
tegers/indices. With Python it is possible to loop exactly over the objects of interest without bothering with Compute the decimals of Pi using the Wallis formula:
indices you often don’t care about. This feature can often be used to make code more readable.
∞
Y 4i 2
π=2
i =1 4i 2 − 1
Warning: Not safe to modify the sequence you are iterating over.
Common task is to iterate over a sequence while keeping track of the item number. 2.4.1 Function definition
• Could use while loop with a counter as above. Or a for loop:
In [56]: def test():
>>> words = ('cool', 'powerful', 'readable') ....: print('in test function')
>>> for i in range(0, len(words)): ....:
... print((i, words[i])) ....:
(0, 'cool')
(1, 'powerful') In [57]: test()
(2, 'readable') in test function
2.4.3 Parameters
In [125]: def double_it(x=bigx): Keyword arguments are a very convenient feature for defining functions with a variable number of arguments,
.....: return x * 2 especially when default values are to be used in most calls to the function.
.....:
In [3]: add_to_dict If the value passed in a function is immutable, the function does not modify the caller’s variable. If the value
Out[3]: <function __main__.add_to_dict> is mutable, the function may modify the caller’s variable in-place:
2.4.7 Docstrings
2.4.5 Global variables
Documentation about what the function does and its parameters. General convention:
Variables declared outside the function can be referenced within the function: In [67]: def funcname(params):
....: """Concise one-line sentence describing the function.
In [114]: x = 5
....:
....: Extended summary which can contain multiple paragraphs.
In [115]: def addx(y):
....: """
.....: return x + y
....: # function body
.....:
....: pass
....:
In [116]: addx(10)
Out[116]: 15
In [68]: funcname?
Type: function
But these “global” variables cannot be modified within the function, unless declared global in the function. Base Class: type 'function'>
This doesn’t work: String Form: <function funcname at 0xeaa0f0>
Namespace: Interactive
In [117]: def setx(y): File: <ipython console>
.....: x = y Definition: funcname(params)
.....: print('x is %d ' % x) Docstring:
.....: Concise one-line sentence describing the function.
.....:
Extended summary which can contain multiple paragraphs.
In [118]: setx(10)
x is 10
Note: Docstring guidelines
In [120]: x
Out[120]: 5 For the sake of standardization, the Docstring Conventions webpage documents the semantics and conven-
tions associated with Python docstrings.
This works: Also, the Numpy and Scipy modules have defined a precise standard for documenting scientific func-
In [121]: def setx(y): tions, that you may want to follow for your own functions, with a Parameters section, an Examples sec-
.....: global x tion, etc. See http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard and http://
.....: x = y projects.scipy.org/numpy/browser/trunk/doc/example.py#L37
.....: print('x is %d ' % x)
.....:
.....:
2.4.8 Functions are objects
In [122]: setx(10)
x is 10 Functions are first-class objects, which means they can be:
• passed as an argument to another function. The extension for Python files is .py. Write or copy-and-paste the following lines in a file called test.py
Methods are functions attached to objects. You’ve seen these in our examples on lists, dictionaries, strings, Note: in Ipython, the syntax to execute a script is %run script.py. For example,
etc. . .
In [2]: message
Write a function that displays the n first terms of the Fibonacci sequence, defined by:
Out[2]: 'Hello how are you?'
U0 = 0
U =1 The script has been executed. Moreover the variables defined in the script (such as message) are now available
1 inside the interpreter’s namespace.
Un+2 = Un+1 +Un
Tip: Other interpreters also offer the possibility to execute scripts (e.g., execfile in the plain Python inter-
Exercise: Quicksort preter, etc.).
Implement the quicksort algorithm, as defined by wikipedia It is also possible In order to execute this script as a standalone program, by executing the script inside a shell
terminal (Linux/Mac console or cmd Windows console). For example, if we are in the same directory as the
test.py file, we can execute this in a console:
function quicksort(array)
var list less, greater $ python test.py
if length(array) < 2 Hello
return array how
select and remove a pivot value pivot from array are
for each x in array you?
if x < pivot + 1 then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))
Tip: Standalone scripts may also take command-line arguments
In file.py:
For now, we have typed all instructions in the interpreter. For longer sets of instructions we need to change
track and write the code in text files (using a text editor), that we will call either scripts or modules. Use your fa- $ python file.py test arguments
['file.py', 'test', 'arguments']
vorite text editor (provided it offers syntax highlighting for Python), or the editor that comes with the Scientific
Python Suite you may be using.
Warning: Don’t implement option parsing yourself. Use modules such as optparse, argparse or
2.5.1 Scripts :mod‘docopt‘.
Tip: Let us first write a script, that is a file with a sequence of instructions that are executed each time the script
is called. Instructions may be e.g. copied-and-pasted from the interpreter (but take care to respect indentation
rules!).
2.5. Reusing code: scripts and modules 30 2.5. Reusing code: scripts and modules 31
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
In [1]: import os Let us create a module demo contained in the file demo.py:
In [7]: dir(demo)
2.5.3 Creating modules Out[7]:
['__builtins__',
'__doc__',
Tip: If we want to write larger and better organized programs (compared to simple scripts), where some '__file__',
objects are defined, (variables, functions, classes) and that we want to reuse several times, we have to create '__name__',
2.5. Reusing code: scripts and modules 32 2.5. Reusing code: scripts and modules 33
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
'__package__',
'c', Importing it:
'd',
'print_a', In [11]: import demo2
'print_b'] b
In [10]: whos
Variable Type Data/Info 2.5.5 Scripts or modules? How to organize your code
--------------------------------
demo module <module 'demo' from 'demo.py'>
print_a function <function print_a at 0xb7421534> Note: Rule of thumb
print_b function <function print_b at 0xb74214c4>
• Sets of instructions that are called several times should be written inside functions for better code
In [11]: print_a() reusability.
a
• 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!).
Warning: Module caching
Modules are cached: if you modify demo.py and re-import it in the old session, you will get the
old one.
How modules are found and imported
Solution:
In [10]: reload(demo) When the import mymodule statement is executed, the module mymodule is searched in a given list of direc-
tories. This list includes a list of installation-dependent default path (e.g., /usr/lib/python) as well as the
In Python3 instead reload is not builtin, so you have to import the importlib module first and then do: list of directories specified by the environment variable PYTHONPATH.
In [10]: importlib.reload(demo) The list of directories searched by Python is given by the sys.path variable
2.5. Reusing code: scripts and modules 34 2.5. Reusing code: scripts and modules 35
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• or modify the sys.path variable itself within a Python script. In [17]: morphology.binary_dilation?
Type: function
Base Class: <type 'function'>
Tip: String Form: <function binary_dilation at 0x9bedd84>
Namespace: Interactive
import sys File: /usr/lib/python2.6/dist-packages/scipy/ndimage/morphology.py
new_path = '/home/emma/user_defined_modules' Definition: morphology.binary_dilation(input, structure=None,
if new_path not in sys.path: iterations=1, mask=None, output=None, border_value=0, origin=0,
sys.path.append(new_path) brute_force=False)
Docstring:
This method is not very robust, however, because it makes the code less portable (user-dependent path) Multi-dimensional binary dilation with the given structure.
and because you have to add the directory to your sys.path each time you want to import from a module
in this directory. An output array can optionally be provided. The origin parameter
controls the placement of the filter. If no structuring element is
provided an element is generated with a squared connectivity equal
See also: to one. The dilation operation is repeated iterations times. If
iterations is less than 1, the dilation is repeated until the
See https://docs.python.org/tutorial/modules.html for more information about modules.
result does not change anymore. If a mask is given, only those
elements with a true value at the corresponding mask element are
modified at each iteration.
2.5.6 Packages
A directory that contains many modules is called a package. A package is a module with submodules (which
can have submodules themselves, etc.). A special file called __init__.py (which may be empty) tells Python 2.5.7 Good practices
that the directory is a Python package, from which modules can be imported.
• Use meaningful object names
$ ls
cluster/ io/ README.txt@ stsci/ • Indentation: no choice!
__config__.py@ LATEST.txt@ setup.py@ __svn_version__.py@
__config__.pyc lib/ setup.pyc __svn_version__.pyc
constants/ linalg/ setupscons.py@ THANKS.txt@ Tip: Indenting is compulsory in Python! Every command block following a colon bears an additional
fftpack/ linsolve/ setupscons.pyc TOCHANGE.txt@ indentation level with respect to the previous line with a colon. One must therefore indent after def
__init__.py@ maxentropy/ signal/ version.py@ f(): or while:. At the end of such logical blocks, one decreases the indentation depth (and re-increases
__init__.pyc misc/ sparse/ version.pyc it if a new block is entered, etc.)
INSTALL.txt@ ndimage/ spatial/ weave/
Strict respect of indentation is the price to pay for getting rid of { or ; characters that delineate logical
integrate/ odr/ special/
interpolate/ optimize/ stats/ blocks in other languages. Improper indentation leads to errors such as
$ cd ndimage
------------------------------------------------------------
$ ls
IndentationError: unexpected indent (test.py, line 2)
doccer.py@ fourier.pyc interpolation.py@ morphology.pyc setup.pyc
doccer.pyc info.py@ interpolation.pyc _nd_image.so
setupscons.py@ All this indentation business can be a bit confusing in the beginning. However, with the clear indenta-
filters.py@ info.pyc measurements.py@ _ni_support.py@ tion, and in the absence of extra characters, the resulting code is very nice to read compared to other
setupscons.pyc languages.
filters.pyc __init__.py@ measurements.pyc _ni_support.pyc tests/
fourier.py@ __init__.pyc morphology.py@ setup.py@
• Indentation depth: Inside your text editor, you may choose to indent with any positive number of spaces
(1, 2, 3, 4, . . . ). However, it is considered good practice to indent with 4 spaces. You may configure your
From Ipython:
editor to map the Tab key to a 4-space indentation.
In [1]: import scipy
• Style guidelines
In [2]: scipy.__file__ Long lines: you should not write very long lines that span over more than (e.g.) 80 characters. Long lines
Out[2]: '/usr/lib/python2.6/dist-packages/scipy/__init__.pyc' can be broken with the \ character
In [3]: import scipy.version >>> long_line = "Here is a very very long line \
... that we break in two parts."
In [4]: scipy.version.version
Out[4]: '0.7.0' Spaces
In [5]: import scipy.ndimage.morphology Write well-spaced code: put whitespaces after commas, around arithmetic operators, etc.:
2.5. Reusing code: scripts and modules 36 2.5. Reusing code: scripts and modules 37
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
File modes
>>> a = 1 # yes
>>> a=1 # too cramped
• Read-only: r
A certain number of rules for writing “beautiful” code (and more importantly using the same conven- • Write-only: w
tions as anybody else!) are given in the Style Guide for Python Code.
– Note: Create a new file or overwrite existing file.
• Append a file: a
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come back
2.6 Input and Output Note: Reference document for this section:
• The Python Standard Library documentation: https://docs.python.org/library/index.html
To be exhaustive, here are some information about input and output in Python. Since we will use the Numpy • Python Essential Reference, David Beazley, Addison-Wesley Professional
methods to read and write files, you may skip this chapter at first reading.
We write or read strings to/from files (other types must be converted to strings). To write in a file:
>>> f = open('workfile', 'w') # opens the workfile file 2.7.1 os module: operating system functionality
>>> type(f)
<type 'file'> “A portable way of using operating system dependent functionality.”
>>> f.write('This is a test \nand another test')
>>> f.close()
Directory and file manipulation
To read from a file
Current directory:
In [1]: f = open('workfile', 'r')
In [17]: os.getcwd()
In [2]: s = f.read() Out[17]: '/Users/cburns/src/scipy2009/scipy_2009_tutorial/source'
In [41]: os.rmdir('foodir')
Running an external command
In [42]: 'foodir' in os.listdir(os.curdir)
Out[42]: False In [8]: os.system('ls')
basic_types.rst demo.py functions.rst python_language.rst standard_library.rst
Delete a file: control_flow.rst exceptions.rst io.rst python-logo.png
demo2.py first_steps.rst oop.rst reusing_code.rst
In [44]: fp = open('junk.txt', 'w')
In [46]: 'junk.txt' in os.listdir(os.curdir) A noteworthy alternative to os.system is the sh module. Which provides much more convenient ways to
Out[46]: True obtain the output, error stream and exit code of the external command.
In [72]: a = os.path.abspath('junk.txt')
In [84]: os.path.exists('junk.txt')
Out[84]: True Environment variables:
In [86]: os.path.isfile('junk.txt')
Out[86]: True In [9]: import os
Exercise
2.7.3 glob: Pattern matching on files
Write a program to search your PYTHONPATH for the module site.py.
The glob module provides convenient file pattern matching.
Find all files ending in .txt:
path_site
In [18]: import glob
It is likely that you have raised Exceptions if you have typed all the previous commands of the tutorial. For
example, you may have raised an exception if you entered a command with a typo.
2.7.4 sys module: system-specific information
Exceptions are raised by different kinds of errors arising when executing Python code. In your own code, you
System-specific information related to the Python interpreter. may also catch errors, or define custom error types. You may want to look at the descriptions of the the built-in
Exceptions when looking for the right exception type.
• Which version of python are you running and where is it installed:
In [117]: sys.platform
Out[117]: 'darwin' 2.8.1 Exceptions
In [7]: l.foobar
---------------------------------------------------------------------------
AttributeError: 'list' object has no attribute 'foobar' 2.8.3 Raising exceptions
As you can see, there are different types of exceptions for different errors. • Capturing and reraising an exception:
....:
In [20]: x
Out[20]: 0.9990234375
3
Use exceptions to notify certain conditions are met (e.g. StopIteration) or not (e.g. custom error raising)
In the previous example, the Student class has __init__, set_age and set_major methods. Its at-
tributes are name, age and major. We can call these methods and attributes with the following notation:
classinstance.method or classinstance.attribute. The __init__ constructor is a special method we Authors: Emmanuelle Gouillart, Didrik Pinte, Gaël Varoquaux, and Pauli Virtanen
call with: MyClass(init parameters if any).
This chapter gives an overview of NumPy, the core tool for performant numerical computing with Python.
Now, suppose we want to create a new class MasterStudent with the same methods and attributes as the pre-
vious one, but with an additional internship attribute. We won’t copy the previous class, but inherit from
it:
3.1.1 What are NumPy and NumPy arrays? • Looking for something:
NumPy provides
In [6]: np.con*?
• extension package to Python for multi-dimensional arrays np.concatenate
np.conj
• closer to hardware (efficiency)
np.conjugate
• designed for scientific computation (convenience) np.convolve
Import conventions
In [1]: L = range(1000)
• 2-D, 3-D, . . . :
In [2]: %timeit [i**2 for i in L] >>> b = np.array([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array
1000 loops, best of 3: 403 us per loop >>> b
array([[0, 1, 2],
In [3]: a = np.arange(1000) [3, 4, 5]])
>>> b.ndim
In [4]: %timeit a**2 2
100000 loops, best of 3: 12.7 us per loop >>> b.shape
(2, 3)
>>> len(b) # returns the size of the first dimension
NumPy Reference documentation 2
3.1. The NumPy array object 48 3.1. The NumPy array object 49
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• Evenly spaced:
3.1. The NumPy array object 50 3.1. The NumPy array object 51
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Bool
[<matplotlib.lines.Line2D object at ...>]
>>> e = np.array([True, False, False, True]) >>> plt.plot(x, y, 'o') # dot plot
>>> e.dtype [<matplotlib.lines.Line2D object at ...>]
dtype('bool')
Strings
Much more
• int32
• int64
• uint32
• 2D arrays (such as images):
• uint64
>>> x = np.linspace(0, 3, 20)
>>> y = np.linspace(0, 9, 20)
3.1.4 Basic visualization >>> plt.plot(x, y) # line plot
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(x, y, 'o') # dot plot
Now that we have our first data arrays, we are going to visualize them.
[<matplotlib.lines.Line2D object at ...>]
Start by launching IPython:
$ ipython
Or the notebook:
$ ipython notebook
>>> %matplotlib
The inline is important for the notebook, so that plots are displayed in the notebook and not in a new window.
See also:
Matplotlib is a 2D plotting package. We can import its functions as below:
More in the: matplotlib chapter
>>> import matplotlib.pyplot as plt # the tidy way
And then use (note that you have to use show explicitly if you have not enabled interactive plots with Exercise: Simple visualizations
%matplotlib):
• Plot some simple arrays: a cosine as a function of time and a 2D matrix.
>>> plt.plot(x, y) # line plot
• Try using the gray colormap on the 2D matrix.
>>> plt.show() # <-- shows the plot (not needed with interactive plots)
The items of an array can be accessed and assigned to the same way as other Python sequences (e.g. lists):
• 1D plotting:
>>> a = np.arange(10)
>>> x = np.linspace(0, 3, 20)
>>> a
>>> y = np.linspace(0, 9, 20)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> plt.plot(x, y) # line plot
3.1. The NumPy array object 52 3.1. The NumPy array object 53
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Warning: Indices begin at 0, like other Python sequences (and C/C++). In contrast, in Fortran or Matlab,
indices begin at 1.
>>> a[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> a = np.diag(np.arange(3))
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 2]])
>>> a[1, 1]
1
>>> a[2, 1] = 10 # third line, second column
>>> a You can also combine assignment and slicing:
array([[ 0, 0, 0],
[ 0, 1, 0], >>> a = np.arange(10)
[ 0, 10, 2]]) >>> a[5:] = 10
>>> a[1] >>> a
array([0, 1, 0]) array([ 0, 1, 2, 3, 4, 10, 10, 10, 10, 10])
>>> b = np.arange(5)
>>> a[5:] = b[::-1]
Note: >>> a
array([0, 1, 2, 3, 4, 4, 3, 2, 1, 0])
• In 2D, the first dimension corresponds to rows, the second to columns.
• for multidimensional a, a[0] is interpreted by taking all elements in the unspecified dimensions.
Exercise: Indexing and slicing
Slicing: Arrays, like other Python sequences can also be sliced: • Try the different flavours of slicing, using start, end and step: starting from a linspace, try to obtain
odd numbers counting backwards, and even numbers counting forwards.
>>> a = np.arange(10)
>>> a • Reproduce the slices in the diagram above. You may use the following expression to create the array:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[2:9:3] # [start:end:step] >>> np.arange(6) + np.arange(0, 51, 10)[:, np.newaxis]
array([2, 5, 8]) array([[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
Note that the last index is not included! :
[30, 31, 32, 33, 34, 35],
>>> a[:4] [40, 41, 42, 43, 44, 45],
array([0, 1, 2, 3]) [50, 51, 52, 53, 54, 55]])
All three slice components are not required: by default, start is 0, end is the last and step is 1:
Skim through the documentation for np.tile, and use this function to construct the array:
[[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1],
[4, 3, 4, 3, 4, 3],
[2, 1, 2, 1, 2, 1]]
>>> np.may_share_memory(a, c)
False 3.1.7 Fancy indexing
This behavior can be surprising at first sight. . . but it allows to save both memory and time.
Tip: NumPy arrays can be indexed with slices, but also with boolean or integer arrays (masks). This method
Worked example: Prime number sieve is called fancy indexing. It creates copies not views.
>>> np.random.seed(3)
>>> a = np.random.randint(0, 21, 15)
>>> a
array([10, 3, 8, 0, 19, 10, 11, 9, 10, 6, 0, 20, 12, 7, 14])
3.1. The NumPy array object 56 3.1. The NumPy array object 57
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> (a % 3 == 0)
array([False, True, False, True, False, False, False, True, False,
True, True, False, True, False, False], dtype=bool)
>>> 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, 0, 9, 6, 0, 12])
Indexing with a mask can be very useful to assign a new value to a sub-array:
>>> a[a % 3 == 0] = -1
>>> a
array([10, -1, 8, -1, 19, 10, 11, -1, 10, -1, -1, 20, -1, 7, 14])
New values can be assigned with this kind of indexing: 3.2 Numerical operations on arrays
>>> a[[9, 7]] = -100
>>> a
array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100]) Section contents
• Elementwise operations
Tip: When a new array is created by indexing with an array of integers, the new array has the same shape than • Basic reductions
the array of integers:
• Broadcasting
>>> a = np.arange(10)
• Array shape manipulation
>>> idx = np.array([[3, 4], [9, 7]])
>>> idx.shape • Sorting data
(2, 2)
>>> a[idx] • Summary
array([[3, 4],
[9, 7]])
Basic operations
The image below illustrates various fancy indexing applications
With scalars:
>>> b = np.ones(4) + 1
>>> a - b
array([-1., 0., 1., 2.])
>>> a = np.array([1, 2, 3, 4]) As a results, the following code is wrong and will not make a matrix symmetric:
>>> b = np.array([4, 2, 2, 4]) >>> a += a.T
>>> a == b
array([False, True, False, True], dtype=bool) It will work for small arrays (because of buffering) but fail for large one, in unpredictable ways.
>>> a > b
array([False, False, True, False], dtype=bool)
The sub-module numpy.linalg implements basic linear algebra, such as solving linear systems, singular
>>> x[0, 1, :].sum()
value decomposition, etc. However, it is not guaranteed to be compiled using efficient routines, and thus 1.14764...
we recommend the use of scipy.linalg, as detailed in section Linear algebra operations: scipy.linalg
• Look at the help for np.allclose. When might this be useful? — works the same way (and take axis=)
• Look at the help for np.triu and np.tril. Extrema:
Exercise: Reductions
Tip: Let us consider a simple 1D random walk process: at each time step a walker jumps right or left with
equal probability.
• Given there is a sum, what other function might you expect to see?
• What is the difference between sum and cumsum?
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 com-
puting tricks: we are going to create a 2D array with the “stories” (each walker has a story) in one direction,
Worked Example: data statistics and the time in the other:
Data in populations.txt describes the populations of hares and lynxes (and carrots) in northern Canada
during 20 years.
You can view the data in an editor, or alternatively in IPython (both shell and notebook):
In [1]: !cat data/populations.txt
>>> t = np.arange(t_max)
>>> steps = 2 * np.random.randint(0, 1 + 1, (n_stories, t_max)) - 1 # +1 because the high␣
,→value is exclusive
>>> np.unique(steps) # Verification: all steps are 1 or -1
array([-1, 1])
The sample standard deviations: We get the mean in the axis of the stories:
Which species has the highest population each year?: Plot the results:
>>> np.argmax(populations, axis=1)
array([2, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1, 2, 2, 2, 2, 2]) >>> plt.figure(figsize=(4, 3))
<matplotlib.figure.Figure object at ...>
>>> plt.plot(t, np.sqrt(mean_sq_distance), 'g.', t, np.sqrt(t), 'y-')
[<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
>>> plt.xlabel(r"$t$")
Worked Example: diffusion using a random walk algorithm
<matplotlib.text.Text object at ...>
>>> plt.ylabel(r"$\sqrt{\langle (\delta x)^2 \rangle}$")
<matplotlib.text.Text object at ...>
>>> plt.tight_layout() # provide sufficient space for labels
Nevertheless, It’s also possible to do operations on arrays of different >>> a = np.arange(0, 40, 10)
sizes if NumPy can transform these arrays so that they all have >>> a.shape
(4,)
the same size: this conversion is called broadcasting.
>>> a = a[:, np.newaxis] # adds a new axis -> 2D array
The image below gives an example of broadcasting: >>> a.shape
(4, 1)
>>> a
array([[ 0],
[10],
[20],
[30]])
>>> a + b
array([[ 0, 1, 2],
[10, 11, 12],
[20, 21, 22],
[30, 31, 32]])
Tip: Broadcasting seems a bit magical, but it is actually quite natural to use it when we want to solve a problem
whose output data is an array with more dimensions than input data.
Let’s construct an array of distances (in miles) between cities of Route 66: Chicago, Springfield, Saint-Louis,
Tulsa, Oklahoma City, Amarillo, Santa Fe, Albuquerque, Flagstaff and Los Angeles.
>>> mileposts = np.array([0, 198, 303, 736, 871, 1175, 1475, 1544,
... 1913, 2448])
>>> distance_array = np.abs(mileposts - mileposts[:, np.newaxis])
>>> distance_array
array([[ 0, 198, 303, 736, 871, 1175, 1475, 1544, 1913, 2448],
[ 198, 0, 105, 538, 673, 977, 1277, 1346, 1715, 2250],
[ 303, 105, 0, 433, 568, 872, 1172, 1241, 1610, 2145],
[ 736, 538, 433, 0, 135, 439, 739, 808, 1177, 1712],
[ 871, 673, 568, 135, 0, 304, 604, 673, 1042, 1577],
Let’s verify:
[1175, 977, 872, 439, 304, 0, 300, 369, 738, 1273],
[1475, 1277, 1172, 739, 604, 300, 0, 69, 438, 973],
[1544, 1346, 1241, 808, 673, 369, 69, 0, 369, 904],
3.2. Numerical operations on arrays 66 3.2. Numerical operations
[1913, 1715, 1610, on arrays
1177, 1042, 738, 438, 369, 0, 535], 67
[2448, 2250, 2145, 1712, 1577, 1273, 973, 904, 535, 0]])
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
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:
Reshaping
>>> a.shape
(2, 3)
>>> b = a.ravel()
Remark : the numpy.ogrid() function allows to di- >>> b = b.reshape((2, 3))
rectly create vectors x and y of the previous example, with two “significant dimensions”: >>> b
array([[1, 2, 3],
>>> x, y = np.ogrid[0:5, 0:5] [4, 5, 6]])
>>> x, y
(array([[0], Or,
[1],
[2], >>> a.reshape((2, -1)) # unspecified (-1) value is inferred
[3], array([[1, 2, 3],
[4]]), array([[0, 1, 2, 3, 4]])) [4, 5, 6]])
Resizing
Warning: ndarray.reshape may return a view (cf help(np.reshape))), or copy
Size of an array can be changed with ndarray.resize:
>>> a = np.arange(4)
Tip: >>> a.resize((8,))
>>> a
>>> b[0, 0] = 99
array([0, 1, 2, 3, 0, 0, 0, 0])
>>> a
array([[99, 2, 3],
[ 4, 5, 6]]) However, it must not be referred to somewhere else:
>>> b = a
Beware: reshape may also return a copy!: >>> a.resize((4,))
Traceback (most recent call last):
>>> a = np.zeros((3, 2))
File "<stdin>", line 1, in <module>
>>> b = a.T.reshape(3*2)
ValueError: cannot resize an array that has been referenced or is
>>> b[0] = 9
referencing another array in this way. Use the resize function
>>> a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]]) Exercise: Shape manipulations
To understand this you need to learn more about the memory layout of a numpy array. • Look at the docstring for reshape, especially the notes section which has some more information
about copies and views.
• Use flatten as an alternative to ravel. What is the difference? (Hint: check which one returns a view
and which a copy)
Adding a dimension
• Experiment with transpose for dimension shuffling.
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):
Dimension shuffling
In-place sort:
>>> a = np.arange(4*3*2).reshape(4, 3, 2) >>> a.sort(axis=1)
>>> a.shape >>> a
(4, 3, 2) array([[3, 4, 5],
>>> a[0, 2, 1] [1, 1, 2]])
5
>>> b = a.transpose(1, 2, 0)
Sorting with fancy indexing:
>>> b.shape
(3, 2, 4) >>> a = np.array([4, 3, 1, 2])
>>> b[2, 1, 0] >>> j = np.argsort(a)
5 >>> j
array([2, 3, 1, 0])
Also creates a view: >>> a[j]
array([1, 2, 3, 4])
>>> b[2, 1, 0] = -1
>>> a[0, 2, 1]
Finding minima and maxima:
-1
• 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])
>>> a.dtype
• Use all or array_equal to check the results. dtype('int64')
• Look at np.random.shuffle for a way to create sortable input quicker. >>> a[0] = 1.9 # <-- float is truncated to integer
>>> a
• Combine ravel, sort and reshape. array([1, 2, 3])
• Look at the axis keyword for sort and rewrite the previous exercise.
Forced casts:
• Know the shape of the array with array.shape, then use slicing to obtain different views of the array: >>> a = np.array([1.2, 1.5, 1.6, 2.5, 3.5, 4.5])
array[::2], etc. Adjust the shape of the array using reshape or flatten it with ravel. >>> b = np.around(a)
>>> b # still floating-point
• Obtain a subset of the elements of an array and/or modify their values with masks array([ 1., 2., 2., 2., 4., 4.])
>>> c = np.around(a).astype(int)
>>> a[a < 0] = 0
>>> c
array([1, 2, 2, 2, 4, 4])
• Know miscellaneous operations on arrays, such as finding the mean or max (array.max(), array.
mean()). No need to retain everything, but have the reflex to search in the documentation (online docs,
help(), lookfor())!!
Different data type sizes
• For advanced use: master the indexing with arrays of integers, as well as broadcasting. Know more
NumPy functions to handle various array operations. Integers (signed):
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come back
and finish this chapter, as well as to do some more exercices. >>> np.array([1], dtype=int).dtype
dtype('int64')
>>> np.iinfo(np.int32).max, 2**31 - 1
(2147483647, 2147483647)
uint8 8 bits
Section contents uint16 16 bits
uint32 32 bits
• More data types
uint64 64 bits
• Structured data types
• maskedarray: dealing with (propagation of) missing data
Python 2 has a specific type for ‘long’ integers, that cannot overflow, represented with an ‘L’ at the end. In
Python 3, all integers are long, and thus cannot overflow. >>> samples = np.zeros((6,), dtype=[('sensor_code', 'S4'),
... ('position', float), ('value', float)])
>>> np.iinfo(np.int64).max, 2**63 - 1 >>> samples.ndim
(9223372036854775807, 9223372036854775807L) 1
>>> samples.shape
(6,)
Floating-point numbers: >>> samples.dtype.names
('sensor_code', 'position', 'value')
float16 16 bits
float32 32 bits >>> samples[:] = [('ALFA', 1, 0.37), ('BETA', 1, 0.11), ('TAU', 1, 0.13),
... ('ALFA', 1.5, 0.37), ('ALFA', 3, 0.11), ('TAU', 1.2, 0.13)]
float64 64 bits (same as float)
>>> samples
float96 96 bits, platform-dependent (same as np.longdouble)
array([('ALFA', 1.0, 0.37), ('BETA', 1.0, 0.11), ('TAU', 1.0, 0.13),
float128 128 bits, platform-dependent (same as np.longdouble) ('ALFA', 1.5, 0.37), ('ALFA', 3.0, 0.11), ('TAU', 1.2, 0.13)],
dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')])
>>> np.finfo(np.float32).eps
1.1920929e-07 Field access works by indexing with field names:
>>> np.finfo(np.float64).eps
2.2204460492503131e-16 >>> samples['sensor_code']
array(['ALFA', 'BETA', 'TAU', 'ALFA', 'ALFA', 'TAU'],
>>> np.float32(1e-8) + np.float32(1) == 1 dtype='|S4')
True >>> samples['value']
>>> np.float64(1e-8) + np.float64(1) == 1 array([ 0.37, 0.11, 0.13, 0.37, 0.11, 0.13])
False >>> samples[0]
('ALFA', 1.0, 0.37)
Complex floating-point numbers:
>>> samples[0]['sensor_code'] = 'TAU'
>>> samples[0]
complex64 two 32-bit floats ('TAU', 1.0, 0.37)
complex128 two 64-bit floats
complex192 two 96-bit floats, platform-dependent Multiple fields at once:
complex256 two 128-bit floats, platform-dependent
>>> samples[['position', 'value']]
array([(1.0, 0.37), (1.0, 0.11), (1.0, 0.13), (1.5, 0.37), (3.0, 0.11),
Smaller data types (1.2, 0.13)],
dtype=[('position', '<f8'), ('value', '<f8')])
If you don’t know you need special data types, then you probably don’t.
Fancy indexing works, as usual:
Comparison on using float32 instead of float64:
>>> samples[samples['sensor_code'] == 'ALFA']
• Half the size in memory and on disk
array([('ALFA', 1.5, 0.37), ('ALFA', 3.0, 0.11)],
• Half the memory bandwidth required (may be a bit faster in some operations) dtype=[('sensor_code', 'S4'), ('position', '<f8'), ('value', '<f8')])
In [2]: b = np.zeros((1e6,), dtype=np.float32) Note: There are a bunch of other syntaxes for constructing structured arrays, see here and here.
• But: bigger rounding errors — sometimes in surprising places (i.e., don’t use them unless you really >>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
need them) >>> x
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:
See http://docs.scipy.org/doc/numpy/reference/
Good practices
routines.polynomials.poly1d.html for more.
• Explicit variable names (no need of a comment to explain what is in the variable)
• Style: spaces after commas, around =, etc. More polynomials (with more bases)
A certain number of rules for writing “beautiful” code (and, more importantly, using the same conven- NumPy also has a more sophisticated polynomial interface, which supports e.g. the Chebyshev basis.
tions as everybody else!) are given in the Style Guide for Python Code and the Docstring Conventions
page (to manage help strings). 3x 2 + 2x − 1:
• Except some rare cases, variable names and comments in English. >>> p = np.polynomial.Polynomial([-1, 2, 3]) # coefs in different order!
>>> p(0)
-1.0
>>> p.roots()
Section contents Example using polynomials in Chebyshev basis, for polynomials in range [-1, 1]:
For example, 3x 2 + 2x − 1:
Images
Using Matplotlib:
Text files
Example: populations.txt:
# year hare lynx carrot
1900 30e3 4e3 48300
1901 47.2e3 6.1e3 48200
This saved only one channel (of RGB):
1902 70.2e3 9.8e3 41500
1903 77.4e3 35.2e3 38200 >>> plt.imshow(plt.imread('red_elephant.png'))
<matplotlib.image.AxesImage object at ...>
Note: If you have a complicated text file, what you can try are:
• np.genfromtxt
• Using Python’s I/O functions and e.g. regexps for parsing (Python is quite well suited for this) Other libraries:
[[1, 6, 11],
[2, 7, 12],
[3, 8, 13],
[4, 9, 14],
[5, 10, 15]]
and generate a new array containing its 2nd and 4th rows.
2. Divide each column of the array:
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.
NumPy’s own format • Use abs and argsort to find the column j closest for each row.
NumPy has its own binary format, not portable but with efficient I/O: • Use fancy indexing to extract the numbers. (Hint: a[i,j] – the array i must contain the row num-
bers corresponding to stuff in j.)
>>> data = np.ones((3, 3))
>>> np.save('pop.npy', data)
>>> data3 = np.load('pop.npy') 3.5.2 Picture manipulation: Framing a Face
Let’s do some manipulations on numpy arrays by starting with an image of a racoon. scipy provides a 2D
Well-known (& more obscure) file formats array of this image with the scipy.misc.face function:
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. • Let’s use the imshow function of pylab to display the image.
6. Compare (plot) the change in hare population (see help(np.gradient)) and the number of lynxes.
>>> sy, sx = face.shape
>>> y, x = np.ogrid[0:sy, 0:sx] # x and y indices of pixels Check correlation (see help(np.corrcoef)).
>>> y.shape, x.shape . . . all without for-loops.
((768, 1), (1, 1024))
>>> centerx, centery = (660, 300) # center of the image Solution: Python source file
>>> mask = ((y - centery)**2 + (x - centerx)**2) > 230**2 # circle
then we assign the value 0 to the pixels of the image corresponding to the mask. The syntax is 3.5.4 Crude integral approximations
extremely simple and intuitive:
Write a function f(a, b, c) that returns a b − c. Form a 24x12x6 array containing its values in parameter
>>> face[mask] = 0 ranges [0,1] x [0,1] x [0,1].
>>> plt.imshow(face)
<matplotlib.image.AxesImage object at 0x...> Approximate the 3-d integral
Z 1Z 1Z 1
• Follow-up: copy all instructions of this exercise in a script called face_locket.py then execute this (a b − c)d a d b d c
script in IPython with %run face_locket.py. 0 0 0
Change the circle to an ellipsoid. over this volume with the mean. The exact result is: ln 2 − 12 ≈ 0.1931 . . . — what is your relative error?
(Hints: use elementwise operations and broadcasting. You can make np.ogrid give a number of points in
3.5.3 Data statistics given range with np.ogrid[0:1:20j].)
Reminder Python functions:
The data in populations.txt describes the populations of hares and lynxes (and carrots) in northern Canada
during 20 years: def f(a, b, c):
return some_result
>>> data = np.loadtxt('data/populations.txt')
>>> year, hares, lynxes, carrots = data.T # trick: columns to variables Solution: Python source file
N_max = 50
Computes and print, based on the data in some_threshold = 50
populations.txt. . .
c = x + 1j*y
1. The mean and std of the populations of each species for the years in the period.
z = 0
2. Which year each species had the largest population. for j in range(N_max):
3. Which species has the largest population for each year. (Hint: argsort & fancy indexing of np. z = z**2 + c
array(['H', 'L', 'C']))
Point (x, y) belongs to the Mandelbrot set if |z| < some_threshold.
4. Which years any of the populations is above 50000. (Hint: comparisons and np.any)
Do this computation by:
5. The top 2 years for each species when they had the lowest populations. (Hint: argsort, fancy indexing)
1. Construct a grid of c = x + 1j*y values in range [-2, 1] x [-1.5, 1.5]
• Constructs a random matrix, and normalizes each row so that it is a transition matrix. image = np.random.rand(30, 30)
plt.imshow(image, cmap=plt.cm.hot)
• Starts from a random (normalized) probability distribution p and takes 50 steps => p_50
plt.colorbar()
• Computes the stationary distribution: the eigenvector of P.T with eigenvalue 1 (numerically: closest to plt.show()
1) => p_stationary
Total running time of the script: ( 0 minutes 0.125 seconds)
Remember to normalize the eigenvector — I didn’t. . .
Download Python source code: plot_basic2dplot.py
• Checks if p_50 and p_stationary are equal to tolerance 1e-5
Download Jupyter notebook: plot_basic2dplot.ipynb
Toolbox: np.random.rand, .dot(), np.linalg.eig, reductions, abs(), argmin, comparisons, all, np.
linalg.norm, etc. Generated by Sphinx-Gallery
Total running time of the script: ( 0 minutes 0.034 seconds) Total running time of the script: ( 0 minutes 0.082 seconds)
Download Python source code: plot_basic1dplot.py Download Python source code: plot_distances.py
Download Jupyter notebook: plot_basic1dplot.ipynb Download Jupyter notebook: plot_distances.ipynb
Generated by Sphinx-Gallery Generated by Sphinx-Gallery
Plot distances in a grid Plot noisy data and their polynomial fit
np.random.seed(12) np.random.seed(0)
original figure
plt.figure()
img = plt.imread('../data/elephant.png')
plt.imshow(img)
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('../data/populations.txt')
year, hares, lynxes, carrots = data.T
plt.figure()
Total running time of the script: ( 0 minutes 0.037 seconds)
img_red = img[:, :, 0]
Download Python source code: plot_populations.py plt.imshow(img_red, cmap=plt.cm.gray)
import numpy as np
import matplotlib.pyplot as plt
Generated by Sphinx-Gallery
Plot distance as a function of time for a random walk together with the theoretical result
import numpy as np
import matplotlib.pyplot as plt
CHAPTER 4
Matplotlib: plotting
Thanks
Many thanks to Bill Wing and Christoph Deil for review and corrections.
Chapter contents
• Introduction
• Simple plot
• Figures, Subplots, Axes and Ticks
• Other Types of Plots: examples and exercises
• Beyond this tutorial
• Quick references
• Full code examples
4.1 Introduction
Tip: Matplotlib is probably the most used Python package for 2D-graphics. It provides both a quick way to
visualize data from Python and publication-quality figures in many formats. We are going to explore matplotlib
For interactive matplotlib sessions, turn on the matplotlib mode You can get source for each step by clicking on the corresponding figure.
%matplotlib inline
4.1.2 pyplot
Tip: pyplot provides a procedural interface to the matplotlib object-oriented plotting library. It is modeled
closely after Matlab™. Therefore, the majority of plotting commands in pyplot have Matlab™ analogs with
similar arguments. Important commands are explained with interactive examples.
Hint: Documentation
Tip: In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default
settings, we’ll enrich the figure step by step to make it nicer.
Tip: Matplotlib comes with a set of default settings that allow customizing all kinds of properties. You can
First step is to get the data for the sine and cosine functions: control the defaults of almost every property in matplotlib: figure size and dpi, line width, color and style,
axes, axis and grid properties, text and font properties and so on.
import numpy as np
import numpy as np
X = np.linspace(-np.pi, np.pi, 256, endpoint=True) import matplotlib.pyplot as plt
C, S = np.cos(X), np.sin(X)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
X is now a numpy array with 256 values ranging from -π to +π (included). C is the cosine (256 values) and S is C, S = np.cos(X), np.sin(X)
the sine (256 values).
plt.plot(X, C)
To run the example, you can type them in an IPython interactive session: plt.plot(X, S)
Hint: Documentation
• Customizing matplotlib
Hint: Documentation
In the script below, we’ve instantiated (and commented) all the figure settings that influence the appearance • Controlling line properties
of the plot.
• Line API
Tip: The settings have been explicitly set to their default values, but now you can interactively play with the
values to explore their affect (see Line properties and Line styles below).
Tip: First step, we want to have the cosine in blue and the sine in red and a slighty thicker line for both of
them. We’ll also slightly alter the figure size to make it more horizontal.
import numpy as np
import matplotlib.pyplot as plt
...
# Create a figure of size 8x6 inches, 80 dots per inch plt.figure(figsize=(10, 6), dpi=80)
plt.figure(figsize=(8, 6), dpi=80) plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
# Create a new subplot from a grid of 1x1 ...
plt.subplot(1, 1, 1)
# Set x limits
plt.xlim(-4.0, 4.0)
# Set x ticks
plt.xticks(np.linspace(-4, 4, 9, endpoint=True))
# Set y limits
plt.ylim(-1.0, 1.0) Hint: Documentation
# Set y ticks • xlim() command
plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
• ylim() command
# Save figure using 72 dots per inch
# plt.savefig("exercise_2.png", dpi=72)
Tip: Current limits of the figure are a bit too tight and we want to make some space in order to clearly see all Hint: Documentation
data points.
• Working with text
• xticks() command
...
plt.xlim(X.min() * 1.1, X.max() * 1.1) • yticks() command
plt.ylim(C.min() * 1.1, C.max() * 1.1)
• set_xticklabels()
...
• set_yticklabels()
...
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1],
[r'$-1$', r'$0$', r'$+1$'])
...
Tip: Current ticks are not ideal because they do not show the interesting values (+/-π,+/-π/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
• Axis container
Tip: Spines are the lines connecting the axis tick marks and noting the boundaries of the data area. They can
be placed at arbitrary positions and until now, they were on the border of the axis. We’ll change that since we
want to have them in the middle. Since there are four of them (top/bottom/left/right), we’ll discard the top
and right by setting their color to none and we’ll move the bottom and left ones to coordinate 0 in data space
coordinates.
...
ax = plt.gca() # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
• Annotating axis
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') • annotate() command
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
... 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.
4.2.8 Adding a legend
...
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
...
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.legend(loc='upper left')
...
Tip: The tick labels are now hardly visible because of the blue and red lines. We can make them bigger and we
can also adjust their properties such that they’ll be rendered on a semi-transparent white background. This
will allow us to see both the data and the labels.
...
for label in ax.get_xticklabels() + ax.get_yticklabels():
Hint: Documentation label.set_fontsize(16)
A “figure” in matplotlib means the whole window in the user interface. Within this figure there can be “sub-
plots”. 4.3.3 Axes
Tip: So far we have used implicit figure and axes creation. This is handy for fast plots. We can have more Axes are very similar to subplots but allow placement of plots at any location in the fig-
control over the display using figure, subplot, and axes explicitly. While subplot positions the plots in a regular ure. So if we want to put a smaller plot inside a bigger one we do so with axes.
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:
4.3.4 Ticks
Argument Default Description
num 1 number of figure Well formatted ticks are an important part of publishing-ready figures. Matplotlib provides a totally config-
figsize figure.figsize figure size in inches (width, height) urable system for ticks. There are tick locators to specify where ticks should appear and tick formatters to
dpi figure.dpi resolution in dots per inch give ticks the appearance you want. Major and minor ticks can be located and formatted independently from
facecolor figure.facecolor color of the drawing background each other. Per default minor ticks are not shown, i.e. there is only an empty list for them because it is as
edgecolor figure.edgecolor color of edge around the drawing background NullLocator (see below).
frameon True draw figure frame or not
Tick Locators
Tip: The defaults can be specified in the resource file and will be used most of the time. Only the number of
Tick locators control the positions of the ticks. They are set as follows:
the figure is frequently changed.
As with other objects, you can set figure properties also setp or with the set_something methods. ax = plt.gca()
ax.xaxis.set_major_locator(eval(locator))
When you work with the GUI you can close a figure by clicking on the x in the upper right corner. But you can
close a figure programmatically by calling close. Depending on the argument it closes (1) the current figure
(no argument), (2) a specific figure (figure number or figure instance as argument), or (3) all figures ("all" as
argument).
4.3.2 Subplots
Tip: With subplot you can arrange plots in a regular grid. You need to specify the number of rows and columns
and the number of the plot. Note that the gridspec command is a more powerful alternative.
There are several locators for different kind of requirements:
All of these locators derive from the base class matplotlib.ticker.Locator. You can make your own lo-
4.3. Figures, Subplots, Axes and Ticks 106 4.3. Figures, Subplots, Axes and Ticks 107
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
cator deriving from it. Handling dates as ticks can be especially tricky. Therefore, matplotlib provides special 4.4.2 Scatter Plots
locators in matplotlib.dates.
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
4.4.1 Regular Plots
plt.scatter(X,Y)
n = 256 Starting from the code below, try to reproduce the graphic by
X = np.linspace(-np.pi, np.pi, n, endpoint=True) adding labels for red bars.
Y = np.sin(2 * X)
Hint: You need to take care of text alignment.
plt.plot(X, Y + 1, color='blue', alpha=1.00)
plt.plot(X, Y - 1, color='blue', alpha=1.00)
n = 12
Click on the figure for solution. X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
4.4. Other Types of Plots: examples and exercises 108 4.4. Other Types of Plots: examples and exercises 109
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
n = 10
4.4.4 Contour Plots x = np.linspace(-3, 3, 4 * n)
y = np.linspace(-3, 3, 3 * n)
X, Y = np.meshgrid(x, y)
plt.imshow(f(X, Y))
4.4. Other Types of Plots: examples and exercises 110 4.4. Other Types of Plots: examples and exercises 111
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
4.4.8 Grids
plt.axes([0, 0, 1, 1])
Starting from the code below, try to reproduce the graphic
taking care of line styles. N = 20
theta = np.arange(0., 2 * np.pi, 2 * np.pi / N)
axes = plt.gca() radii = 10 * np.random.rand(N)
axes.set_xlim(0, 4) width = np.pi / 4 * np.random.rand(N)
axes.set_ylim(0, 3) bars = plt.bar(theta, radii, width=width, bottom=0.0)
axes.set_xticklabels([])
axes.set_yticklabels([]) for r, bar in zip(radii, bars):
bar.set_facecolor(cm.jet(r / 10.))
Click on figure for solution. bar.set_alpha(0.5)
4.4. Other Types of Plots: examples and exercises 112 4.4. Other Types of Plots: examples and exercises 113
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• User guide
Quick read • FAQ
• Installation
If you want to do a first quick pass through the Scipy lectures to learn the ecosystem, you can directly skip • Usage
to the next chapter: Scipy : high-level scientific computing. • How-To
• Troubleshooting
The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come back • Environment Variables
and finish this chapter later. • Screenshots
4.4. Other Types of Plots: examples and exercises 114 4.5. Beyond this tutorial 115
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
The code is well documented and you can quickly access a specific command from within a python session:
Property Description Appearance
>>> import matplotlib.pyplot as plt
alpha (or a) alpha transparency on 0-1
>>> help(plt.plot)
Help on function plot in module matplotlib.pyplot: scale
plot(x, y) # plot x and y using default line style and color solid_capstyle Cap style for solid lines
plot(x, y, 'bo') # plot x and y using blue circle markers solid_joinstyle Join style for solid lines
plot(y) # plot y using x as index array 0..N-1
plot(y, 'r+') # ditto, but with red plusses dash_capstyle Cap style for dashes
dash_joinstyle Join style for dashes
If *x* and/or *y* is 2-dimensional, then the corresponding columns
will be plotted. marker see Markers
... markeredgewidth line width around the marker
(mew) symbol
markeredgecolor edge color if a marker is used
4.5.4 Galleries (mec)
markerfacecolor face color if a marker is used
The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each example
(mfc)
comes with its source.
markersize (ms) size of the marker in points
4.6.4 Colormaps
All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.
If you want to know more about colormaps, checks Documenting the matplotlib colormaps.
import numpy as np
import matplotlib.pyplot as plt
n = 20
Z = np.ones(n)
Z[-1] *= 2
plt.show()
4.7. Full code examples 118 4.7. Full code examples 119
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np fig = plt.figure(figsize=(5, 4), dpi=72)
import matplotlib.pyplot as plt axes = fig.add_axes([0.01, 0.01, .98, 0.98])
X = np.linspace(0, 2, 200, endpoint=True)
n = 1024 Y = np.sin(2*np.pi*X)
X = np.random.normal(0, 1, n) plt.plot(X, Y, lw=2)
Y = np.random.normal(0, 1, n) plt.ylim(-1.1, 1.1)
T = np.arctan2(Y, X) plt.grid()
plt.axes([0.025, 0.025, 0.95, 0.95]) plt.show()
plt.scatter(X, Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5, 1.5) Total running time of the script: ( 0 minutes 0.081 seconds)
plt.xticks(()) Download Python source code: plot_good.py
plt.ylim(-1.5, 1.5)
plt.yticks(()) Download Jupyter notebook: plot_good.ipynb
Generated by Sphinx-Gallery
plt.show()
4.7. Full code examples 120 4.7. Full code examples 121
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
fig = plt.figure()
fig.subplots_adjust(bottom=0.025, left=0.025, top = 0.975, right=0.975)
import matplotlib.pyplot as plt
plt.subplot(2, 1, 1)
plt.xticks(()), plt.yticks(()) plt.axes([.1, .1, .8, .8])
plt.xticks(())
plt.subplot(2, 3, 4) plt.yticks(())
plt.xticks(()) plt.text(.6, .6, 'axes([0.1, 0.1, .8, .8])', ha='center', va='center',
plt.yticks(()) size=20, alpha=.5)
Total running time of the script: ( 0 minutes 0.126 seconds) Download Python source code: plot_axes.py
Generated by Sphinx-Gallery
A simple plotting example
4.7. Full code examples 122 4.7. Full code examples 123
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
4.7. Full code examples 124 4.7. Full code examples 125
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.figure(figsize=(6, 4))
plt.subplot(1, 2, 1)
plt.xticks(()) import numpy as np
plt.yticks(()) import matplotlib.pyplot as plt
plt.text(0.5, 0.5, 'subplot(1,2,1)', ha='center', va='center', from mpl_toolkits.mplot3d import Axes3D
size=24, alpha=.5)
fig = plt.figure()
plt.subplot(1, 2, 2) ax = Axes3D(fig)
plt.xticks(()) X = np.arange(-4, 4, 0.25)
plt.yticks(()) Y = np.arange(-4, 4, 0.25)
plt.text(0.5, 0.5, 'subplot(1,2,2)', ha='center', va='center', X, Y = np.meshgrid(X, Y)
size=24, alpha=.5) R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
plt.tight_layout()
plt.show() ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2, 2)
Total running time of the script: ( 0 minutes 0.068 seconds)
Download Python source code: plot_subplot-vertical.py plt.show()
Download Jupyter notebook: plot_subplot-vertical.ipynb Total running time of the script: ( 0 minutes 0.065 seconds)
Generated by Sphinx-Gallery Download Python source code: plot_plot3d.py
Download Jupyter notebook: plot_plot3d.ipynb
3D plotting
Generated by Sphinx-Gallery
A simple example of 3D plotting.
Imshow elaborate
4.7. Full code examples 126 4.7. Full code examples 127
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Total running time of the script: ( 0 minutes 0.075 seconds) Total running time of the script: ( 0 minutes 0.034 seconds)
Download Python source code: plot_imshow.py Download Python source code: plot_quiver.py
Download Jupyter notebook: plot_imshow.ipynb Download Jupyter notebook: plot_quiver.ipynb
Generated by Sphinx-Gallery Generated by Sphinx-Gallery
A simple example showing how to plot a vector field (quiver) with matplotlib. A simple example showing how to plot in polar coordinnates with matplotlib.
4.7. Full code examples 128 4.7. Full code examples 129
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Download Python source code: plot_polar.py Total running time of the script: ( 0 minutes 0.095 seconds)
Download Jupyter notebook: plot_polar.ipynb Download Python source code: plot_contour.py
Generated by Sphinx-Gallery Download Jupyter notebook: plot_contour.ipynb
Generated by Sphinx-Gallery
Displaying the contours of a function
4.7. Full code examples 130 4.7. Full code examples 131
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import matplotlib import numpy as np
matplotlib.use('Agg') import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
n = 256
matplotlib.rc('grid', color='black', linestyle='-', linewidth=1) X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2 * X)
fig = plt.figure(figsize=(5,4),dpi=72)
axes = fig.add_axes([0.01, 0.01, .98, 0.98], axisbg='.75') plt.axes([0.025, 0.025, 0.95, 0.95])
X = np.linspace(0, 2, 40, endpoint=True)
Y = np.sin(2 * np.pi * X) plt.plot(X, Y + 1, color='blue', alpha=1.00)
plt.plot(X, Y, lw=.05, c='b', antialiased=False) plt.fill_between(X, 1, Y + 1, color='blue', alpha=.25)
Download Jupyter notebook: plot_ugly.ipynb Total running time of the script: ( 0 minutes 0.038 seconds)
Generated by Sphinx-Gallery Download Python source code: plot_plot.py
Download Jupyter notebook: plot_plot.ipynb
Plot and filled plots
Generated by Sphinx-Gallery
Simple example of plots and filling between them with matplotlib.
4.7. Full code examples 132 4.7. Full code examples 133
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Subplot grid
4.7. Full code examples 134 4.7. Full code examples 135
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.xticks(())
plt.tight_layout() plt.yticks(())
plt.show() plt.text(0.1, 0.1, 'axes([0.3, 0.3, .5, .5])', ha='left', va='center',
size=16, alpha=.5)
Total running time of the script: ( 0 minutes 0.136 seconds)
plt.axes([.4, .4, .5, .5])
Download Python source code: plot_subplot-grid.py plt.xticks(())
plt.yticks(())
Download Jupyter notebook: plot_subplot-grid.ipynb
plt.text(0.1, 0.1, 'axes([0.4, 0.4, .5, .5])', ha='left', va='center',
Generated by Sphinx-Gallery size=16, alpha=.5)
plt.show()
Axes
Total running time of the script: ( 0 minutes 0.166 seconds)
This example shows various axes command to position matplotlib axes.
Download Python source code: plot_axes-2.py
Download Jupyter notebook: plot_axes-2.ipynb
Generated by Sphinx-Gallery
Grid
4.7. Full code examples 136 4.7. Full code examples 137
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Download Python source code: plot_grid.py ax.text2D(-0.05, .975, " Plot 2D or 3D data",
horizontalalignment='left',
Download Jupyter notebook: plot_grid.ipynb
verticalalignment='top',
Generated by Sphinx-Gallery family='Lint McCree Intl BB',
size='medium',
transform=plt.gca().transAxes)
3D plotting
plt.show()
Demo 3D plotting with matplotlib and style the figure.
Total running time of the script: ( 0 minutes 0.052 seconds)
Download Python source code: plot_plot3d-2.py
Download Jupyter notebook: plot_plot3d-2.ipynb
Generated by Sphinx-Gallery
GridSpec
ax = plt.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contourf(X, Y, Z)
4.7. Full code examples 138 4.7. Full code examples 139
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.figure(figsize=(6, 4))
G = gridspec.GridSpec(3, 3)
for i in range(24):
index = np.random.randint(0, len(eqs))
eq = eqs[index]
size = np.random.uniform(12, 32)
x,y = np.random.uniform(0, 1, 2)
alpha = np.random.uniform(0.25, .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()
4.7. Full code examples 140 4.7. Full code examples 141
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Excercise 1
import numpy as np
import matplotlib.pyplot as plt
Generated by Sphinx-Gallery
4.7. Full code examples 142 4.7. Full code examples 143
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Exercise 5
Exercise 6
Exercise 5 with matplotlib.
Exercise 6 with matplotlib.
4.7. Full code examples 144 4.7. Full code examples 145
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import matplotlib.pyplot as plt
plt.ylim(C.min() * 1.1, C.max() * 1.1) # Plot cosine using blue color with a continuous line of width 1 (pixels)
plt.yticks([-1, 0, +1], plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")
[r'$-1$', r'$0$', r'$+1$'])
# Plot sine using green color with a continuous line of width 1 (pixels)
plt.show() plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")
Total running time of the script: ( 0 minutes 0.040 seconds) # Set x limits
plt.xlim(-4., 4.)
Download Python source code: plot_exercise_6.py
Download Jupyter notebook: plot_exercise_6.ipynb # Set x ticks
plt.xticks(np.linspace(-4, 4, 9, endpoint=True))
Generated by Sphinx-Gallery
# Set y limits
plt.ylim(-1.0, 1.0)
Exercise 2
# Set y ticks
Exercise 2 with matplotlib. plt.yticks(np.linspace(-1, 1, 5, endpoint=True))
4.7. Full code examples 146 4.7. Full code examples 147
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Exercise 8
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8,5), dpi=80)
plt.subplot(111)
4.7. Full code examples 148 4.7. Full code examples 149
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.legend(loc='upper left')
plt.show()
Exercise
import numpy as np
import matplotlib.pyplot as plt
4.7. Full code examples 150 4.7. Full code examples 151
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
4.7. Full code examples 152 4.7. Full code examples 153
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Alpha: transparency
Aliased versus anti-aliased
This example demonstrates using alpha for transparency.
The example shows aliased versus anti-aliased text.
4.7. Full code examples 154 4.7. Full code examples 155
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Demo the marker size control in matplotlib. Demo the marker edge color of matplotlib’s markers.
Download Python source code: plot_ms.py Total running time of the script: ( 0 minutes 0.041 seconds)
Download Jupyter notebook: plot_ms.ipynb Download Python source code: plot_mec.py
Generated by Sphinx-Gallery Download Jupyter notebook: plot_mec.ipynb
Generated by Sphinx-Gallery
Marker edge width
Demo the marker edge widths of matplotlib’s markers. Marker face color
4.7. Full code examples 156 4.7. Full code examples 157
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
size = 256, 16
Colormaps dpi = 72.0
figsize= size[0] / float(dpi), size[1] / float(dpi)
An example plotting the matplotlib colormaps. fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)
plt.xlim(0, 14)
plt.xticks(())
plt.yticks(())
plt.show()
plt.rc('text', usetex=False)
a = np.outer(np.arange(0, 1, 0.01), np.ones(10))
Solid joint style
plt.figure(figsize=(10, 5)) An example showing the differen solid joint styles in matplotlib.
plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)
maps = [m for m in plt.cm.datad if not m.endswith("_r")]
maps.sort()
l = len(maps) + 1 import numpy as np
import matplotlib.pyplot as plt
for i, m in enumerate(maps):
plt.subplot(1, l, i+1) size = 256, 16
plt.axis("off") dpi = 72.0
plt.imshow(a, aspect='auto', cmap=plt.get_cmap(m), origin="lower") figsize = size[0] / float(dpi), size[1] / float(dpi)
plt.title(m, rotation=90, fontsize=10, va='bottom') fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
plt.show() plt.axes([0, 0, 1, 1], frameon=False)
Total running time of the script: ( 0 minutes 2.670 seconds) plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8,
solid_joinstyle='miter')
Download Python source code: plot_colormaps.py plt.plot(4 + np.arange(3), [0, 1, 0], color="blue", linewidth=8,
solid_joinstyle='bevel')
Download Jupyter notebook: plot_colormaps.ipynb plt.plot(8 + np.arange(3), [0, 1, 0], color="blue", linewidth=8,
Generated by Sphinx-Gallery solid_joinstyle='round')
plt.xlim(0, 12)
Solid cap style plt.ylim(-1, 2)
plt.xticks(())
An example demoing the solide cap style in matplotlib. plt.yticks(())
plt.show()
4.7. Full code examples 158 4.7. Full code examples 159
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
import numpy as np
import matplotlib.pyplot as plt
Total running time of the script: ( 0 minutes 0.034 seconds)
size = 256, 16 Download Python source code: plot_dash_joinstyle.py
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi) Download Jupyter notebook: plot_dash_joinstyle.ipynb
fig = plt.figure(figsize=figsize, dpi=dpi)
Generated by Sphinx-Gallery
fig.patch.set_alpha(0)
plt.axes([0, 0, 1, 1], frameon=False)
Linestyles
plt.plot(np.arange(4), np.ones(4), color="blue", dashes=[15, 15],
linewidth=8, dash_capstyle='butt')
Plot the different line styles.
plt.plot(5 + np.arange(4), np.ones(4), color="blue", dashes=[15, 15],
linewidth=8, dash_capstyle='round')
plt.xlim(0, 14)
plt.xticks(())
plt.yticks(())
plt.show()
import numpy as np
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
def linestyle(ls, i):
size = 256, 16
X = i * .5 * np.ones(11)
dpi = 72.0
Y = np.arange(11)
figsize= size[0] / float(dpi), size[1] / float(dpi)
plt.plot(X, Y, ls, color=(.0, .0, 1, 1), lw=3, ms=8,
fig = plt.figure(figsize=figsize, dpi=dpi)
mfc=(.75, .75, 1, 1), mec=(0, 0, 1, 1))
fig.patch.set_alpha(0)
plt.text(.5 * i, 10.25, ls, rotation=90, fontsize=15, va='bottom')
plt.axes([0, 0, 1, 1], frameon=False)
4.7. Full code examples 160 4.7. Full code examples 161
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
linestyles = ['-', '--', ':', '-.', '.', ',', 'o', '^', 'v', '<', '>', 's', markers = [0, 1, 2, 3, 4, 5, 6, 7, 'o', 'h', '_', '1', '2', '3', '4',
'+', 'x', 'd', '1', '2', '3', '4', 'h', 'p', '|', '_', 'D', 'H'] '8', 'p', '^', 'v', '<', '>', '|', 'd', ',', '+', 's', '*',
n_lines = len(linestyles) '|', 'x', 'D', 'H', '.']
Download Python source code: plot_linestyles.py Total running time of the script: ( 0 minutes 0.070 seconds)
Download Jupyter notebook: plot_linestyles.ipynb Download Python source code: plot_markers.py
Generated by Sphinx-Gallery Download Jupyter notebook: plot_markers.ipynb
Generated by Sphinx-Gallery
Markers
import numpy as np
import matplotlib.pyplot as plt
4.7. Full code examples 162 4.7. Full code examples 163
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
ax.plot(np.arange(11), np.zeros(11))
return ax
locators = [
'plt.NullLocator()',
'plt.MultipleLocator(1.0)',
'plt.FixedLocator([0, 2, 8, 9, 10])',
'plt.IndexLocator(3, 1)',
'plt.LinearLocator(5)',
'plt.LogLocator(2, [1.0])',
'plt.AutoLocator()',
]
n_locators = len(locators)
plt.show()
4.7. Full code examples 164 4.7. Full code examples 165
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
4.7. Full code examples 166 4.7. Full code examples 167
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
X = np.linspace(0, 2, n)
Y = np.sin(2 * np.pi * X)
ax = plt.subplot(2, 2, 3)
ax.set_xticklabels([])
ax.set_yticklabels([])
4.7. Full code examples 168 4.7. Full code examples 169
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Download Python source code: plot_multiplot_ext.py plt.text(-0.05, 1.02, " Box Plot: plt.boxplot(...)\n ",
horizontalalignment='left',
Download Jupyter notebook: plot_multiplot_ext.ipynb
verticalalignment='top',
Generated by Sphinx-Gallery size='xx-large',
transform=axes.transAxes)
Boxplot with matplotlib plt.text(-0.04, .98, "\n Make a box and whisker plot ",
horizontalalignment='left',
An example of doing box plots with matplotlib verticalalignment='top',
size='large',
transform=axes.transAxes)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
n = 5
Z = np.zeros((n, 4))
X = np.linspace(0, 2, n, endpoint=True)
Y = np.random.random((n, 4))
plt.boxplot(Y)
plt.xticks(())
plt.yticks(())
4.7. Full code examples 170 4.7. Full code examples 171
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
import numpy as np
import matplotlib.pyplot as plt
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y,X)
4.7. Full code examples 172 4.7. Full code examples 173
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.xlim(-1.5, 1.5)
plt.ylim(-1.5 * r, 1.5 * r)
plt.xticks(())
plt.yticks(())
plt.show()
4.7. Full code examples 174 4.7. Full code examples 175
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
horizontalalignment='left', plt.xlim(-1, n)
verticalalignment='top', plt.xticks(())
size='large', plt.ylim(-1, n)
transform=plt.gca().transAxes) plt.yticks(())
plt.show()
# Add a title and a box around it
Total running time of the script: ( 0 minutes 0.056 seconds) from matplotlib.patches import FancyBboxPatch
ax = plt.gca()
Download Python source code: plot_bar_ext.py ax.add_patch(FancyBboxPatch((-0.05, .87),
width=.66, height=.165, clip_on=False,
Download Jupyter notebook: plot_bar_ext.ipynb
boxstyle="square,pad=0", zorder=3,
Generated by Sphinx-Gallery facecolor='white', alpha=1.0,
transform=plt.gca().transAxes))
plt.show()
Imshow demo
Demoing imshow
import numpy as np
import matplotlib.pyplot as plt
n = 8
X, Y = np.mgrid[0:n, 0:n]
T = np.arctan2(Y - n/ 2., X - n / 2.)
R = 10 + np.sqrt((Y - n / 2.) ** 2 + (X - n / 2.) ** 2)
U, V = R * np.cos(T), R * np.sin(T)
plt.quiver(X, Y, U, V, R, alpha=.5)
plt.quiver(X, Y, U, V, edgecolor='k', facecolor='None', linewidth=.5)
4.7. Full code examples 176 4.7. Full code examples 177
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
An example demoing how to plot the contours of a function, with additional layout tweeks.
import numpy as np
import matplotlib.pyplot as plt
n = 10
x = np.linspace(-3, 3, 8 * n)
y = np.linspace(-3, 3, 6 * n)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.imshow(Z, interpolation='nearest', cmap='bone', origin='lower')
plt.xticks(())
plt.yticks(())
4.7. Full code examples 178 4.7. Full code examples 179
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.text(-0.05, 1.01, "\n\n Draw contour lines and filled contours ",
horizontalalignment='left',
verticalalignment='top',
size='large',
transform=plt.gca().transAxes)
plt.show()
Total running time of the script: ( 0 minutes 0.092 seconds) import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
Download Python source code: plot_contour_ext.py
Download Jupyter notebook: plot_contour_ext.ipynb fig = plt.figure(figsize=(8, 6), dpi=72, facecolor="white")
axes = plt.subplot(111)
Generated by Sphinx-Gallery axes.set_xlim(0, 4)
axes.set_ylim(0, 3)
4.7. Full code examples 180 4.7. Full code examples 181
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
plt.xticks(())
plt.yticks(())
eqs = []
eqs.append((r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}
,→{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1␣
,→\rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$
,→"))
4.7. Full code examples 182 4.7. Full code examples 183
Scipy lecture notes, Edition 2017.1
5
• Signal processing: scipy.signal
• Image manipulation: scipy.ndimage
• Summary exercises on scientific computing
CHAPTER
• Full code examples for the scipy chapter
Warning: This tutorial is far from an introduction to numerical computing. As enumerating the different
submodules and functions in scipy would be very boring, we concentrate instead on a few examples to give
a general idea of how to use scipy for scientific computing.
Tip: scipy can be compared to other standard scientific-computing libraries, such as the GSL (GNU Scientific Tip: They all depend on numpy, but are mostly independent of each other. The standard way of importing
Library for C and C++), or Matlab’s toolboxes. scipy is the core package for scientific routines in Python; it is Numpy and these Scipy modules is:
meant to operate efficiently on numpy arrays, so that numpy and scipy work hand in hand.
>>> import numpy as np
Before implementing a routine, it is worth checking if the desired data processing is not already implemented >>> from scipy import stats # same for other sub-modules
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 The main scipy namespace mostly contains functions that are really numpy functions (try scipy.cos is
tested, and should therefore be used when possible. np.cos). Those are exposed for historical reasons; there’s no reason to use import scipy in your code.
Chapters contents
5.1 File input/output: scipy.io
• File input/output: scipy.io
• Special functions: scipy.special Matlab files: Loading and saving:
>>> data['a']
array([[ 1., 1., 1.], Tip: The scipy.linalg module provides standard linear algebra operations, relying on an underlying effi-
[ 1., 1., 1.], cient implementation (BLAS, LAPACK).
[ 1., 1., 1.]])
• The scipy.linalg.det() function computes the determinant of a square matrix:
Warning: Python / Matlab mismatches, eg matlab does not represent 1D arrays >>> from scipy import linalg
>>> arr = np.array([[1, 2],
>>> a = np.ones(3) ... [3, 4]])
>>> a >>> linalg.det(arr)
array([ 1., 1., 1.]) -2.0
>>> spio.savemat('file.mat', {'a': a}) >>> arr = np.array([[3, 2],
>>> spio.loadmat('file.mat')['a'] ... [6, 4]])
array([[ 1., 1., 1.]]) >>> linalg.det(arr)
0.0
Notice the difference? >>> linalg.det(np.ones((3, 4)))
Traceback (most recent call last):
...
ValueError: expected square matrix
• More advanced operations are available, for example singular-value decomposition (SVD):
5.2 Special functions: scipy.special >>> arr = np.arange(9).reshape((3, 3)) + np.diag([1, 0, 1])
>>> uarr, spec, vharr = linalg.svd(arr)
Special functions are transcendental functions. The docstring of the scipy.special module is well-written,
so we won’t list all functions here. Frequently used ones are: The resulting array spectrum is:
• Bessel function, such as scipy.special.jn() (nth integer order Bessel function) >>> spec
array([ 14.88982544, 0.45294236, 0.29654967])
• Elliptic function (scipy.special.ellipj() for the Jacobian elliptic function, . . . )
• Gamma function: scipy.special.gamma(), also note scipy.special.gammaln() which will give the The original matrix can be re-composed by matrix multiplication of the outputs of svd with np.dot:
log of Gamma to a higher numerical precision.
>>> sarr = np.diag(spec)
• Erf, the area under a Gaussian curve: scipy.special.erf() >>> svd_mat = uarr.dot(sarr).dot(vharr)
>>> np.allclose(svd_mat, arr)
True
5.3 Linear algebra operations: scipy.linalg SVD is commonly used in statistics and signal processing. Many other standard decompositions (QR,
LU, Cholesky, Schur), as well as solvers for linear systems, are available in scipy.linalg.
5.2. Special functions: scipy.special 186 5.3. Linear algebra operations: scipy.linalg 187
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
scipy.interpolate is useful for fitting a function from experimental data and thus evaluating points where
no measure exists. The module is based on the FITPACK Fortran subroutines.
By imagining experimental data close to a sine function:
If we know that the data lies on a sine wave, but not the amplitudes or the period, we can find those by least
squares curve fitting. First we have to define the test function to fit, here a sine with unknown amplitude and
period:
A cubic interpolation can also be selected by providing the kind optional keyword argument:
5.5 Optimization and fit: scipy.optimize The temperature extremes in Alaska for each month, starting in January, are given by (in degrees
Celcius):
Optimization is the problem of finding a numerical solution to a minimization or equality. max: 17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18
min: -62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58
Tip: The scipy.optimize module provides algorithms for function minimization (scalar or multi- 1. Plot these temperature extremes.
dimensional), curve fitting and root finding.
2. Define a function that can describe min and max temperatures. Hint: this function has to
>>> from scipy import optimize have a period of 1 year. Hint: include a time offset.
3. Fit this function to the data with scipy.optimize.curve_fit().
4. Plot the result. Is the fit reasonable? If not, why?
5.4. Interpolation: scipy.interpolate 188 5.5. Optimization and fit: scipy.optimize 189
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
5. Is the time offset for min and max temperatures the same within the fit accuracy? >>> result.x # The coordinate of the minimum
solution array([-1.30644...])
Methods: As the function is a smooth function, gradient-descent based methods are good options. The lBFGS
algorithm is a good choice in general:
Note how it cost only 12 functions evaluation above to find a good value for the minimum.
>>> def f(x): Global minimum: A possible issue with this approach is that, if the function has local minima, the algorithm
... return x**2 + 10*np.sin(x)
may find these local minima instead of the global minimum depending on the initial point x0:
5.5. Optimization and fit: scipy.optimize 190 5.5. Optimization and fit: scipy.optimize 191
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
A list of bounds • Use numpy.meshgrid() and pylab.imshow() to find visually the regions.
• Use scipy.optimize.minimize(), optionally trying out several of its ‘methods’.
As minimize() works in general with x multidimensionsal, the “bounds” argument is a list of bound on
each dimension. How many global minima are there, and what is the function value at those points? What hap-
pens for an initial guess of (x, y) = (0, 0) ?
>>> res = optimize.minimize(f, x0=1, solution
... bounds=((0, 10), ))
>>> res.x
array([ 0.])
5.5.3 Finding the roots of a scalar function
Tip: What has happened? Why are we finding 0, which is not a mimimum of our function. To find a root, i.e. a point where f (x) = 0, of the function f above we can use scipy.optimize.root():
Note: scipy.optimize.root() also comes with a variety of algorithms, set via the “method” argument.
5.5. Optimization and fit: scipy.optimize 192 5.5. Optimization and fit: scipy.optimize 193
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
You can find all algorithms and functions with similar functionalities in the documentation of scipy. If we know that the random process belongs to a given family of random processes, such as normal processes,
optimize. we can do a maximum-likelihood fit of the observations to estimate the parameters of the underlying distri-
bution. Here we fit a normal process to the observed data:
See the summary exercise on Non linear least squares curve fitting: application to point extraction in topo-
graphical lidar data for another, more advanced example. >>> loc, std = stats.norm.fit(samples)
>>> loc
-0.045256707...
5.6 Statistics and random numbers: scipy.stats >>> std
0.9870331586...
The module scipy.stats contains statistical tools and probabilistic descriptions of random processes. Ran-
dom number generators for various random process can be found in numpy.random. Exercise: Probability distributions
Generate 1000 random variates from a gamma distribution with a shape parameter of 1, then plot a his-
5.6.1 Distributions: histogram and probability density function togram from those samples. Can you plot the pdf on top (it should match)?
Given observations of a random process, their histogram is an estimator of the random process’s PDF (proba- Extra: the distributions have many useful methods. Explore them by reading the docstring or by using tab
bility density function): completion. Can you recover the shape parameter 1 by using the fit method on your random variates?
Tip: Unlike the mean, the median is not sensitive to the tails of the distribution. It is “robust”.
Which one seems to be the best estimator of the center for the Gamma distribution?
The median is also the percentile 50, because 50% of the observation are below it:
5.6. Statistics and random numbers: scipy.stats 194 5.6. Statistics and random numbers: scipy.stats 195
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
dy
As an introduction, let us solve the ODE d t = −2y between t = 0 . . . 4, with the initial condition y(t = 0) = 1.
First the function computing the derivative of the position needs to be defined:
scipy.integrate also features routines for integrating Ordinary Differential Equations (ODE). In particular,
5.7. Numerical integration: scipy.integrate 196 5.7. Numerical integration: scipy.integrate 197
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Tip: scipy.integrate.odeint() uses the LSODA (Livermore Solver for Ordinary Differential equations As the signal comes from a real function, the Fourier transform is symmetric.
with Automatic method switching for stiff and non-stiff problems), see the ODEPACK Fortran library for more The peak signal frequency can be found with freqs[power.argmax()]
details.
See also:
Partial Differental Equations
There is no Partial Differential Equations (PDE) solver in Scipy. Some Python packages for solving PDE’s are
available, such as fipy or SfePy.
The scipy.fftpack module computes fast Fourier transforms (FFTs) and offers utilities to handle them. The
main functions are:
• scipy.fftpack.fft() to compute the FFT
• scipy.fftpack.fftfreq() to generate the sampling frequencies
• scipy.fftpack.ifft() computes the inverse FFT, from frequency space to signal space Setting the Fourrier component above
this frequency to zero and inverting the FFT with scipy.fftpack.ifft(), gives a filtered signal.
5.8. Fast Fourier transforms: scipy.fftpack 198 5.8. Fast Fourier transforms: scipy.fftpack 199
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
4. The spectrum consists of high and low frequency components. The noise is contained in the high-
Crude periodicity finding (link) Gaussian image blur (link)
frequency part of the spectrum, so set some of those components to zero (use array slicing).
5. Apply the inverse Fourier transform to see the resulting image.
Solution
>>> 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 reg-
ularly sampled data.
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 pylab.imread().
3. Find and use the 2-D FFT function in scipy.fftpack, and plot the spectrum (Fourier transform of )
the image. Do you have any trouble visualising the spectrum? If so, why?
5.8. Fast Fourier transforms: scipy.fftpack 200 5.9. Signal processing: scipy.signal 201
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> plt.subplot(151)
<matplotlib.axes._subplots.AxesSubplot object at 0x...>
>>> plt.axis('off')
(-0.5, 1023.5, 767.5, -0.5)
>>> # etc.
5.9. Signal processing: scipy.signal 202 5.10. Image manipulation: scipy.ndimage 203
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Tip: Mathematical morphology stems from set theory. It characterizes and transforms geometrical structures. • Dilation scipy.ndimage.binary_dilation()
Binary (black and white) images, in particular, can be transformed using this theory: the sets to be transformed >>> a = np.zeros((5, 5))
are the sets of neighboring non-zero-valued pixels. The theory was also extended to gray-valued images. >>> a[2, 2] = 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ndimage.binary_dilation(a).astype(a.dtype)
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.]])
• Opening scipy.ndimage.binary_opening()
Mathematical-morphology operations use a structuring element in order to modify geometrical structures. >>> a = np.zeros((5, 5), dtype=np.int)
>>> a[1:4, 1:4] = 1
Let us first generate a structuring element: >>> a[4, 4] = 1
>>> a
>>> el = ndimage.generate_binary_structure(2, 1)
array([[0, 0, 0, 0, 0],
>>> el
5.10. Image manipulation: scipy.ndimage 204 5.10. Image manipulation: scipy.ndimage 205
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
An opening operation removes small structures, while a closing operation fills small holes. Such operations
can therefore be used to “clean” an image.
For gray-valued images, eroding (resp. dilating) amounts to replacing a pixel by the minimal (resp. maximal)
value among pixels covered by the structuring element centered on the pixel of interest.
5.10. Image manipulation: scipy.ndimage 206 5.10. Image manipulation: scipy.ndimage 207
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
The annual wind speeds maxima have already been computed and saved in the numpy format in the file
examples/max-speeds.npy, thus they will be loaded by using numpy:
Following the cumulative probability definition p_i from the previous section, the corresponding values will
be:
>>> ndimage.find_objects(labels==4) and they are assumed to fit the given wind speeds:
[(slice(30L, 48L, None), slice(30L, 48L, None))]
>>> sl = ndimage.find_objects(labels==4) >>> sorted_max_speeds = np.sort(max_speeds)
>>> from matplotlib import pyplot as plt
>>> plt.imshow(sig[sl[0]])
<matplotlib.image.AxesImage object at ...> Prediction with UnivariateSpline
See the summary exercise on Image processing application: counting bubbles and unmolten grains for a more In this section the quantile function will be estimated by using the UnivariateSpline class which can
advanced example. represent a spline from points. The default behavior is to build a spline of degree 3 and points can
have different weights according to their reliability. Variants are InterpolatedUnivariateSpline and
LSQUnivariateSpline on which errors checking is going to change. In case a 2D spline is wanted, the
5.11 Summary exercises on scientific computing BivariateSpline class family is provided. All those classes for 1D and 2D splines use the FITPACK For-
tran subroutines, that’s why a lower library access is available through the splrep and splev functions for
respectively representing and evaluating a spline. Moreover interpolation functions without the use of FIT-
The summary exercises use mainly Numpy, Scipy and Matplotlib. They provide some real-life examples of sci-
PACK parameters are also provided for simpler use (see interp1d, interp2d, barycentric_interpolate
entific computing with Python. Now that the basics of working with Numpy and Scipy have been introduced,
and so on).
the interested user is invited to try these exercises.
For the Sprogø maxima wind speeds, the UnivariateSpline will be used because a spline of degree 3 seems
to correctly fit the data:
5.11.1 Maximum wind speed prediction at the Sprogø station
>>> from scipy.interpolate import UnivariateSpline
The exercise goal is to predict the maximum wind speed occurring every 50 years even if no measure exists >>> quantile_func = UnivariateSpline(cprob, sorted_max_speeds)
for such a period. The available data are only measured over 21 years at the Sprogø meteorological station
located in Denmark. First, the statistical steps will be given and then illustrated with functions from the The quantile function is now going to be evaluated from the full range of probabilities:
scipy.interpolate module. At the end the interested readers are invited to compute results from raw data and
>>> nprob = np.linspace(0, 1, 1e2)
in a slightly different approach. >>> fitted_max_speeds = quantile_func(nprob)
Statistical approach In the current model, the maximum wind speed occurring every 50 years is defined as the upper 2% quantile.
As a result, the cumulative probability value will be:
The annual maxima are supposed to fit a normal probability density function. However such function is not >>> fifty_prob = 1. - 0.02
going to be estimated because it gives a probability from a wind speed maxima. Finding the maximum wind
speed occurring every 50 years requires the opposite approach, the result needs to be found from a defined
So the storm wind speed occurring every 50 years can be guessed by:
probability. That is the quantile function role and the exercise goal will be to find it. In the current model, it is
supposed that the maximum wind speed occurring every 50 years is defined as the upper 2% quantile. >>> fifty_wind = quantile_func(fifty_prob)
>>> fifty_wind
By definition, the quantile function is the inverse of the cumulative distribution function. The latter describes
array(32.97989825...)
the probability distribution of an annual maxima. In the exercise, the cumulative probability p_i for a given
year i is defined as p_i = i/(N+1) with N = 21, the number of measured years. Thus it will be possible to
The results are now gathered on a Matplotlib figure:
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. Exercise with the Gumbell distribution
The interested readers are now invited to make an exercise by using the wind speeds measured over 21 years.
The measurement period is around 90 minutes (the original period was around 10 minutes but the file size
has been reduced for making the exercise setup easier). The data are stored in numpy format inside the file
5.11. Summary exercises on scientific computing 208 5.11. Summary exercises on scientific computing 209
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
examples/sprog-windspeeds.npy. Do not look at the source code for the plots until you have completed
the exercise.
• The first step will be to find the annual maxima by using numpy and plot them as a matplotlib bar figure.
• The second step will be to use the Gumbell distribution on cumulative probabilities p_i defined as
-log( -log(p_i) ) for fitting a linear quantile function (remember that you can define the degree
of the UnivariateSpline). Plotting the annual maxima versus the Gumbell distribution should give
you the following figure.
• The last step will be to find 34.23 m/s for the maximum wind speed occurring every 50 years.
Fig. 5.1: Solution: Python source file 5.11.2 Non linear least squares curve fitting: application to point extraction in
topographical lidar data
The goal of this exercise is to fit a model to some data. The data used in this tutorial are lidar data and are
described in details in the following introductory paragraph. If you’re impatient and want to practice now,
please skip it and go directly to Loading and visualization.
Introduction
Lidars systems are optical rangefinders that analyze property of scattered light to measure distances. Most of
them emit a short light impulsion towards a target and record the reflected signal. This signal is then processed
to extract the distance between the lidar system and the target.
5.11. Summary exercises on scientific computing 210 5.11. Summary exercises on scientific computing 211
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Topographical lidar systems are such systems embedded in airborne platforms. They measure distances be-
tween 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.
1 Mallet, C. and Bretar, F. Full-Waveform Topographic Lidar: State-of-the-Art. ISPRS Journal of Photogrammetry and Remote Sensing
64(1), pp.1-16, January 2009 http://dx.doi.org/10.1016/j.isprsjprs.2008.09.007
2 The data used for this tutorial are part of the demonstration data available for the FullAnalyze software and were kindly provided by
the GIS DRAIX.
5.11. Summary exercises on scientific computing 212 5.11. Summary exercises on scientific computing 213
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• coeffs[3] is σ (width)
Initial solution
An approximative initial solution that we can find from looking at the graph is for instance:
Fit
scipy.optimize.leastsq minimizes the sum of squares of the function given as an argument. Basically, the
function to minimize is the residuals (the difference between the data and the model):
So let’s get our solution by calling scipy.optimize.leastsq() with the following arguments:
• the function to minimize
• an initial solution
• the additional arguments to pass to the function
As you can notice, this waveform is a 80-bin-length signal with a single peak. And visualize the solution:
Model • Try with a more complex waveform (for instance data/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
A Gaussian function defined by peak.
½ µ ¶ ¾
t −µ 2
B + A exp −
σ
can be defined in python by:
where
• coeffs[0] is B (noise)
• coeffs[1] is A (amplitude)
• coeffs[2] is µ (center)
5.11. Summary exercises on scientific computing 214 5.11. Summary exercises on scientific computing 215
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• In some cases, writing an explicit function to compute the Jacobian is faster than letting leastsq esti-
mate it numerically. Create a function to compute the Jacobian of the residuals and use it as an input for
leastsq.
• When we want to detect very small peaks in the signal, or when the initial guess is too far from a good
solution, the result given by the algorithm is often not satisfying. Adding constraints to the parameters
of the model enables to overcome such limitations. An example of a priori knowledge we can add is the
sign of our variables (which are all positive).
With the following initial solution:
compare the result of scipy.optimize.leastsq() and what you can get with scipy.optimize. Statement of the problem
fmin_slsqp() when adding boundary constraints.
1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments in the doc-
string of imshow to display the image with the “right” orientation (origin in the bottom left corner, and not the
upper left corner as for standard arrays).
This Scanning Element Microscopy image shows a glass sample (light gray matrix) with some bubbles (on
black) and unmolten sand grains (dark gray). We wish to determine the fraction of the sample covered by
these three phases, and to estimate the typical size of sand grains and bubbles, their sizes, etc.
2. Crop the image to remove the lower panel with measure information.
3. Slightly filter the image with a median filter in order to refine its histogram. Check how the histogram
changes.
4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand pixels,
glass pixels and bubble pixels. Other option (homework): write a function that determines automatically the
thresholds from the minima of the histogram.
5. Display an image in which the three phases are colored with three different colors.
6. Use mathematical morphology to clean the different phases.
5.11. Summary exercises on scientific computing 216 5.11. Summary exercises on scientific computing 217
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
7. Attribute labels to all bubbles and sand grains, and remove from the sand mask grains that are smaller than
>>> filtdat = ndimage.median_filter(dat, size=(7,7))
10 pixels. To do so, use ndimage.sum or np.bincount to compute the grain sizes. >>> hi_dat = np.histogram(dat, bins=np.arange(256))
8. Compute the mean size of bubbles. >>> hi_filtdat = np.histogram(filtdat, bins=np.arange(256))
Proposed solution
5.11.4 Example of solution for the image processing exercise: unmolten grains in
glass
4. Using the histogram of the filtered image, determine thresholds that allow to define masks for sand pix-
els, glass pixels and bubble pixels. Other option (homework): write a function that determines automat-
ically the thresholds from the minima of the histogram.
5. Display an image in which the three phases are colored with three different colors.
1. Open the image file MV_HFV_012.jpg and display it. Browse through the keyword arguments in the
docstring of imshow to display the image with the “right” orientation (origin in the bottom left corner,
and not the upper left corner as for standard arrays).
2. Crop the image to remove the lower panel with measure information.
3. Slightly filter the image with a median filter in order to refine its histogram. Check how the histogram
changes.
5.11. Summary exercises on scientific computing 218 5.11. Summary exercises on scientific computing 219
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2 + 10*np.sin(x)
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.
5.11. Summary exercises on scientific computing 220 5.12. Full code examples for the scipy chapter 221
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Out:
fun: array([-7.94582338])
hess_inv: <1x1 LbfgsInvHessProduct with dtype=float64>
jac: array([ -1.42108547e-06])
message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
nfev: 12
nit: 5
status: 0
success: True
x: array([-1.30644013])
plt.show()
Total running time of the script: ( 0 minutes 0.103 seconds) Total running time of the script: ( 0 minutes 0.187 seconds)
Download Python source code: plot_optimize_example1.py Download Python source code: plot_detrend.py
Download Jupyter notebook: plot_optimize_example1.ipynb Download Jupyter notebook: plot_detrend.ipynb
Generated by Sphinx-Gallery Generated by Sphinx-Gallery
Plot Plot
from matplotlib import pyplot as plt from matplotlib import pyplot as plt
plt.figure(figsize=(5, 4)) plt.figure(figsize=(5, 4))
plt.plot(t, x, label="x") plt.plot(t, x, label='Original signal')
plt.plot(t, x_detrended, label="x_detrended") plt.plot(t[::4], x_resampled, 'ko', label='Resampled signal')
plt.legend(loc='best')
plt.show() plt.legend(loc='best')
plt.show()
5.12. Full code examples for the scipy chapter 222 5.12. Full code examples for the scipy chapter 223
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.figure(figsize=(4, 3))
plt.plot(time_vec, yvec)
plt.xlabel('t: Time')
plt.ylabel('y: Position')
plt.tight_layout()
Solve the ODE dy/dt = -2y between t = 0..4, with the initial condition y(t=0) = 1.
import numpy as np
from matplotlib import pyplot as plt
5.12. Full code examples for the scipy chapter 224 5.12. Full code examples for the scipy chapter 225
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
from scipy.integrate import odeint import numpy as np
from matplotlib import pyplot as plt
# Sample from a normal distribution using numpy's random number generator
mass = 0.5 # kg samples = np.random.normal(size=10000)
kspring = 4 # N/m
cviscous = 0.4 # N s/m # Compute a histogram of the sample
bins = np.linspace(-5, 5, 30)
histogram, bins = np.histogram(samples, bins=bins, normed=True)
eps = cviscous / (2 * mass * np.sqrt(kspring/mass))
omega = np.sqrt(kspring / mass) bin_centers = 0.5*(bins[1:] + bins[:-1])
# Compute the PDF on the bin centers from scipy distribution object
def calc_deri(yvec, time, eps, omega): from scipy import stats
return (yvec[1], -eps * omega * yvec[1] - omega **2 * yvec[0]) pdf = stats.norm.pdf(bin_centers)
5.12. Full code examples for the scipy chapter 226 5.12. Full code examples for the scipy chapter 227
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.figure(figsize=(6, 4))
5.12.8 Curve fitting plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, test_func(x_data, params[0], params[1]),
Demos a simple curve fitting label='Fitted function')
First generate some data
plt.legend(loc='best')
import numpy as np
plt.show()
# Seed the random number generator for reproducibility
np.random.seed(0)
# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)
5.12. Full code examples for the scipy chapter 228 5.12. Full code examples for the scipy chapter 229
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
time_step = .01
time_vec = np.arange(0, 70, time_step)
plt.figure(figsize=(8, 5))
plt.plot(time_vec, sig)
plt.figure(figsize=(5, 4))
plt.semilogx(freqs, psd)
plt.title('PSD: power spectral density')
plt.xlabel('Frequency')
Compute and plot the spectrogram plt.ylabel('Power')
plt.tight_layout()
The spectrum of the signal on consecutive time windows
plt.figure(figsize=(5, 4))
plt.imshow(spectrogram, aspect='auto', cmap='hot_r', origin='lower')
plt.title('Spectrogram')
plt.ylabel('Frequency band')
plt.xlabel('Time window')
plt.tight_layout()
5.12. Full code examples for the scipy chapter 230 5.12. Full code examples for the scipy chapter 231
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.show()
Total running time of the script: ( 0 minutes 0.303 seconds) # Generate data
Download Python source code: plot_spectrogram.py import numpy as np
np.random.seed(0)
Download Jupyter notebook: plot_spectrogram.ipynb measured_time = np.linspace(0, 1, 10)
noise = 1e-1 * (np.random.random(10)*2 - 1)
Generated by Sphinx-Gallery measures = np.sin(2 * np.pi * measured_time) + noise
5.12. Full code examples for the scipy chapter 232 5.12. Full code examples for the scipy chapter 233
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.subplot(142) plt.subplot(153)
plt.imshow(mask, cmap=plt.cm.gray) plt.imshow(rotated_face, cmap=plt.cm.gray)
plt.axis('off') plt.axis('off')
plt.title('mask')
plt.subplot(154)
plt.subplot(143) plt.imshow(cropped_face, cmap=plt.cm.gray)
plt.imshow(opened_mask, cmap=plt.cm.gray) plt.axis('off')
plt.axis('off')
plt.title('opened_mask') plt.subplot(155)
plt.imshow(zoomed_face, cmap=plt.cm.gray)
plt.subplot(144) plt.axis('off')
plt.imshow(closed_mask, cmap=plt.cm.gray)
plt.title('closed_mask') plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)
plt.axis('off')
plt.show()
plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)
Total running time of the script: ( 0 minutes 0.916 seconds)
plt.show()
Download Python source code: plot_image_transform.py
Total running time of the script: ( 0 minutes 0.133 seconds)
Download Jupyter notebook: plot_image_transform.ipynb
Download Python source code: plot_mathematical_morpho.py
Generated by Sphinx-Gallery
Download Jupyter notebook: plot_mathematical_morpho.ipynb
5.12. Full code examples for the scipy chapter 234 5.12. Full code examples for the scipy chapter 235
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
from matplotlib import pyplot as plt
np.random.seed(0)
x, y = np.indices((100, 100))
sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2
mask = sig > 1
plt.figure(figsize=(7, 3.5))
plt.subplot(1, 2, 1)
plt.imshow(sig)
plt.axis('off')
plt.title('sig')
plt.subplot(1, 2, 2)
plt.imshow(mask, cmap=plt.cm.gray)
plt.axis('off')
plt.title('mask')
plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9) Extract the 4th connected component, and crop the array around it
sl = ndimage.find_objects(labels==4)
plt.figure(figsize=(3.5, 3.5))
plt.imshow(sig[sl[0]])
plt.title('Cropped connected component')
plt.axis('off')
plt.show()
plt.figure(figsize=(3.5, 3.5))
plt.imshow(labels)
plt.title('label')
plt.axis('off')
5.12. Full code examples for the scipy chapter 236 5.12. Full code examples for the scipy chapter 237
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Generated by Sphinx-Gallery
ax.plot(xmins, f(xmins), 'go', label="Minima")
Find minima
# Global optimization
grid = (-10, 10, 0.1)
xmin_global = optimize.brute(f, (grid, ))
print("Global minima found %s " % xmin_global)
# Constrain optimization
xmin_local = optimize.fminbound(f, 0, 10)
print("Local minimum found %s " % xmin_local)
Out:
Root finding
root = optimize.root(f, 1) # our initial guess is 1 Total running time of the script: ( 0 minutes 0.043 seconds)
print("First root found %s " % root.x)
root2 = optimize.root(f, -2.5) Download Python source code: plot_optimize_example2.py
print("Second root found %s " % root2.x)
Download Jupyter notebook: plot_optimize_example2.ipynb
Out: Generated by Sphinx-Gallery
import numpy as np
Plot function, minima, and roots
5.12. Full code examples for the scipy chapter 238 5.12. Full code examples for the scipy chapter 239
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Simple visualization in 2D
plt.figure()
# Show the function in 2D
plt.imshow(sixhump([xg, yg]), extent=[-2, 2, -1, 1])
A 3D surface plot of the function plt.colorbar()
# And the minimum that we've found:
from mpl_toolkits.mplot3d import Axes3D plt.scatter(x_min.x[0], x_min.x[1])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') plt.show()
surf = ax.plot_surface(xg, yg, sixhump([xg, yg]), rstride=1, cstride=1,
cmap=plt.cm.jet, linewidth=0, antialiased=False)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x, y)')
ax.set_title('Six-hump Camelback function')
5.12. Full code examples for the scipy chapter 240 5.12. Full code examples for the scipy chapter 241
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
noisy_face = np.copy(face).astype(np.float)
noisy_face += face.std() * 0.5 * np.random.standard_normal(face.shape)
blurred_face = ndimage.gaussian_filter(noisy_face, sigma=3)
median_face = ndimage.median_filter(noisy_face, size=5)
wiener_face = signal.wiener(noisy_face, (5, 5))
plt.figure(figsize=(12, 3.5))
plt.subplot(141)
plt.imshow(noisy_face, cmap=plt.cm.gray)
plt.axis('off')
plt.title('noisy')
plt.subplot(142)
plt.imshow(blurred_face, cmap=plt.cm.gray)
plt.axis('off')
plt.title('Gaussian filter')
plt.subplot(143)
plt.imshow(median_face, cmap=plt.cm.gray)
plt.axis('off')
plt.title('median filter')
plt.subplot(144)
plt.imshow(wiener_face, cmap=plt.cm.gray)
plt.title('Wiener filter')
plt.axis('off')
Total running time of the script: ( 0 minutes 0.236 seconds) plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.99)
Plot the power of the FFT of a signal and inverse FFT back to reconstruct a signal.
This example demonstrate scipy.fftpack.fft(), scipy.fftpack.fftfreq() and scipy.fftpack.
ifft(). It implements a basic filter that is very suboptimal, and should not be used.
import numpy as np
from scipy import fftpack
from matplotlib import pyplot as plt
5.12. Full code examples for the scipy chapter 242 5.12. Full code examples for the scipy chapter 243
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
freqs = sample_freq[pos_mask]
time_vec = np.arange(0, 20, time_step) peak_freq = freqs[power[pos_mask].argmax()]
sig = (np.sin(2 * np.pi / period * time_vec)
+ 0.5 * np.random.randn(time_vec.size)) # Check that it does indeed correspond to the frequency that we generate
# the signal with
plt.figure(figsize=(6, 5)) np.allclose(peak_freq, 1./period)
plt.plot(time_vec, sig, label='Original signal')
# An inner plot to show the peak frequency
axes = plt.axes([0.55, 0.3, 0.3, 0.5])
plt.title('Peak frequency')
plt.plot(freqs[:8], power[:8])
plt.setp(axes, yticks=[])
5.12. Full code examples for the scipy chapter 244 5.12. Full code examples for the scipy chapter 245
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Note This is actually a bad way of creating a filter: such brutal cut-off in frequency space does not control
distorsion on the signal.
Filters should be created using the scipy filter design code
plt.show()
plt.figure()
plt.plot(periods, abs(ft_populations) * 1e-3, 'o')
5.12. Full code examples for the scipy chapter 246 5.12. Full code examples for the scipy chapter 247
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.xlim(0, 22)
plt.xlabel('Period') import matplotlib.pyplot as plt
plt.ylabel('Power ($\cdot10^3$)') months = np.arange(12)
plt.plot(months, temp_max, 'ro')
plt.show() plt.plot(months, temp_min, 'bo')
plt.xlabel('Month')
plt.ylabel('Min and max temperature')
There’s probably a period of around 10 years (obvious from the plot), but for this crude a method, there’s not
enough data to say much more.
Total running time of the script: ( 0 minutes 0.073 seconds)
Fitting it to a periodic function
Download Python source code: plot_periodicity_finder.py
Download Jupyter notebook: plot_periodicity_finder.ipynb from scipy import optimize
def yearly_temps(times, avg, ampl, time_offset):
Generated by Sphinx-Gallery return (avg
+ ampl * np.cos((times + time_offset) * 2 * np.pi / times.max()))
Curve fitting: temperature as a function of month of the year res_max, cov_max = optimize.curve_fit(yearly_temps, months,
temp_max, [20, 10, 0])
We have the min and max temperatures in Alaska for each months of the year. We would like to find a function res_min, cov_min = optimize.curve_fit(yearly_temps, months,
to describe this yearly evolution. temp_min, [-40, 20, 0])
For this, we will fit a periodic function.
5.12. Full code examples for the scipy chapter 248 5.12. Full code examples for the scipy chapter 249
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
# convolve
img_ft = fftpack.fft2(img, axes=(0, 1))
# the 'newaxis' is to match to color direction
5.12. Full code examples for the scipy chapter 250 5.12. Full code examples for the scipy chapter 251
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
# 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()
im = plt.imread('../../../../data/moonlanding.png').astype(float)
5.12. Full code examples for the scipy chapter 252 5.12. Full code examples for the scipy chapter 253
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.figure()
plt.imshow(im, plt.cm.gray)
plt.title('Original image')
Filter in FFT
# In the lines following, we'll make a copy of the original spectrum and
# truncate coefficients.
Compute the 2d FFT of the input image # Define the fraction of coefficients (in each direction) we keep
keep_fraction = 0.1
from scipy import fftpack # Call ff a copy of the original transform. Numpy arrays have a copy
im_fft = fftpack.fft2(im) # method for this purpose.
im_fft2 = im_fft.copy()
# Show the results
# Set r and c to be the number of rows and columns of the array.
def plot_spectrum(im_fft): r, c = im_fft2.shape
from matplotlib.colors import LogNorm
# 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):
plt.colorbar() im_fft2[int(r*keep_fraction):int(r*(1-keep_fraction))] = 0
plt.figure() # Similarly with the columns:
plot_spectrum(im_fft) im_fft2[:, int(c*keep_fraction):int(c*(1-keep_fraction))] = 0
plt.title('Fourier transform')
plt.figure()
plot_spectrum(im_fft2)
plt.title('Filtered Spectrum')
5.12. Full code examples for the scipy chapter 254 5.12. Full code examples for the scipy chapter 255
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
# Reconstruct the denoised image from the filtered spectrum, keep only the Implementing filtering directly with FFTs is tricky and time consuming. We can use the Gaussian
# real part for display. filter from scipy.ndimage
im_new = fftpack.ifft2(im_fft2).real
from scipy import ndimage
plt.figure() im_blur = ndimage.gaussian_filter(im, 4)
plt.imshow(im_new, plt.cm.gray)
plt.title('Reconstructed Image') plt.figure()
plt.imshow(im_blur, plt.cm.gray)
plt.title('Blurred image')
plt.show()
5.12. Full code examples for the scipy chapter 256 5.12. Full code examples for the scipy chapter 257
Scipy lecture notes, Edition 2017.1
CHAPTER 6
Getting help and finding documentation
Total running time of the script: ( 0 minutes 0.381 seconds) Author: Emmanuelle Gouillart
Download Python source code: plot_fft_image_denoise.py 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:
Download Jupyter notebook: plot_fft_image_denoise.ipynb
• In Ipython, help function opens the docstring of the function. Only type the beginning of the func-
Generated by Sphinx-Gallery
tion’s name and use tab completion to display the matching functions.
Download all examples in Python source code: auto_examples_python.zip
In [204]: help np.v
Download all examples in Jupyter notebooks: auto_examples_jupyter.zip np.vander np.vdot np.version np.void0 np.vstack
np.var np.vectorize np.void np.vsplit
Generated by Sphinx-Gallery
See also: In [204]: help np.vander
References to go further In Ipython it is not possible to open a separated window for help and documentation; how-
• Some chapters of the advanced and the packages and applications parts of the scipy lectures ever 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 http://docs.scipy.org/doc. The search
button is quite useful inside the reference documentation of the two packages (http://docs.scipy.org/
doc/numpy/reference/ and http://docs.scipy.org/doc/scipy/reference/).
5.12. Full code examples for the scipy chapter 258 259
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Tutorials on various topics as well as the complete API with all docstrings are found on this website.
remove(path)
os.removedirs
removedirs(path)
os.rmdir
rmdir(path)
os.unlink
unlink(path)
os.walk
Directory tree generator.
• If everything listed above fails (and Google doesn’t have the answer). . . don’t despair! Write to the
mailing-list suited to your problem: you should have a quick answer if you describe your problem well.
Experts on scientific python often give very enlightening explanations on the mailing-list.
• Numpy’s and Scipy’s documentation is enriched and updated on a regular basis by users on a wiki http:
//docs.scipy.org/doc/numpy/. As a result, some docstrings are clearer or more detailed on the wiki, – Numpy discussion (numpy-discussion@scipy.org): all about numpy arrays, manipulating them,
and you may want to read directly the documentation on the wiki instead of the official documentation indexation questions, etc.
website. Note that anyone can create an account on the wiki and write better documentation; this is an
– SciPy Users List (scipy-user@scipy.org): scientific computing with Python, high-level data process-
easy way to contribute to an open-source project and improve the tools you are using!
ing, in particular with the scipy package.
• Scipy central http://central.scipy.org/ gives recipes on many common problems frequently encoun-
– matplotlib-users@lists.sourceforge.net for plotting with matplotlib.
In [45]: numpy.lookfor('convolution')
Search results for 'convolution'
--------------------------------
numpy.convolve
Returns the discrete, linear convolution of two one-dimensional
sequences.
numpy.bartlett
Return the Bartlett window.
numpy.correlate
Discrete, linear correlation of two 1-dimensional sequences.
In [46]: numpy.lookfor('remove', module='os')
Search results for 'remove'
---------------------------
os.remove
260 261
Scipy lecture notes, Edition 2017.1
This part of the Scipy lecture notes 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
262 263
Scipy lecture notes, Edition 2017.1
7
– A while-loop removing decorator
– A plugin registration system
• Context managers
CHAPTER
– Catching exceptions
– Using generators to define context managers
7.1.1 Iterators
Advanced Python Constructs
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˛edrzejewski-Szmek An iterator is an object adhering to the iterator protocol — basically this means that it has a next method,
This section covers some features of the Python language which can be considered advanced — in the sense which, when called, returns the next item in the sequence, and when there’s nothing to return, raises the
that not every language has them, and also in the sense that they are more useful in more complicated pro- StopIteration exception.
grams 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
It is important to underline that this chapter is purely about the language itself — about features supported side, each loop over a sequence requires a single iterator object. This means that we can iterate over the same
through special syntax complemented by functionality of the Python stdlib, which could not be implemented sequence more than once concurrently. Separating the iteration logic from the sequence allows us to have
through clever external modules. more than one way of iteration.
The process of developing the Python programming language, its syntax, is very transparent; proposed Calling the __iter__ method on a container to create an iterator object is the most straightforward way to get
changes are evaluated from various angles and discussed via Python Enhancement Proposals — PEPs. As a hold of an iterator. The iter function does that for us, saving a few keystrokes.
result, features described in this chapter were added after it was shown that they indeed solve real problems >>> nums = [1, 2, 3] # note that ... varies: these are different objects
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)
1
– Generators
>>> next(it)
– Bidirectional communication 2
>>> next(it)
– Chaining generators 3
>>> next(it)
• Decorators
Traceback (most recent call last):
– Replacing or tweaking the original object File "<stdin>", line 1, in <module>
StopIteration
When used in a loop, StopIteration is swallowed and causes the loop to finish. But with explicit invocation, of a generator function creates a generator object, adhering to the iterator protocol. As with normal function
we can see that once the iterator is exhausted, accessing it raises an exception. 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 When next is called, the function is executed until the first yield. Each encountered yield statement gives a
sequence. But if we already have the iterator, we want to be able to use it in an for loop in the same way. In value becomes the return value of next. After executing the yield statement, the execution of this function is
order to achieve this, iterators in addition to next are also required to have a method called __iter__ which suspended.
returns the iterator (self).
>>> def f():
Support for iteration is pervasive in Python: all sequences and unordered containers in the standard library ... yield 1
allow this. The concept is also stretched to other things: e.g. file objects support iteration over lines. ... yield 2
>>> f()
>>> f = open('/etc/fstab') <generator object f at 0x...>
>>> f is f.__iter__() >>> gen = f()
True >>> next(gen)
1
The file is an iterator itself and it’s __iter__ method doesn’t create a separate object: only a single thread of >>> next(gen)
sequential access is allowed. 2
>>> 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 compre-
hensions. To increase clarity, a generator expression must always be enclosed in parentheses or an expression. Let’s go over the life of the single invocation of the generator function.
If round parentheses are used, then a generator iterator is created. If rectangular parentheses are used, the pro-
>>> def f():
cess is short-circuited and we get a list. ... print("-- start --")
... yield 3
>>> (i for i in nums)
... print("-- middle --")
<generator object <genexpr> at 0x...>
... yield 4
>>> [i for i in nums]
... print("-- finished --")
[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 created when the >>> next(gen)
generator expression is enclosed in curly braces. A dict is created when the generator expression contains -- middle --
“pairs” of the form key:value: 4
>>> next(gen)
>>> {i for i in range(3)} -- finished --
set([0, 1, 2]) Traceback (most recent call last):
>>> {i:i**2 for i in range(3)} ...
{0: 0, 1: 1, 2: 4} StopIteration
One gotcha should be mentioned: in old Pythons the index variable (i) would leak, and in versions >= 3 this is Contrary to a normal function, where executing f() would immediately cause the first print to be executed,
fixed. gen is assigned without executing any statements in the function body. Only when gen.next() is invoked by
next, the statements up to the first yield are executed. The second next prints -- middle -- and execution
halts on the second yield. The third next prints -- finished -- and falls of the end of the function. Since
7.1.3 Generators no yield was reached, an exception is raised.
What happens with the function after a yield, when the control passes to the caller? The state of each generator
Generators is stored in the generator object. From the point of view of the generator function, is looks almost as if it was
running in a separate thread, but this is just an illusion: execution is strictly single-threaded, but the interpreter
A generator is a function that produces a sequence of results instead of a single value. keeps and restores the state in between the requests for the next value.
David Beazley — A Curious Course on Coroutines and Concurrency Why are generators useful? As noted in the parts about iterators, a generator function is just a different way to
create an iterator object. Everything that can be done with yield statements, could also be done with next
methods. Nevertheless, using a function and having the interpreter perform its magic to create an iterator
A third way to create iterator objects is to call a generator function. A generator is a function containing the
has advantages. A function can be much shorter than the definition of a class with the required next and
keyword yield. It must be noted that the mere presence of this keyword completely changes the nature of the
__iter__ methods. What is more important, it is easier for the author of the generator to understand the state
function: this yield statement doesn’t have to be invoked, or even reachable, but causes the function to be
which is kept in local variables, as opposed to instance attributes, which have to be used to pass data between
marked as a generator. When a normal function is called, the instructions contained in the body start to be
consecutive invocations of next on an iterator object.
executed. When a generator is called, the execution stops before the first instruction in the body. An invocation
A broader question is why are iterators useful? When an iterator is used to power a loop, the loop becomes very
7.1. Iterators, generator expressions and generators 266 7.1. Iterators, generator expressions and generators 267
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
simple. The code to initialise the state, to decide if the loop is finished, and to find the next value is extracted
1
into a separate place. This highlights the body of the loop — the interesting part. In addition, it is possible to >>> it.throw(IndexError)
reuse the iterator code in other places. --yield raised IndexError()--
--yielding 2--
2
7.1.4 Bidirectional communication >>> it.close()
--closing--
Each yield statement causes a value to be passed to the caller. This is the reason for the introduction of
generators by PEP 255 (implemented in Python 2.2). But communication in the reverse direction is also useful.
One obvious way would be some external state, either a global variable or a shared mutable object. Direct next or __next__?
communication is possible thanks to PEP 342 (implemented in 2.5). It is achieved by turning the previously
boring yield statement into an expression. When the generator resumes execution after a yield statement, In Python 2.x, the iterator method to retrieve the next value is called next. It is invoked implicitly through
the caller can call a method on the generator object to either pass a value into the generator, which then is the global function next, which means that it should be called __next__. Just like the global function iter
returned by the yield statement, or a different method to inject an exception into the generator. calls __iter__. This inconsistency is corrected in Python 3.x, where it.next becomes it.__next__. For
other generator methods — send and throw — the situation is more complicated, because they are not
The first of the new methods is send(value), which is similar to next(), but passes value into the generator
called implicitly by the interpreter. Nevertheless, there’s a proposed syntax extension to allow continue
to be used for the value of the yield expression. In fact, g.next() and g.send(None) are equivalent.
to take an argument which will be passed to send of the loop’s iterator. If this extension is accepted, it’s
The second of the new methods is throw(type, value=None, traceback=None) which is equivalent to: likely that gen.send will become gen.__send__. The last of generator methods, close, is pretty obviously
named incorrectly, because it is already invoked implicitly.
raise type, value, traceback
For completeness’ sake, it’s worth mentioning that generator iterators also have a close() method, which can subgen = some_other_generator()
be used to force a generator that would otherwise be able to provide more values to finish immediately. It for v in subgen:
allows the generator __del__ method to destroy objects holding the state of generator. yield v
Let’s define a generator which just prints what is passed in through send and throw. However, if the subgenerator is to interact properly with the caller in the case of calls to send(), throw()
and close(), things become considerably more difficult. The yield statement has to be guarded by a
>>> import itertools
>>> def g(): try..except..finally structure similar to the one defined in the previous section to “debug” the generator func-
... print('--start--') tion. Such code is provided in PEP 380#id13, here it suffices to say that new syntax to properly yield from a
... for i in itertools.count(): subgenerator is being introduced in Python 3.3:
... print('--yielding %i --' % i)
... try: yield from some_other_generator()
... ans = yield i
... except GeneratorExit: This behaves like the explicit loop above, repeatedly yielding values from some_other_generator until it is
... print('--closing--') exhausted, but also forwards send, throw and close to the subgenerator.
... raise
... except Exception as e:
...
...
print('--yield raised %r --' % e)
else:
7.2 Decorators
... print('--yield returned %s --' % ans)
7.1. Iterators, generator expressions and generators 268 7.2. Decorators 269
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Since functions and classes are objects, they can be passed around. Since they are mutable objects, they can 7.2.2 Decorators implemented as classes and as functions
be modified. The act of altering a function or class object after it has been constructed but before is is bound
to its name is called decorating. The only requirement on decorators is that they can be called with a single argument. This means that deco-
rators can be implemented as normal functions, or as classes with a __call__ method, or in theory, even as
There are two things hiding behind the name “decorator” — one is the function which does the work of deco-
lambda functions.
rating, i.e. performs the real work, and the other one is the expression adhering to the decorator syntax, i.e. an
at-symbol and the name of the decorating function. Let’s compare the function and class approaches. The decorator expression (the part after @) can be either just
a name, or a call. The bare-name approach is nice (less to type, looks cleaner, etc.), but is only possible when
Function can be decorated by using the decorator syntax for functions:
no arguments are needed to customise the decorator. Decorators written as functions can be used in those
@decorator # · two cases:
def function(): # ¶
pass >>> def simple_decorator(function):
... print("doing decoration")
... return function
• A function is defined in the standard way. ¶
>>> @simple_decorator
• An expression starting with @ placed before the function definition is the decorator ·. The part after @ ... def function():
must be a simple expression, usually this is just the name of a function or class. This part is evaluated ... print("inside function")
first, and after the function defined below is ready, the decorator is called with the newly defined function doing decoration
>>> function()
object as the single argument. The value returned by the decorator is attached to the original name of
inside function
the function.
Decorators can be applied to functions and to classes. For classes the semantics are identical — the original >>> def decorator_with_arguments(arg):
class definition is used as an argument to call the decorator and whatever is returned is assigned under the ... print("defining the decorator")
original name. ... def _decorator(function):
... # in this inner function, arg is available too
Before the decorator syntax was implemented (PEP 318), it was possible to achieve the same effect by assign- ... print("doing decoration, %r " % arg)
ing the function or class object to a temporary variable and then invoking the decorator explicitly and then ... return function
assigning the return value to the name of the function. This sounds like more typing, and it is, and also the ... return _decorator
name of the decorated function doubling as a temporary variable must be used at least three times, which is >>> @decorator_with_arguments("abc")
prone to errors. Nevertheless, the example above is equivalent to: ... def function():
... print("inside function")
def function(): # ¶ defining the decorator
pass doing decoration, 'abc'
function = decorator(function) # · >>> function()
inside function
Decorators can be stacked — the order of application is bottom-to-top, or inside-out. The semantics are such
that the originally defined function is used as an argument for the first decorator, whatever is returned by The two trivial decorators above fall into the category of decorators which return the original function. If they
the first decorator is used as an argument for the second decorator, . . . , and whatever is returned by the last were to return a new function, an extra level of nestedness would be required. In the worst case, three levels of
decorator is attached under the name of the original function. nested functions.
The decorator syntax was chosen for its readability. Since the decorator is specified before the header of the >>> def replacing_decorator_with_args(arg):
function, it is obvious that its is not a part of the function body and its clear that it can only operate on the ... print("defining the decorator")
whole function. Because the expression is prefixed with @ is stands out and is hard to miss (“in your face”, ... def _decorator(function):
according to the PEP :) ). When more than one decorator is applied, each one is placed on a separate line in an ... # in this inner function, arg is available too
... print("doing decoration, %r " % arg)
easy to read way.
... def _wrapper(*args, **kwargs):
... print("inside wrapper, %r %r " % (args, kwargs))
... return function(*args, **kwargs)
7.2.1 Replacing or tweaking the original object ... return _wrapper
... return _decorator
Decorators can either return the same function or class object or they can return a completely different ob- >>> @replacing_decorator_with_args("abc")
ject. In the first case, the decorator can exploit the fact that function and class objects are mutable and add ... def function(*args, **kwargs):
attributes, e.g. add a docstring to a class. A decorator might do something useful even without modifying ... print("inside function, %r %r " % (args, kwargs))
the object, for example register the decorated class in a global registry. In the second case, virtually anything is ... return 14
possible: when something different is substituted for the original function or class, the new object can be com- defining the decorator
pletely different. Nevertheless, such behaviour is not the purpose of decorators: they are intended to tweak doing decoration, 'abc'
the decorated object, not do something unpredictable. Therefore, when a function is “decorated” by replacing >>> function(11, 12)
inside wrapper, (11, 12) {}
it with a different function, the new function usually calls the original function, after doing some preparatory
inside function, (11, 12) {}
work. Likewise, when a class is “decorated” by replacing if with a new class, the new class is usually derived
14
from the original class. When the purpose of the decorator is to do something “every time”, like to log every call
to a decorated function, only the second type of decorators can be used. On the other hand, if the first type is
The _wrapper function is defined to accept all positional and keyword arguments. In general we cannot know
sufficient, it is better to use it, because it is simpler.
what arguments the decorated function is supposed to accept, so the wrapper function just passes everything
to the wrapped function. One unfortunate consequence is that the apparent argument list is misleading. 7.2.3 Copying the docstring and other attributes of the original function
Compared to decorators defined as functions, complex decorators defined as classes are simpler. When an
When a new function is returned by the decorator to replace the original function, an unfortunate conse-
object is created, the __init__ method is only allowed to return None, and the type of the created object
quence is that the original function name, the original docstring, the original argument list are lost. Those
cannot be changed. This means that when a decorator is defined as a class, it doesn’t make much sense to use
attributes of the original function can partially be “transplanted” to the new function by setting __doc__ (the
the argument-less form: the final decorated object would just be an instance of the decorating class, returned
docstring), __module__ and __name__ (the full name of the function), and __annotations__ (extra informa-
by the constructor call, which is not very useful. Therefore it’s enough to discuss class-based decorators where
tion about arguments and the return value of the function available in Python 3). This can be done automati-
arguments are given in the decorator expression and the decorator __init__ method is used for decorator
cally by using functools.update_wrapper.
construction.
return self._wrapper
7.2.7 A plugin registration system
def _wrapper(self, *args, **kwargs):
self.count += 1 This is a class decorator which doesn’t modify the class, but just puts it in a global registry. It falls into the
if self.count == 1: category of decorators returning the original object:
print self.func.__name__, 'is deprecated'
return self.func(*args, **kwargs) class WordProcessor(object):
PLUGINS = []
def process(self, text):
It can also be implemented as a function:
for plugin in self.PLUGINS:
def deprecated(func): text = plugin().cleanup(text)
"""Print a deprecation warning once on first use of the function. return text
Let’s say we have function which returns a lists of things, and this list created by running a loop. If we don’t See also:
know how many objects will be needed, the standard way to do this is something like: More examples and reading
def find_answers(): • PEP 318 (function and method decorator syntax)
answers = []
while True: • PEP 3129 (class decorator syntax)
ans = look_for_next_answer() • http://wiki.python.org/moin/PythonDecoratorLibrary
if ans is None:
break • https://docs.python.org/dev/library/functools.html
answers.append(ans)
• http://pypi.python.org/pypi/decorator
return answers
• Bruce Eckel
This is fine, as long as the body of the loop is fairly compact. Once it becomes more complicated, as often
– Decorators I: Introduction to Python Decorators
happens in real code, this becomes pretty unreadable. We could simplify this by using yield statements, but
then the user would have to explicitly call list(find_answers()). – Python Decorators II: Decorator Arguments
We can define a decorator which constructs the list for us: – Python Decorators III: A Decorator-Based Build System
def vectorized(generator_func):
def wrapper(*args, **kwargs):
return list(generator_func(*args, **kwargs)) 7.3 Context managers
return functools.update_wrapper(wrapper, generator_func)
A context manager is an object with __enter__ and __exit__ methods which can be used in the with state-
Our function then becomes: ment:
@vectorized with manager as var:
def find_answers(): do_something(var)
while True:
ans = look_for_next_answer()
is in the simplest case equivalent to
if ans is None:
break
yield ans
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 success-
fully to the end, or it can break, continue‘ or return, or it can throw an exception. Either way, after the When an exception is thrown in the with-block, it is passed as arguments to __exit__. Three arguments are
block is finished, the __exit__ method is called. If an exception was thrown, the information about the used, the same as returned by sys.exc_info(): type, value, traceback. When no exception is thrown, None is
exception is passed to __exit__, which is described below in the next subsection. In the normal case, used for all three arguments. The context manager can “swallow” the exception by returning a true value from
exceptions can be ignored, just like in a finally clause, and will be rethrown after __exit__ is finished. __exit__. Exceptions can be easily ignored, because if __exit__ doesn’t use return and just falls of the end,
None is returned, a false value, and therefore the exception is rethrown after __exit__ is finished.
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
>>> class closing(object): want to make sure that some code throws the right kind of exception:
... def __init__(self, obj):
... self.obj = obj class assert_raises(object):
... def __enter__(self): # based on pytest and unittest.TestCase
... return self.obj def __init__(self, type):
... def __exit__(self, *args): self.type = type
... self.obj.close() def __enter__(self):
>>> with closing(open('/tmp/file', 'w')) as f: pass
... f.write('the contents\n') def __exit__(self, type, value, traceback):
if type is None:
Here we have made sure that the f.close() is called when the with block is exited. Since closing files is such raise AssertionError('exception expected')
if issubclass(type, self.type):
a common operation, the support for this is already present in the file class. It has an __exit__ method
return True # swallow the expected exception
which calls close and can be used as a context manager itself:
raise AssertionError('wrong exception type')
>>> with open('/tmp/file', 'a') as f:
... f.write('more contents\n') with assert_raises(KeyError):
{}['foo']
The common use for try..finally is releasing resources. Various different cases are implemented similarly:
in the __enter__ phase the resource is acquired, in the __exit__ phase it is released, and the exception, if
thrown, is propagated. As with files, there’s often a natural operation to perform after the object has been used 7.3.2 Using generators to define context managers
and it is most convenient to have the support built in. With each release, Python provides support in more
places: When discussing generators, it was said that we prefer generators to iterators implemented as classes because
they are shorter, sweeter, and the state is stored as local, not instance, variables. On the other hand, as de-
• all file-like objects:
scribed in Bidirectional communication, the flow of data between the generator and its caller can be bidirec-
– file å automatically closed tional. This includes exceptions, which can be thrown into the generator. We would like to implement context
managers as special generator functions. In fact, the generator protocol was designed to support this use case.
– fileinput, tempfile (py >= 3.2)
@contextlib.contextmanager
– bz2.BZ2File, gzip.GzipFile, tarfile.TarFile, zipfile.ZipFile
def some_generator(<arguments>):
– ftplib, nntplib å close connection (py >= 3.2 or 3.3) <setup>
try:
• locks yield <value>
– multiprocessing.RLock å lock and unlock finally:
<cleanup>
– multiprocessing.Semaphore
– memoryview å automatically release (py >= 3.2 and 2.7) The contextlib.contextmanager helper takes a generator and turns it into a context manager. The gener-
ator has to obey some rules which are enforced by the wrapper function — most importantly it must yield
• decimal.localcontext å modify precision of computations temporarily exactly once. The part before the yield is executed from __enter__, the block of code protected by the con-
• _winreg.PyHKEY å open and close hive key text 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 wrap-
• warnings.catch_warnings å kill warnings temporarily per function then throws it at the point of the yield statement. Through the use of generators, the context
manager is shorter and simpler.
@contextlib.contextmanager
def closing(obj):
try:
yield obj
8
finally:
obj.close()
@contextlib.contextmanager
def assert_raises(type):
try:
CHAPTER
yield
except type:
return
except Exception as value:
raise AssertionError('wrong exception type')
else:
raise AssertionError('exception expected')
Prerequisites
• NumPy
• Cython
• Pillow (Python imaging library, used in a couple of examples)
Chapter contents
• Life of ndarray
– It’s. . .
– Data types
– Indexing scheme: strides
– Findings in dissection
• Universal functions
– What they are?
– Exercise: building an ufunc from scratch
– Solution: building an ufunc from scratch
– Generalized ufuncs
• Interoperability features
– Sharing multidimensional, typed data
typedef struct PyArrayObject {
– The old buffer protocol PyObject_HEAD
– The old buffer protocol
/* Block of memory */
– Array interface protocol char *data;
>>> x.__array_interface__['data'][0]
64803824
8.1 Life of ndarray
The whole __array_interface__:
Example: reading .wav files • The first element is the sub-dtype in the structured data, corresponding to the name format
The .wav file header: • The second one is its offset (in bytes) from the beginning of the item
where the last three dimensions are the R, B, and G, and alpha channels. The answer (in NumPy)
How to make a (10, 10) structured array with field names ‘r’, ‘g’, ‘b’, ‘a’ without copying data? • strides: the number of bytes to jump to find the next element
>>> x.strides
>>> assert (y['r'] == 1).all()
(3, 1)
>>> assert (y['g'] == 2).all()
>>> byte_offset = 3*1 + 1*2 # to find x[1, 2]
>>> assert (y['b'] == 3).all()
>>> x.flat[byte_offset]
>>> assert (y['a'] == 4).all()
6
>>> x[1, 2]
Solution 6
>>> y = x.view([('r', 'i1'),
- simple, **flexible**
... ('g', 'i1'),
... ('b', 'i1'),
... ('a', 'i1')]
... )[:, :, 0] C and Fortran order
• Need to jump 2 bytes to find the next row • Similarly, transposes never make copies (it just swaps strides):
• Need to jump 4 bytes to find the next column
>>> x = np.zeros((10, 10, 10), dtype=np.float)
• Similarly to higher dimensions: >>> x.strides
(800, 80, 8)
– C: last dimensions vary fastest (= smaller strides) >>> x.T.strides
(8, 80, 800)
– F: first dimensions vary fastest
shape = (d 1 , d 2 , ..., d n ) But: not all reshaping operations can be represented by playing with strides:
strides = (s 1 , s 2 , ..., s n )
>>> a = np.arange(6, dtype=np.int8).reshape(3, 2)
s Cj = d j +1 d j +2 ...d n × itemsize >>> b = a.T
>>> b.strides
s Fj = d 1 d 2 ...d j −1 × itemsize (1, 2)
Note: Now we can understand the behavior of .view(): So far, so good. However:
Stride manipulation
• the results are different when interpreted as 2 of int16
• .copy() creates new arrays in the C order (by default)
>>> from numpy.lib.stride_tricks import as_strided
>>> help(as_strided)
as_strided(x, shape=None, strides=None)
Make an ndarray from the given array with the given shape and strides
Slicing with integers
• Everything can be represented by changing only shape, strides, and possibly adjusting the data
Warning: as_strided does not check that you stay inside the memory block bounds. . .
pointer!
• Never makes copies of the data
>>> x = np.array([1, 2, 3, 4], dtype=np.int16)
>>> x = np.array([1, 2, 3, 4, 5, 6], dtype=np.int32) >>> as_strided(x, strides=(2*2, ), shape=(2, ))
>>> y = x[::-1] array([1, 3], dtype=int16)
>>> y >>> x[::2]
array([6, 5, 4, 3, 2, 1], dtype=int32) array([1, 3], dtype=int16)
See also:
. . . seems somehow familiar . . .
stride-diagonals.py
plt.imshow(abs(z)**2 < 1000, extent=[-1.7, 0.6, -1.4, 1.4]) 2, # number of input args
plt.gray() 1, # number of output args
plt.show() 0, # `identity` element, never mind this
"mandel", # function name
"mandel(z, c) -> computes iterated z*z + c", # docstring
0 # unused
)
ufunc
output = elementwise_function(input)
Both output and input can be a single array element only.
generalized ufunc
output and input can be arrays with a fixed number of dimensions
For example, matrix trace (sum of diag elements):
Note: Most of the boilerplate could be automated by these Cython modules:
input shape = (n, n)
http://wiki.cython.org/MarkLodato/CreatingUfuncs output shape = () i.e. scalar
(n, n) -> ()
void gufunc_loop(void **args, int *dimensions, int *steps, void *data) >>> from PIL import Image
{ >>> data = np.zeros((200, 200, 4), dtype=np.int8)
char *input_1 = (char*)args[0]; /* these are as previously */ >>> data[:, :] = [255, 0, 0, 255] # Red
char *input_2 = (char*)args[1]; >>> # In PIL, RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA]
char *output = (char*)args[2]; >>> data = data.view(np.int32).squeeze()
>>> img = Image.frombuffer("RGBA", (200, 200), data, "raw", "RGBA", 0, 1)
int input_1_stride_m = steps[3]; /* strides for the core dimensions */ >>> img.save('test.png')
int input_1_stride_n = steps[4]; /* are added after the non-core */
int input_2_strides_n = steps[5]; /* steps */ Q:
int input_2_strides_p = steps[6];
Check what happens if data is now modified, and img saved again.
int output_strides_n = steps[7];
int output_strides_p = steps[8];
for (i = 0; i < dimensions[0]; ++i) { Show how to exchange data between numpy and a library that only knows
matmul_for_strided_matrices(input_1, input_2, output, the buffer interface.
strides for each array...); """
Note: .view() has a second meaning: it can make an ndarray an instance of a specialized ndarray subclass
Masked arrays are arrays that may have missing or invalid entries.
8.3.4 Array interface protocol For example, suppose we have an array where the fourth entry is invalid:
• NumPy-specific approach; slowly deprecated (but not going away) >>> mx = np.ma.masked_array(x, mask=[0, 0, 0, 1, 0])
>>> mx
• Not integrated in Python otherwise masked_array(data = [1 2 3 -- 5],
See also: mask = [False False False True False],
fill_value = 999999)
Documentation: http://docs.scipy.org/doc/numpy/reference/arrays.interface.html
Masked mean ignores masked data:
>>> x = np.array([[1, 2], [3, 4]])
>>> x.__array_interface__ >>> mx.mean()
{'data': (171694552, False), # memory address of data, is readonly? 2.75
'descr': [('', '<i4')], # data type descriptor >>> np.mean(mx)
'typestr': '<i4', # same, in another form 2.75
'strides': None, # strides; or None if in C-order
'shape': (2, 2),
'version': 3,
} Warning: Not all NumPy functions respect masks, for instance np.dot, so check the return types.
::
The masked_array returns a view to the original array:
8.3. Interoperability features 306 8.4. Array siblings: chararray, maskedarray, matrix 307
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> mx[1] = np.ma.masked >>> bad_years = (((year >= 1903) & (year <= 1910))
>>> mx ... | ((year >= 1917) & (year <= 1918)))
masked_array(data = [1 -- 3 -- 5], >>> # '&' means 'and' and '|' means 'or'
mask = [False True False True False], >>> populations[bad_years, 0] = np.ma.masked
fill_value = 999999) >>> populations[bad_years, 1] = np.ma.masked
>>> x2 = mx.filled(-1)
>>> x2
array([ 1, 9, 3, -1, 5])
Domain-aware functions
8.4. Array siblings: chararray, maskedarray, matrix 308 8.4. Array siblings: chararray, maskedarray, matrix 309
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> print(np.__version__)
• “There’s a bug?” 1...
• “I don’t understand what this is supposed to do?”
Check that the following is what you expect
• “I have this fancy code. Would you like to have it?”
>>> print(np.__file__)
• “I’d like to help! What can I do?” /...
Good bug report – Problem with mailing lists: you get mail
When calling numpy.random.permutation with non-integer arguments – Send a mail @ scipy-dev mailing list; ask for activation:
<edit stuff>
git commit -a
9
9.1 Avoiding bugs
“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?”
Author: Gaël Varoquaux • Try to limit interdependencies of your code. (Loose Coupling)
This section explores tools to understand better your code base: debugging, to find and fix bugs. • Give your variables, functions and modules meaningful names (not mathematics names)
It is not specific to the scientific Python community, but the strategies that we will employ are tailored to its
needs. 9.1.2 pyflakes: fast static analysis
• Using the Python debugger You can bind a key to run pyflakes in the current buffer.
– Invoking the debugger • In kate Menu: ‘settings -> configure kate
• In TextMate
Menu: TextMate -> Preferences -> Advanced -> Shell variables, add a shell variable:
TM_PYCHECKER = /Library/Frameworks/Python.framework/Versions/Current/bin/pyflakes
(add-hook 'python-mode-hook (lambda () (pyflakes-mode t))) For debugging a given problem, the favorable situation is when the problem is isolated in a
small number of lines of code, outside framework or application code, with short modify-run-
fail cycles
A type-as-go spell-checker like integration 1. Make it fail reliably. Find a test case that makes the code fail every time.
2. Divide and Conquer. Once you have a failing test case, isolate the failing code.
• In vim
• Which module.
– Use the pyflakes.vim plugin:
• Which function.
1. download the zip file from http://www.vim.org/scripts/script.php?script_id=2441
• Which line of code.
2. extract the files in ~/.vim/ftplugin/python
=> isolate a small reproducible failure: a test case
3. make sure your vimrc has filetype plugin indent on
3. Change one thing at a time and re-run the failing test case.
4. Use the debugger to understand what is going wrong.
5. Take notes and be patient. It may take a while.
Note: Once you have gone through this process: isolated a tight piece of code reproducing the bug and fix the
bug using this piece of code, add the corresponding code to your test suite.
– Alternatively: use the syntastic plugin. This can be configured to use flake8 too and also handles
on-the-fly checking for many other languages.
ipdb> list
The python debugger, pdb: https://docs.python.org/library/pdb.html, allows you to inspect your code inter-
1 """Small snippet to raise an IndexError."""
actively.
2
Specifically it allows you to: 3 def index_error():
4 lst = list('foobar')
• View the source code. ----> 5 print lst[len(lst)]
6
• Walk up and down the call stack.
7 if __name__ == '__main__':
• Inspect values of variables. 8 index_error()
9
• Modify values of variables.
• Set breakpoints. ipdb> len(lst)
6
ipdb> print lst[len(lst)-1]
print r
ipdb> quit
Yes, print statements do work as a debugging tool. However to inspect runtime, it is often more efficient to
use the debugger. In [3]:
9.3. Using the Python debugger 318 9.3. Using the Python debugger 319
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• Step into code with n(ext) and s(tep): next jumps to the next statement in the current execution 55 pl.matshow(noisy_face[cut], cmap=pl.cm.gray)
context, while step will go across execution contexts, i.e. enable exploring inside function calls: 56
---> 57 denoised_face = iterated_wiener(noisy_face)
ipdb> s 58 pl.matshow(denoised_face[cut], cmap=pl.cm.gray)
> /home/varoquau/dev/scipy-lecture-notes/advanced/optimizing/wiener_filtering. 59
,→py(35)iterated_wiener()
2 34 noisy_img = noisy_img /home/esc/physique-cuso-python-2013/scipy-lecture-notes/advanced/debugging/wiener_filtering.
---> 35 denoised_img = local_mean(noisy_img, size=size) ,→py in iterated_wiener(noisy_img, size)
9.3. Using the Python debugger 320 9.3. Using the Python debugger 321
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Warning: When running nosetests, the output is captured, and thus it seems that the debugger does not
work. Simply run the nosetests with the -s flag.
9.4 Debugging segmentation faults using gdb
If you have a segmentation fault, you cannot debug it with pdb, as it crashes the Python interpreter before it
Graphical debuggers and alternatives can drop in the debugger. Similarly, if you have a bug in C code embedded in Python, pdb is useless. For this
we turn to the gnu debugger, gdb, available on Linux.
• For stepping through code and inspecting variables, you might find it more convenient to use a graph- Before we start with gdb, let us add a few Python-specific tools to it. For this we add a few macros to our ~/.
ical debugger such as winpdb. gdbinit. The optimal choice of macro depends on your Python version and your gdb version. I have added a
• Alternatively, pudb is a good semi-graphical debugger with a text user interface in the console. simplified version in gdbinit, but feel free to read DebuggingWithGdb.
• Also, the pydbgr project is probably worth looking at. To debug with gdb the Python script segfault.py, we can run the script in gdb as follows
$ gdb python
...
(gdb) run segfault.py
9.3.2 Debugger commands and interaction Starting program: /usr/bin/python segfault.py
[Thread debugging using libthread_db enabled]
l(list) Lists the code at the current position Program received signal SIGSEGV, Segmentation fault.
u(p) Walk up the call stack _strided_byte_copy (dst=0x8537478 "\360\343G", outstrides=4, src=
d(own) Walk down the call stack 0x86c0690 <Address 0x86c0690 out of bounds>, instrides=32, N=3,
n(ext) Execute the next line (does not go down in new functions) elsize=4)
s(tep) Execute the next statement (goes down in new functions) at numpy/core/src/multiarray/ctors.c:365
bt Print the call stack 365 _FAST_MOVE(Int32);
a Print the local variables (gdb)
!command Execute the given Python command (by opposition to pdb commands
We get a segfault, and gdb captures it for post-mortem debugging in the C level stack (not the Python call
stack). We can debug the C call stack using gdb’s commands:
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
Getting help when in the debugger
triggers this segfault, so we go up the stack until we hit the Python execution loop:
Type h or help to access the interactive help: (gdb) up
#8 0x080ddd23 in call_function (f=
ipdb> help Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/
,→arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote 0x85371b0>, _nc=
Documented commands (type help <topic>): ,→<module at remote 0xb7f93a64>), throwflag=0)
======================================== at ../Python/ceval.c:3750
EOF bt cont enable jump pdef r tbreak w 3750 ../Python/ceval.c: No such file or directory.
a c continue exit l pdoc restart u whatis in ../Python/ceval.c
alias cl d h list pinfo return unalias where
args clear debug help n pp run unt (gdb) up
b commands disable ignore next q s until #9 PyEval_EvalFrameEx (f=
break condition down j p quit step up Frame 0x85371ec, for file /home/varoquau/usr/lib/python2.6/site-packages/numpy/core/
,→arrayprint.py, line 156, in _leading_trailing (a=<numpy.ndarray at remote 0x85371b0>, _nc=
Miscellaneous help topics: ,→<module at remote 0xb7f93a64>), throwflag=0)
========================== at ../Python/ceval.c:2412
exec pdb
9.3. Using the Python debugger 322 9.4. Debugging segmentation faults using gdb 323
Scipy lecture notes, Edition 2017.1
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:
10
(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:
CHAPTER
(gdb) up
...
(gdb) up
#34 0x080dc97a in PyEval_EvalFrameEx (f=
Frame 0x82f064c, for file segfault.py, line 11, in print_big_array (small_array=<numpy.
,→ndarray at remote 0x853ecf0>, big_array=<numpy.ndarray at remote 0x853ed20>), throwflag=0)␣
,→at ../Python/ceval.c:1630
1630 ../Python/ceval.c: No such file or directory.
Optimizing code
in ../Python/ceval.c
(gdb) pyframe
segfault.py (12): print_big_array
def make_big_array(small_array):
big_array = stride_tricks.as_strided(small_array,
shape=(2e6, 2e6), strides=(32, 32))
return big_array
Prerequisites
• line_profiler
Wrap up exercise
The following script is well documented and hopefully legible. It seeks to answer a problem of actual interest
for numerical computing, but it does not work. . . Can you debug it? Chapters contents
def test():
10.1 Optimization workflow data = np.random.random((5000, 100))
u, s, v = linalg.svd(data)
pca = np.dot(u[:, :10].T, data)
1. Make it work: write the code in a simple legible ways.
results = fastica(pca.T, whiten=False)
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. if __name__ == '__main__':
test()
3. Optimize the code by profiling simple use-cases to find the bottlenecks and speeding up these bottle-
neck, finding a better algorithm or implementation. Keep in mind that a trade off should be found be-
tween profiling on a realistic example and the simplicity and speed of execution of the code. For efficient Note: This is a combination of two unsupervised learning techniques, principal component analysis (PCA)
work, it is best to work with profiling runs lasting around 10s. 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 seperation technique,
for example to unmix multiple signals that have been recorded through multiple sensors. Doing a PCA first
10.2 Profiling Python code and then an ICA can be useful if you have more sensors than signals. For more information see: the FastICA
example from scikits-learn.
No optimization without measuring! To run it, you also need to download the ica module. In IPython we can time the script:
• You’ll have surprises: the fastest code is not always what you think IPython CPU timings (estimated):
User : 14.3929 s.
System: 0.256016 s.
In IPython, use timeit (https://docs.python.org/library/timeit.html) to time elementary operations: In [2]: %run -p demo.py
The profiler tells us which function takes most of the time, but not where it is called. In [5]: %timeit linalg.svd(data)
1 loops, best of 3: 14.2 s per loop
For this, we use the line_profiler: in the source file, we decorate a few functions that we want to inspect with
@profile (no need to import it)
In [6]: %timeit linalg.svd(data, full_matrices=False)
@profile 1 loops, best of 3: 295 ms per loop
def test():
data = np.random.random((5000, 100)) In [7]: %timeit np.linalg.svd(data, full_matrices=False)
u, s, v = linalg.svd(data) 1 loops, best of 3: 293 ms per loop
pca = np.dot(u[:, :10], data)
results = fastica(pca.T, whiten=False) We can then use this insight to optimize the previous code:
def test():
Then we run the script using the kernprof.py program, with switches -l, --line-by-line and -v, --view
data = np.random.random((5000, 100))
to use the line-by-line profiler and view the results in addition to saving them:
u, s, v = linalg.svd(data, full_matrices=False)
$ kernprof.py -l -v demo.py pca = np.dot(u[:, :10].T, data)
results = fastica(pca.T, whiten=False)
Wrote profile results to demo.py.lprof
Timer unit: 1e-06 s In [1]: import demo
Line # Hits Time Per Hit % Time Line Contents In [2]: %timeit demo.test()
=========== ============ ===== ========= ======= ==== ======== ica.py:65: RuntimeWarning: invalid value encountered in sqrt
5 @profile W = (u * np.diag(1.0/np.sqrt(s)) * u.T) * W # W = (W * W.T) ^{-1/2} * W
6 def test(): 1 loops, best of 3: 17.5 s per loop
7 1 19015 19015.0 0.1 data = np.random.random((5000, 100))
8 1 14242163 14242163.0 99.7 u, s, v = linalg.svd(data) In [3]: import demo_opt
9 1 10282 10282.0 0.1 pca = np.dot(u[:10, :], data)
10 1 7799 7799.0 0.1 results = fastica(pca.T, whiten=False) In [4]: %timeit demo_opt.test()
1 loops, best of 3: 208 ms per loop
The SVD is taking all the time. We need to optimise this line.
Real incomplete SVDs, e.g. computing only the first 10 eigenvectors, can be computed with arpack, available
in scipy.sparse.linalg.eigsh.
10.3 Making code go faster
Once we have identified the bottlenecks, we need to make the corresponding code go faster.
10.3. Making code go faster 328 10.3. Making code go faster 329
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
A complete discussion on advanced use of numpy is found in chapter Advanced NumPy, or in the article The In [9]: %timeit np.dot(b, c)
NumPy array: a structure for efficient numerical computation by van der Walt et al. Here we discuss only some 10 loops, best of 3: 84.2 ms per loop
commonly encountered tricks to make code faster.
Note that copying the data to work around this effect may not be worth it:
• Vectorizing for loops
In [10]: %timeit c = np.ascontiguousarray(a.T)
Find tricks to avoid for loops using numpy arrays. For this, masks and indices arrays can be useful.
10 loops, best of 3: 106 ms per loop
• Broadcasting
Using numexpr can be useful to automatically optimize code for such effects.
Use broadcasting to do operations on arrays as small as possible before combining them.
• Use compiled code
• In place operations
The last resort, once you are sure that all the high-level optimizations have been explored, is to transfer
In [1]: a = np.zeros(1e7) 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
In [2]: %timeit global a ; a = 0*a
compiled code, and with a good use of the numpy support yields efficient code on numpy arrays, for
10 loops, best of 3: 111 ms per loop
instance by unrolling loops.
In [3]: %timeit global a ; a *= 0
10 loops, best of 3: 48.4 ms per loop
Warning: For all the above: profile and time your choices. Don’t base your optimization on theoretical
considerations.
note: we need global a in the timeit so that it work, as it is assigning to a, and thus considers it as a local
variable.
• Be easy on the memory: use views, and not copies
10.4.1 Additional Links
Copying big arrays is as costly as making simple numerical operations on them:
• If you need to profile memory usage, you could try the memory_profiler
In [1]: a = np.zeros(1e7)
• If you need to profile down into C extensions, you could try using gperftools from Python with yep.
In [2]: %timeit a.copy()
• If you would like to track performace of your code across time, i.e. as you make new commits to your
10 loops, best of 3: 124 ms per loop
repository, you could try: vbench
In [3]: %timeit a + 1 • If you need some interactive visualization why not try RunSnakeRun
10 loops, best of 3: 112 ms per loop
10.4. Writing faster numerical code 330 10.4. Writing faster numerical code 331
Scipy lecture notes, Edition 2017.1
11
<matplotlib.text.Text object at ...>
11.1.4 Prerequisites
• numpy
* passing a sparse matrix object to NumPy functions expecting ndarray/matrix does not
work
Examples
– facilitates fast conversion among sparse formats * length is n_row + 1, last item = number of values = length of both indices and data
– when converting to other format (usually CSR or CSC), duplicate entries are summed together * nonzero values of the i-th row are data[indptr[i]:indptr[i+1]] with column indices in-
dices[indptr[i]:indptr[i+1]]
* facilitates efficient construction of finite element matrices
* item (i, j) can be accessed as data[indptr[i]+k], where k is position of j in in-
dices[indptr[i]:indptr[i+1]]
Examples – subclass of _cs_matrix (common CSR/CSC functionality)
• create empty COO matrix: * subclass of _data_matrix (sparse matrix classes with .data attribute)
• fast matrix vector products and other arithmetics (sparsetools)
>>> mtx = sparse.coo_matrix((3, 4), dtype=np.int8)
>>> mtx.todense() • constructor accepts:
matrix([[0, 0, 0, 0],
– dense matrix (array)
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8) – sparse matrix
– shape tuple (create empty matrix)
• create using (data, ij) tuple:
– (data, ij) tuple
>>> row = np.array([0, 3, 1, 0])
>>> col = np.array([0, 3, 1, 2]) – (data, indices, indptr) tuple
>>> data = np.array([4, 5, 7, 9])
>>> mtx = sparse.coo_matrix((data, (row, col)), shape=(4, 4)) • efficient row slicing, row-oriented operations
>>> mtx • slow column slicing, expensive changes to the sparsity structure
<4x4 sparse matrix of type '<... 'numpy.int64'>'
with 4 stored elements in COOrdinate format> • use:
>>> mtx.todense()
– actual computations (most linear solvers support this format)
matrix([[4, 0, 9, 0],
[0, 7, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 5]])
* indptr points to column starts in indices and data >>> data = np.array([1, 4, 5, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
* length is n_col + 1, last item = number of values = length of both indices and data >>> indptr = np.array([0, 2, 3, 6])
>>> mtx = sparse.csc_matrix((data, indices, indptr), shape=(3, 3))
* nonzero values of the i-th column are data[indptr[i]:indptr[i+1]] with row indices in-
dices[indptr[i]:indptr[i+1]] >>> mtx.todense()
matrix([[1, 0, 2],
* item (i, j) can be accessed as data[indptr[j]+k], where k is position of i in in- [0, 0, 3],
dices[indptr[j]:indptr[j+1]] [4, 5, 6]])
– a bug?
• create using (data, ij) tuple with (1, 1) block size (like CSR. . . ):
11.3. Linear System Solvers 346 11.3. Linear System Solvers 347
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
M [{sparse matrix, dense matrix, LinearOperator}] Preconditioner for A. The preconditioner should ap-
=======================
proximate the inverse of A. Effective preconditioning dramatically improves the rate of conver-
Construct a 1000x1000 lil_matrix and add some values to it, convert it gence, which implies that fewer iterations are needed to reach a given error tolerance.
to CSR format and solve A x = b for x:and solve a linear system with a callback [function] User-supplied function to call after each iteration. It is called as callback(xk), where
direct solver.
xk is the current solution vector.
"""
import numpy as np
import scipy.sparse as sps LinearOperator Class
from matplotlib import pyplot as plt
from scipy.sparse.linalg.dsolve import linsolve
from scipy.sparse.linalg.interface import LinearOperator
rand = np.random.rand
• common interface for performing matrix vector products
mtx = sps.lil_matrix((1000, 1000), dtype=np.float64)
mtx[0, :100] = rand(100) • useful abstraction that enables using dense and sparse matrices within the solvers, as well as matrix-free
mtx[1, 100:200] = mtx[0, :100] solutions
mtx.setdiag(rand(1000)) • has shape and matvec() (+ some optional parameters)
plt.clf() • example:
plt.spy(mtx, marker='.', markersize=2)
plt.show() >>> import numpy as np
>>> from scipy.sparse.linalg import LinearOperator
mtx = mtx.tocsr() >>> def mv(v):
rhs = rand(1000) ... return np.array([2*v[0], 3*v[1]])
...
x = linsolve.spsolve(mtx, rhs) >>> A = LinearOperator((2, 2), matvec=mv)
>>> A
print('rezidual: %r ' % np.linalg.norm(mtx * x - rhs)) <2x2 _CustomLinearOperator with dtype=float64>
>>> A.matvec(np.ones(2))
array([ 2., 3.])
• examples/direct_solve.py
>>> A * np.ones(2)
array([ 2., 3.])
11.3.2 Iterative Solvers
• the isolve module contains the following solvers: A Few Notes on Preconditioning
Common Parameters • arpack * a collection of Fortran77 subroutines designed to solve large scale eigenvalue problems
• mandatory: • lobpcg (Locally Optimal Block Preconditioned Conjugate Gradient Method) * works very well in combi-
nation with PyAMG * example by Nathan Bell:
A [{sparse matrix, dense matrix, LinearOperator}] The N-by-N matrix of the linear system.
"""
b [{array, matrix}] Right hand side of the linear system. Has shape (N,) or (N,1). Compute eigenvectors and eigenvalues using a preconditioned eigensolver
• optional: ========================================================================
x0 [{array, matrix}] Starting guess for the solution. In this example Smoothed Aggregation (SA) is used to precondition
the LOBPCG eigensolver on a two-dimensional Poisson problem with
tol [float] Relative tolerance to achieve before terminating. Dirichlet boundary conditions.
maxiter [integer] Maximum number of iterations. Iteration will stop after maxiter steps even if the spec- """
ified tolerance has not been achieved.
11.3. Linear System Solvers 348 11.3. Linear System Solvers 349
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import scipy
from scipy.sparse.linalg import lobpcg
N = 100
K = 9
A = poisson((N,N), format='csr')
# preconditioner based on ml
M = ml.aspreconditioner()
pylab.figure(figsize=(9,9))
for i in range(K):
pylab.subplot(3, 3, i+1)
pylab.title('Eigenvector %d ' % i)
pylab.pcolor(V[:,i].reshape(N,N))
pylab.axis('equal')
pylab.axis('off') 11.4 Other Interesting Packages
pylab.show()
• PyAMG
– examples/pyamg_with_lobpcg.py
– algebraic multigrid solvers
• example by Nils Wagner:
– https://github.com/pyamg/pyamg
– examples/lobpcg_sakurai.py
• Pysparse
• output:
– own sparse matrix classes
$ python examples/lobpcg_sakurai.py
Results by LOBPCG for n=2500 – matrix and eigenvalue problem solvers
– http://pysparse.sourceforge.net/
[ 0.06250083 0.06250028 0.06250007]
Exact eigenvalues
11.3. Linear System Solvers 350 11.4. Other Interesting Packages 351
Scipy lecture notes, Edition 2017.1
12
• Classification
• Feature extraction
• Registration
• ...
CHAPTER
Chapters contents
12.1. Opening and writing to image files 354 12.2. Displaying images 355
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
np.histogram
Exercise
12.4.3 Denoising
Noisy face:
Exercise: denoising
• Create a binary image (of 0s and 1s) with several objects (circles, ellipses, squares, or random shapes).
• Add some noise (e.g., 20% of noise)
• Try two different denoising methods for denoising the image: gaussian filtering and median filtering.
• Compare the histograms of the two different denoised images. Which one is the closest to the his-
togram of the original (noise-free) image?
A Gaussian filter smoothes the noise out. . . and the edges as well: 12.4.4 Mathematical morphology
>>> gauss_denoised = ndimage.gaussian_filter(noisy, 2)
See wikipedia for a definition of mathematical morphology.
Most local linear isotropic filters blur the image (ndimage.uniform_filter) Probe an image with a simple shape (a structuring element), and modify this image according to how the
A median filter preserves better the edges: shape locally fits or misses the image.
Structuring element:
>>> med_denoised = ndimage.median_filter(noisy, 3)
>>> el = ndimage.generate_binary_structure(2, 1)
>>> el
array([[False, True, False],
[ True, True, True],
[False, True, False]], dtype=bool)
>>> el.astype(np.int)
array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]])
Erosion = minimum filter. Replace the value of a pixel by the minimal value covered by the structuring ele-
ment.:
>>> np.random.seed(2)
>>> im = np.zeros((64, 64))
>>> x, y = (63*np.random.random((2, 8))).astype(np.int)
>>> im[x, y] = np.arange(8)
Synthetic data:
Exercise
Check that reconstruction operations (erosion + propagation) produce a better result than opening/closing:
>>> eroded_img = ndimage.binary_erosion(binary_img)
12.5.2 Segmentation >>> reconstruct_img = ndimage.binary_propagation(eroded_img, mask=binary_img)
>>> tmp = np.logical_not(reconstruct_img)
• Histogram-based segmentation (no spatial information) >>> eroded_tmp = ndimage.binary_erosion(tmp)
>>> reconstruct_final = np.logical_not(ndimage.binary_propagation(eroded_tmp, mask=tmp))
>>> n = 10 >>> np.abs(mask - close_img).mean()
>>> l = 256 0.00727836...
>>> im = np.zeros((l, l)) >>> np.abs(mask - reconstruct_final).mean()
>>> np.random.seed(1) 0.00059502...
>>> points = l*np.random.random((2, n**2))
>>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
>>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
Exercise
>>> mask = (im > im.mean()).astype(np.float)
>>> mask += 0.1 * im Check how a first denoising step (e.g. with a median filter) modifies the histogram, and check that the
>>> img = mask + 0.2*np.random.randn(*mask.shape) resulting histogram-based segmentation is more accurate.
the spectral clustering function of the scikit-learn in order to segment glued objects.
>>> points = l*np.random.random((2, n**2))
>>> from sklearn.feature_extraction import image >>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
>>> from sklearn.cluster import spectral_clustering >>> im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
>>> mask = im > im.mean()
>>> l = 100
>>> x, y = np.indices((l, l)) • Analysis of connected components
>>> # 4 circles
>>> img = circle1 + circle2 + circle3 + circle4
>>> mask = img.astype(bool)
>>> img = img.astype(float)
>>> labels = spectral_clustering(graph, n_clusters=4, eigen_solver='arpack') >>> sizes = ndimage.sum(mask, label_im, range(nb_labels + 1))
>>> label_im = -np.ones(mask.shape) >>> mean_vals = ndimage.sum(im, label_im, range(1, nb_labels + 1))
>>> label_im[mask] = labels
Clean up small connect components:
12.6. Measuring objects properties: ndimage.measurements 366 12.6. Measuring objects properties: ndimage.measurements 367
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
When regions are regular blocks, it is more efficient to use stride tricks (Example: fake dimensions with strides).
Non-regularly-spaced blocks: radial mean:
• Other measures
Correlation function, Fourier/wavelet spectrum, etc.
One example with mathematical morphology: granulometry
12.6. Measuring objects properties: ndimage.measurements 368 12.6. Measuring objects properties: ndimage.measurements 369
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
12.6. Measuring objects properties: ndimage.measurements 370 12.7. Full code examples 371
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import scipy.misc import scipy
import matplotlib.pyplot as plt import scipy.misc
import matplotlib.pyplot as plt
f = scipy.misc.face(gray=True)
face = scipy.misc.face(gray=True)
plt.figure(figsize=(8, 4)) face[10:13, 20:23]
face[100:120] = 255
plt.subplot(1, 2, 1)
plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray) lx, ly = face.shape
plt.axis('off') X, Y = np.ogrid[0:lx, 0:ly]
mask = (X - lx/2)**2 + (Y - ly/2)**2 > lx*ly/4
plt.subplot(1, 2, 2) face[mask] = 0
plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation='nearest') face[range(400), range(400)] = 255
plt.axis('off')
plt.figure(figsize=(3, 3))
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) plt.axes([0, 0, 1, 1])
plt.show() plt.imshow(face, cmap=plt.cm.gray)
plt.axis('off')
Total running time of the script: ( 0 minutes 0.254 seconds)
plt.show()
Download Python source code: plot_interpolation_face.py
Download Jupyter notebook: plot_interpolation_face.ipynb Total running time of the script: ( 0 minutes 0.171 seconds)
This example shows how to do image manipulation using common numpy arrays tricks.
12.8.4 Radial mean
12.8. Examples for the image processing chapter 372 12.8. Examples for the image processing chapter 373
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
An example showing how to use broad-casting to plot the mean of blocks of an image.
import numpy as np
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
import numpy as np
f = scipy.misc.face(gray=True) import scipy.misc
sx, sy = f.shape from scipy import ndimage
X, Y = np.ogrid[0:sx, 0:sy] import matplotlib.pyplot as plt
f = scipy.misc.face(gray=True)
r = np.hypot(X - sx/2, Y - sy/2) sx, sy = f.shape
X, Y = np.ogrid[0:sx, 0:sy]
rbin = (20* r/r.max()).astype(np.int)
radial_mean = ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() +1)) regions = sy//6 * (X//4) + Y//6
block_mean = ndimage.mean(f, labels=regions,
plt.figure(figsize=(5, 5)) index=np.arange(1, regions.max() +1))
plt.axes([0, 0, 1, 1]) block_mean.shape = (sx//4, sy//6)
plt.imshow(rbin, cmap=plt.cm.spectral)
plt.axis('off') plt.figure(figsize=(5, 5))
plt.imshow(block_mean, cmap=plt.cm.gray)
plt.show() plt.axis('off')
Download Python source code: plot_radial_mean.py Total running time of the script: ( 0 minutes 0.164 seconds)
Download Jupyter notebook: plot_radial_mean.ipynb Download Python source code: plot_block_mean.py
Generated by Sphinx-Gallery Download Jupyter notebook: plot_block_mean.ipynb
12.8. Examples for the image processing chapter 374 12.8. Examples for the image processing chapter 375
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Generated by Sphinx-Gallery
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
f = scipy.misc.face(gray=True).astype(float)
blurred_f = ndimage.gaussian_filter(f, 3)
filter_blurred_f = ndimage.gaussian_filter(blurred_f, 1)
import scipy.misc
import matplotlib.pyplot as plt alpha = 30
sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)
f = scipy.misc.face(gray=True)
plt.figure(figsize=(12, 4))
plt.figure(figsize=(10, 3.6))
plt.subplot(131)
plt.subplot(131) plt.imshow(f, cmap=plt.cm.gray)
plt.imshow(f, cmap=plt.cm.gray) plt.axis('off')
plt.subplot(132)
plt.subplot(132) plt.imshow(blurred_f, cmap=plt.cm.gray)
plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200) plt.axis('off')
plt.axis('off') plt.subplot(133)
plt.imshow(sharpened, cmap=plt.cm.gray)
plt.subplot(133) plt.axis('off')
plt.imshow(f, cmap=plt.cm.gray)
plt.contour(f, [50, 200]) plt.tight_layout()
plt.axis('off') plt.show()
plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.05, Total running time of the script: ( 0 minutes 0.355 seconds)
right=0.99)
plt.show() Download Python source code: plot_sharpen.py
Download Jupyter notebook: plot_sharpen.ipynb
Total running time of the script: ( 0 minutes 0.403 seconds)
Generated by Sphinx-Gallery
Download Python source code: plot_display_face.py
Download Jupyter notebook: plot_display_face.ipynb
12.8.8 Blurring of images
Generated by Sphinx-Gallery
An example showing various processes that blur an image.
This example shows how to sharpen an image in noiseless situation by applying the filter inverse to the blur.
12.8. Examples for the image processing chapter 376 12.8. Examples for the image processing chapter 377
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
12.8. Examples for the image processing chapter 378 12.8. Examples for the image processing chapter 379
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import scipy
import scipy.misc
import numpy as np from scipy import ndimage
from scipy import ndimage import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
f = scipy.misc.face(gray=True)
square = np.zeros((32, 32)) f = f[230:290, 220:320]
square[10:-10, 10:-10] = 1
np.random.seed(2) noisy = f + 0.4*f.std()*np.random.random(f.shape)
x, y = (32*np.random.random((2, 20))).astype(np.int)
square[x, y] = 1 gauss_denoised = ndimage.gaussian_filter(noisy, 2)
med_denoised = ndimage.median_filter(noisy, 3)
open_square = ndimage.binary_opening(square)
12.8. Examples for the image processing chapter 380 12.8. Examples for the image processing chapter 381
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
np.random.seed(1)
n = 10
l = 256
import numpy as np
im = np.zeros((l, l))
from scipy import ndimage
points = l*np.random.random((2, n**2))
import matplotlib.pyplot as plt
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
np.random.seed(1)
n = 10
mask = im > im.mean()
l = 256
im = np.zeros((l, l))
label_im, nb_labels = ndimage.label(mask)
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
# Find the largest connected component
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
sizes = ndimage.sum(mask, label_im, range(nb_labels + 1))
mask_size = sizes < 1000
mask = im > im.mean()
remove_pixel = mask_size[label_im]
label_im[remove_pixel] = 0
label_im, nb_labels = ndimage.label(mask)
labels = np.unique(label_im)
label_im = np.searchsorted(labels, label_im)
sizes = ndimage.sum(mask, label_im, range(nb_labels + 1))
mask_size = sizes < 1000
# Now that we have only one connected component, extract it's bounding box
remove_pixel = mask_size[label_im]
slice_x, slice_y = ndimage.find_objects(label_im==4)[0]
label_im[remove_pixel] = 0
roi = im[slice_x, slice_y]
labels = np.unique(label_im)
label_clean = np.searchsorted(labels, label_im)
plt.figure(figsize=(4, 2))
plt.axes([0, 0, 1, 1])
plt.imshow(roi)
plt.figure(figsize=(6 ,3))
plt.axis('off')
plt.subplot(121)
plt.show()
plt.imshow(label_im, cmap=plt.cm.spectral)
plt.axis('off')
Total running time of the script: ( 0 minutes 0.102 seconds) plt.subplot(122)
Download Python source code: plot_find_object.py plt.imshow(label_clean, vmax=nb_labels, cmap=plt.cm.spectral)
plt.axis('off')
Download Jupyter notebook: plot_find_object.ipynb
plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1)
Generated by Sphinx-Gallery plt.show()
12.8.13 Measurements from images Total running time of the script: ( 0 minutes 0.073 seconds)
Download Python source code: plot_measure_data.py
This examples shows how to measure quantities from various images.
Download Jupyter notebook: plot_measure_data.ipynb
Generated by Sphinx-Gallery
12.8. Examples for the image processing chapter 382 12.8. Examples for the image processing chapter 383
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
12.8.14 Geometrical transformations 12.8.15 Denoising an image with the median filter
This examples demos some simple geometrical transformations on a Racoon face. This example shows the original image, the noisy image, the denoised one (with the median filter) and the
difference between the two.
import numpy as np
import scipy.misc
from scipy import ndimage
import matplotlib.pyplot as plt
face = scipy.misc.face(gray=True)
import numpy as np
lx, ly = face.shape
from scipy import ndimage
# Cropping
import matplotlib.pyplot as plt
crop_face = face[lx//4:-lx//4, ly//4:-ly//4]
# up <-> down flip
im = np.zeros((20, 20))
flip_ud_face = np.flipud(face)
im[5:-5, 5:-5] = 1
# rotation
im = ndimage.distance_transform_bf(im)
rotate_face = ndimage.rotate(face, 45)
im_noise = im + 0.2*np.random.randn(*im.shape)
rotate_face_noreshape = ndimage.rotate(face, 45, reshape=False)
im_med = ndimage.median_filter(im_noise, 3)
plt.figure(figsize=(12.5, 2.5))
plt.figure(figsize=(16, 5))
plt.subplot(151)
plt.subplot(141)
plt.imshow(face, cmap=plt.cm.gray)
plt.imshow(im, interpolation='nearest')
plt.axis('off')
plt.axis('off')
plt.subplot(152)
plt.title('Original image', fontsize=20)
plt.imshow(crop_face, cmap=plt.cm.gray)
plt.subplot(142)
plt.axis('off')
plt.imshow(im_noise, interpolation='nearest', vmin=0, vmax=5)
plt.subplot(153)
plt.axis('off')
plt.imshow(flip_ud_face, cmap=plt.cm.gray)
plt.title('Noisy image', fontsize=20)
plt.axis('off')
plt.subplot(143)
plt.subplot(154)
plt.imshow(im_med, interpolation='nearest', vmin=0, vmax=5)
plt.imshow(rotate_face, cmap=plt.cm.gray)
plt.axis('off')
plt.axis('off')
plt.title('Median filter', fontsize=20)
plt.subplot(155)
plt.subplot(144)
plt.imshow(rotate_face_noreshape, cmap=plt.cm.gray)
plt.imshow(np.abs(im - im_med), cmap=plt.cm.hot, interpolation='nearest')
plt.axis('off')
plt.axis('off')
plt.title('Error', fontsize=20)
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0,
right=1)
plt.subplots_adjust(wspace=0.02, hspace=0.02, top=0.9, bottom=0, left=0,
plt.show()
right=1)
12.8. Examples for the image processing chapter 384 12.8. Examples for the image processing chapter 385
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
np.random.seed(1)
import matplotlib.pyplot as plt
n = 10
l = 256
im = np.zeros((256, 256))
im = np.zeros((l, l))
im[64:-64, 64:-64] = 1
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.rotate(im, 15, mode='constant')
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
im = ndimage.gaussian_filter(im, 8)
mask = (im > im.mean()).astype(np.float)
sx = ndimage.sobel(im, axis=0, mode='constant')
sy = ndimage.sobel(im, axis=1, mode='constant')
mask += 0.1 * im
sob = np.hypot(sx, sy)
img = mask + 0.2*np.random.randn(*mask.shape)
plt.figure(figsize=(16, 5))
plt.subplot(141)
hist, bin_edges = np.histogram(img, bins=60)
plt.imshow(im, cmap=plt.cm.gray)
bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:])
plt.axis('off')
plt.title('square', fontsize=20)
binary_img = img > 0.5
plt.subplot(142)
plt.imshow(sx)
plt.figure(figsize=(11,4))
plt.axis('off')
plt.title('Sobel (x direction)', fontsize=20)
plt.subplot(131)
plt.subplot(143)
plt.imshow(img)
plt.imshow(sob)
plt.axis('off')
plt.axis('off')
plt.subplot(132)
plt.title('Sobel filter', fontsize=20)
plt.plot(bin_centers, hist, lw=2)
plt.axvline(0.5, color='r', ls='--', lw=2)
im += 0.07*np.random.random(im.shape)
plt.text(0.57, 0.8, 'histogram', fontsize=20, transform = plt.gca().transAxes)
plt.yticks([])
sx = ndimage.sobel(im, axis=0, mode='constant')
plt.subplot(133)
sy = ndimage.sobel(im, axis=1, mode='constant')
plt.imshow(binary_img, cmap=plt.cm.gray, interpolation='nearest')
sob = np.hypot(sx, sy)
plt.axis('off')
plt.subplot(144)
plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)
plt.imshow(sob)
plt.show()
plt.axis('off')
plt.title('Sobel for noisy image', fontsize=20)
Total running time of the script: ( 0 minutes 0.109 seconds)
Download Python source code: plot_histo_segmentation.py
12.8. Examples for the image processing chapter 386 12.8. Examples for the image processing chapter 387
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import numpy as np
import numpy as np from scipy import ndimage
import scipy import matplotlib.pyplot as plt
import scipy.misc
import matplotlib.pyplot as plt im = np.zeros((64, 64))
try: np.random.seed(2)
from skimage.restoration import denoise_tv_chambolle x, y = (63*np.random.random((2, 8))).astype(np.int)
except ImportError: im[x, y] = np.arange(8)
# skimage < 0.12
from skimage.filters import denoise_tv_chambolle bigger_points = ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5)))
12.8. Examples for the image processing chapter 388 12.8. Examples for the image processing chapter 389
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
12.8.20 Cleaning segmentation with mathematical morphology Total running time of the script: ( 0 minutes 0.146 seconds)
Download Python source code: plot_clean_morpho.py
An example showing how to clean segmentation with mathematical morphology: removing small regions and
holes. Download Jupyter notebook: plot_clean_morpho.ipynb
Generated by Sphinx-Gallery
This example performs a Gaussian mixture model analysis of the image histogram to find the right thresholds
for separating foreground from background.
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
np.random.seed(1)
n = 10
l = 256
im = np.zeros((l, l))
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
plt.subplot(141)
plt.imshow(binary_img[:l, :l], cmap=plt.cm.gray) img = mask + 0.3*np.random.randn(*mask.shape)
plt.axis('off')
plt.subplot(142) hist, bin_edges = np.histogram(img, bins=60)
plt.imshow(open_img[:l, :l], cmap=plt.cm.gray) bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:])
plt.axis('off')
plt.subplot(143) classif = GMM(n_components=2)
plt.imshow(close_img[:l, :l], cmap=plt.cm.gray) classif.fit(img.reshape((img.size, 1)))
plt.axis('off')
plt.subplot(144) threshold = np.mean(classif.means_)
plt.imshow(mask[:l, :l], cmap=plt.cm.gray) binary_img = img > threshold
plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors='r')
plt.axis('off')
plt.figure(figsize=(11,4))
12.8. Examples for the image processing chapter 390 12.8. Examples for the image processing chapter 391
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
local_maxi = peak_local_max(
plt.subplot(131) distance, indices=False, footprint=np.ones((3, 3)), labels=image)
plt.imshow(img) markers = ndimage.label(local_maxi)[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=plt.cm.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) plt.imshow(labels, cmap='spectral', interpolation='nearest')
plt.show() plt.axis('off')
Total running time of the script: ( 0 minutes 0.463 seconds) plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0,
right=1)
Download Python source code: plot_GMM.py plt.show()
Download Jupyter notebook: plot_GMM.ipynb
Total running time of the script: ( 0 minutes 0.127 seconds)
Generated by Sphinx-Gallery
Download Python source code: plot_watershed_segmentation.py
Download Jupyter notebook: plot_watershed_segmentation.ipynb
12.8.22 Watershed segmentation
Generated by Sphinx-Gallery
This example shows how to do segmentation with watershed.
12.8.23 Granulometry
import numpy as np
from skimage.morphology import watershed
from skimage.feature import peak_local_max
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from scipy import ndimage
import matplotlib.pyplot as plt
# Generate an initial image with two overlapping circles
def disk_structure(n):
x, y = np.indices((80, 80))
struct = np.zeros((2 * n + 1, 2 * n + 1))
x1, y1, x2, y2 = 28, 28, 44, 52
x, y = np.indices((2 * n + 1, 2 * n + 1))
r1, r2 = 16, 20
mask = (x - n)**2 + (y - n)**2 <= n**2
mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2
struct[mask] = 1
mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2
return struct.astype(np.bool)
image = np.logical_or(mask_circle1, mask_circle2)
# Now we want to separate the two objects in image
# Generate the markers as local maxima of the distance
def granulometry(data, sizes=None):
# to the background
s = max(data.shape)
distance = ndimage.distance_transform_edt(image)
if sizes is None:
12.8. Examples for the image processing chapter 392 12.8. Examples for the image processing chapter 393
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
4 circles
np.random.seed(1)
n = 10 img = circle1 + circle2 + circle3 + circle4
l = 256 mask = img.astype(bool)
im = np.zeros((l, l)) img = img.astype(float)
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 img += 1 + 0.2*np.random.randn(*img.shape)
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))
# Convert the image into a graph with the value of the gradient on the
mask = im > im.mean() # edges.
graph = image.img_to_graph(img, mask=mask)
granulo = granulometry(mask, sizes=np.arange(2, 19, 4))
# Take a decreasing function of the gradient: we take it weakly
plt.figure(figsize=(6, 2.2)) # dependant from the gradient the segmentation is close to a voronoi
graph.data = np.exp(-graph.data / graph.data.std())
plt.subplot(121)
plt.imshow(mask, cmap=plt.cm.gray) # Force the solver to be arpack, since amg is numerically
opened = ndimage.binary_opening(mask, structure=disk_structure(10)) # unstable on this example
opened_more = ndimage.binary_opening(mask, structure=disk_structure(14)) labels = spectral_clustering(graph, n_clusters=4)
plt.contour(opened, [0.5], colors='b', linewidths=2) label_im = -np.ones(mask.shape)
plt.contour(opened_more, [0.5], colors='r', linewidths=2) label_im[mask] = labels
plt.axis('off')
plt.subplot(122) plt.figure(figsize=(6, 3))
plt.plot(np.arange(2, 19, 4), granulo, 'ok', ms=8) plt.subplot(121)
plt.imshow(img, cmap=plt.cm.spectral, interpolation='nearest')
plt.axis('off')
plt.subplots_adjust(wspace=0.02, hspace=0.15, top=0.95, bottom=0.15, left=0, right=0.95) plt.subplot(122)
plt.show() plt.imshow(label_im, cmap=plt.cm.spectral, interpolation='nearest')
plt.axis('off')
Total running time of the script: ( 0 minutes 0.318 seconds)
plt.subplots_adjust(wspace=0, hspace=0., top=0.99, bottom=0.01, left=0.01, right=0.99)
Download Python source code: plot_granulo.py plt.show()
Download Jupyter notebook: plot_granulo.ipynb
Generated by Sphinx-Gallery
import numpy as np
import matplotlib.pyplot as plt
l = 100
x, y = np.indices((l, l))
radius1, radius2, radius3, radius4 = 16, 14, 15, 14 Download Python source code: plot_spectral_clustering.py
Download Jupyter notebook: plot_spectral_clustering.ipynb
12.8. Examples for the image processing chapter 394 12.8. Examples for the image processing chapter 395
Scipy lecture notes, Edition 2017.1
Generated by Sphinx-Gallery
Download all examples in Python source code: auto_examples_python.zip
Download all examples in Jupyter notebooks: auto_examples_jupyter.zip
Generated by Sphinx-Gallery
See also:
More on image-processing:
• The chapter on Scikit-image
CHAPTER 13
• Other, more powerful and complete modules: OpenCV (Python bindings), CellProfiler, ITK with Python
bindings
Prerequisites
• Numpy
• Scipy
• Matplotlib
See also:
References
Mathematical optimization is very . . . mathematical. If you want performance, it really pays to read the books:
• Convex Optimization by Boyd and Vandenberghe (pdf available free online).
• Numerical Optimization, by Nocedal and Wright. Detailed reference on gradient descent methods.
• Practical Methods of Optimization by Fletcher: good at hand-waving explanations.
Not all optimization problems are equal. Knowing your problem enables you to choose the right tool.
13.1. Knowing your problem 398 13.1. Knowing your problem 399
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
13.1.3 Noisy versus exact cost functions >>> from scipy import optimize
>>> def f(x):
... return -np.exp(-(x - 0.7)**2)
>>> result = optimize.minimize_scalar(f)
>>> result.success # check if solver was successful
True
>>> x_min = result.x
>>> x_min
0.699999999...
>>> x_min - 0.7
-2.160590595323697e-10
Many optimization methods rely on gradients of the objective function. If the gradient function is not given,
they are computed numerically, which induces errors. In such situation, even if the objective function is not
noisy, a gradient-based optimization may be a noisy optimization.
Note: You can use different solvers using the parameter method.
Let’s get started by finding the minimum of the scalar function f (x) = exp[(x − 0.7)2 ]. scipy.optimize.
minimize_scalar() uses Brent’s method to find the minimum of a function:
13.2. A review of the different optimizers 400 13.2. A review of the different optimizers 401
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Table 13.1: Fixed step gradient descent Table 13.2: Adaptive step gradient descent
A well-conditioned quadratic
An ill-conditioned quadratic function. function.
The core problem of gradient-methods on ill-conditioned prob-
lems is that the gradient tends not to point in the direction of the
minimum.
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 An ill-conditioned quadratic
preconditioning. function.
Also, it clearly can be advantageous to take bigger steps. This is done in gradient descent code using a line
search.
An ill-conditioned non-
quadratic function.
The more a function looks like a quadratic function (elliptic iso-curves), the easier it is to optimize.
The gradient descent algorithms above are toys not to be used on real problems.
As can be seen from the above experiments, one of the problems of the simple gradient descent algorithms, is
that it tends to oscillate across a valley, each time following the direction of the gradient, that makes it cross
the valley. The conjugate gradient solves this problem by adding a friction term: each step depends on the two
last values of the gradient and sharp turns are reduced.
13.2. A review of the different optimizers 402 13.2. A review of the different optimizers 403
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Newton methods use a local quadratic approximation to compute the jump direction. For this purpose, they
rely on the 2 first derivative of the function: the gradient and the Hessian.
An ill-conditioned non-
quadratic function. An ill-conditioned quadratic function:
Note that, as the quadratic approximation is exact, the Newton
method is blazing fast
scipy provides scipy.optimize.minimize() to find the minimum of scalar functions of one or more vari-
ables. The simple conjugate gradient method can be used by setting the parameter method to CG
An ill-conditioned very non-quadratic function:
>>> def f(x): # The rosenbrock function
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
In scipy, you can use the Newton method by setting method to Newton-CG in scipy.optimize.minimize().
>>> optimize.minimize(f, [2, -1], method="CG")
Here, CG refers to the fact that an internal inversion of the Hessian is performed by conjugate gradient
fun: 1.6503...e-11
jac: array([ -6.1534...e-06, 2.5380...e-07]) >>> def f(x): # The rosenbrock function
message: ...'Optimization terminated successfully.' ... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
nfev: 108 >>> def jacobian(x):
nit: 13 ... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
njev: 27 >>> optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian)
status: 0 fun: 1.5601...e-15
success: True jac: array([ 1.0575...e-07, -7.4832...e-08])
x: array([ 0.99999..., 0.99998...]) message: ...'Optimization terminated successfully.'
nfev: 11
Gradient methods need the Jacobian (gradient) of the function. They can compute it numerically, but will nhev: 0
perform better if you can pass them the gradient: nit: 10
njev: 52
>>> def jacobian(x): status: 0
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2))) success: True
>>> optimize.minimize(f, [2, 1], method="CG", jac=jacobian) x: array([ 0.99999..., 0.99999...])
fun: 2.957...e-14
jac: array([ 7.1825...e-07, -2.9903...e-07])
Note that compared to a conjugate gradient (above), Newton’s method has required less function evaluations,
message: 'Optimization terminated successfully.'
but more gradient evaluations, as it uses it to approximate the Hessian. Let’s compute the Hessian and pass it
nfev: 16
nit: 8 to the algorithm:
njev: 16
>>> def hessian(x): # Computed with sympy
status: 0
... return np.array(((1 - 4*x[1] + 12*x[0]**2, -4*x[0]), (-4*x[0], 2)))
success: True
>>> optimize.minimize(f, [2,-1], method="Newton-CG", jac=jacobian, hess=hessian)
x: array([ 1.0000..., 1.0000...])
fun: 1.6277...e-15
jac: array([ 1.1104...e-07, -7.7809...e-08])
Note that the function has only been evaluated 27 times, compared to 108 without the gradient. message: ...'Optimization terminated successfully.'
nfev: 11
nhev: 10
nit: 10
13.2. A review of the different optimizers 404 13.2. A review of the different optimizers 405
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
njev: 20 pl.clf()
status: 0
success: True pl.plot(x_, f(x_) + .2*np.random.normal(size=31), linewidth=2)
x: array([ 0.99999..., 0.99999...]) pl.plot(x, f(x), linewidth=2)
pl.ylim(ymin=-1.3)
Note: At very high-dimension, the inversion of the Hessian can be costly and unstable (large scale > 250). pl.axis('off')
pl.tight_layout()
pl.show()
Note: Newton optimizers should not to be confused with Newton’s root finding method, based on the same Total running time of the script: ( 0 minutes 0.053 seconds)
principles, scipy.optimize.newton().
Download Python source code: plot_noisy.py
Download Jupyter notebook: plot_noisy.ipynb
Quasi-Newton methods: approximating the Hessian on the fly Generated by Sphinx-Gallery
BFGS: BFGS (Broyden-Fletcher-Goldfarb-Shanno algorithm) refines at each step an approximation of the Hes-
sian. 13.4.2 Smooth vs non-smooth
import numpy as np
import pylab as pl
# A smooth function
pl.figure(1, figsize=(3, 2.5))
pl.clf()
13.3. Full code examples 406 13.4. Examples for the mathematical optimization chapter 407
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
13.4.3 Curve fitting Total running time of the script: ( 0 minutes 0.035 seconds)
Download Python source code: plot_curve_fit.py
A curve fitting example
Download Jupyter notebook: plot_curve_fit.ipynb
Generated by Sphinx-Gallery
import numpy as np
import pylab as pl
x = np.linspace(-1, 2)
13.4. Examples for the mathematical optimization chapter 408 13.4. Examples for the mathematical optimization chapter 409
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
An excercise of finding minimum. This excercise is hard because the function is very flat around the minimum
(all its derivatives are zero). Thus gradient information is unreliable.
The function admits a minimum in [0, 0]. The challenge is to get within 1e-7 of this minimum, starting at x0 =
[1, 1].
The solution that we adopt here is to give up on using gradient or information based on local differences, and
to rely on the Powell algorithm. With 162 function evaluations, we get to 1e-8 of the solution.
•
import numpy as np
from scipy import optimize
import pylab as pl
def f(x):
return np.exp(-1/(.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 410 13.4. Examples for the mathematical optimization chapter 411
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
accumulated = np.array(accumulator)
pl.plot(accumulated[:, 0], accumulated[:, 1])
pl.show()
x, y = np.mgrid[-2.03:4.2:.04, -1.6:3.2:.04]
x = x.T
y = y.T
def f(x):
# Store the list of function calls •
accumulator.append(x)
return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2) Out:
13.4. Examples for the mathematical optimization chapter 412 13.4. Examples for the mathematical optimization chapter 413
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Generated by Sphinx-Gallery
Converged at 6
Converged at 23
13.4.8 Constraint optimization: visualizing the geometry
import numpy as np
import pylab as pl
from scipy import optimize
x = np.linspace(-1, 3, 100)
x_0 = np.exp(-1) •
def f(x):
return (x - x_0)**2 + epsilon*np.exp(-5*(x - .5 - x_0)**2)
13.4. Examples for the mathematical optimization chapter 414 13.4. Examples for the mathematical optimization chapter 415
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
def f(x):
# Store the list of function calls pl.figure(1, figsize=(10, 4))
accumulator.append(x) pl.clf()
return np.sqrt((x[0] - 3)**2 + (x[1] - 2)**2)
colors = pl.cm.Spectral(np.linspace(0, 1, n_dims))[:, :3]
# We don't use the gradient, as with the gradient, L-BFGS is too fast, method_names = list(list(results.values())[0]['Rosenbrock '].keys())
# and finds the optimum without showing us a pretty path method_names.sort(key=lambda x: x[::-1], reverse=True)
def f_prime(x):
r = np.sqrt((x[0] - 3)**2 + (x[0] - 2)**2) for n_dim_index, ((n_dim, n_dim_bench), color) in enumerate(
return np.array(((x[0] - 3)/r, (x[0] - 2)/r)) zip(sorted(results.items()), colors)):
for (cost_name, cost_bench), symbol in zip(sorted(n_dim_bench.items()),
optimize.minimize(f, np.array([0, 0]), method="L-BFGS-B", symbols):
bounds=((-1.5, 1.5), (-1.5, 1.5))) for method_index, method_name, in enumerate(method_names):
this_bench = cost_bench[method_name]
accumulated = np.array(accumulator) bench = np.mean(this_bench)
pl.plot(accumulated[:, 0], accumulated[:, 1]) pl.semilogy([method_index + .1*n_dim_index, ], [bench, ],
marker=symbol, color=color)
pl.show()
# Create a legend for the problem type
Total running time of the script: ( 0 minutes 0.124 seconds) for cost_name, symbol in zip(sorted(n_dim_bench.keys()),
symbols):
Download Python source code: plot_constraints.py pl.semilogy([-10, ], [0, ], symbol, color='.5',
label=cost_name)
Download Jupyter notebook: plot_constraints.ipynb
Generated by Sphinx-Gallery pl.xticks(np.arange(n_methods), method_names, size=11)
pl.xlim(-.2, n_methods - .5)
pl.legend(loc='best', numpoints=1, handletextpad=0, prop=dict(size=12),
13.4.9 Plotting the comparison of optimizers frameon=False)
pl.ylabel('# function calls (a.u.)')
Plots the results from the comparison of optimizers.
# Create a second legend for the problem dimensionality
pl.twinx()
pl.xticks(np.arange(n_methods), method_names)
pl.yticks(())
pl.tight_layout()
pl.show()
symbols = 'o>*Ds'
13.4. Examples for the mathematical optimization chapter 416 13.4. Examples for the mathematical optimization chapter 417
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
def f_prime(x):
return 2*np.dot(np.dot(K.T, K), x - 1) + 4*np.sum(x**2)*x
def hessian(x):
H = 2*np.dot(K.T, K) + 4*2*x*x[:, np.newaxis]
return H + 4*np.eye(H.shape[0])*np.sum(x**2)
pl.figure(1)
pl.clf()
Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j]
# Complete in the additional dimensions with zeros
Z = np.reshape(Z, (2, -1)).copy()
Z.resize((100, Z.shape[-1]))
Z = np.apply_along_axis(f, 0, Z)
Z = np.reshape(Z, X.shape)
pl.imshow(Z.T, cmap=pl.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1],
origin='lower')
pl.contour(X, Y, Z, cmap=pl.cm.gnuplot)
13.4. Examples for the mathematical optimization chapter 418 13.4. Examples for the mathematical optimization chapter 419
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
def super_fmt(value):
if value > 1: def newton_cg(x0, f, f_prime, hessian):
if np.abs(int(value) - value) < .1: all_x_i = [x0[0]]
out = '$10^{%.1i }$' % value all_y_i = [x0[1]]
else: all_f_i = [f(x0)]
out = '$10^{%.1f }$' % value def store(X):
else: x, y = X
value = np.exp(value - .01) all_x_i.append(x)
if value > .1: all_y_i.append(y)
out = '%1.1f ' % value all_f_i.append(f(X))
elif value > .01: optimize.minimize(f, x0, method="Newton-CG", jac=f_prime, hess=hessian, callback=store,␣
out = '%.2f ' % value ,→options={"xtol": 1e-12})
else: return all_x_i, all_y_i, all_f_i
out = '%.2e ' % value
return out
def bfgs(x0, f, f_prime, hessian=None):
A gradient descent algorithm do not use: its a toy, use scipy’s optimize.fmin_cg all_x_i = [x0[0]]
all_y_i = [x0[1]]
def gradient_descent(x0, f, f_prime, hessian=None, adaptative=False): all_f_i = [f(x0)]
x_i, y_i = x0 def store(X):
all_x_i = list() x, y = X
all_y_i = list() all_x_i.append(x)
all_f_i = list() all_y_i.append(y)
all_f_i.append(f(X))
for i in range(1, 100): optimize.minimize(f, x0, method="BFGS", jac=f_prime, callback=store, options={"gtol": 1e-
all_x_i.append(x_i) ,→12})
all_y_i.append(y_i) return all_x_i, all_y_i, all_f_i
all_f_i.append(f([x_i, y_i]))
dx_i, dy_i = f_prime(np.asarray([x_i, y_i]))
if adaptative: def powell(x0, f, f_prime, hessian=None):
# Compute a step size using a line_search to satisfy the Wolf all_x_i = [x0[0]]
# conditions all_y_i = [x0[1]]
step = optimize.line_search(f, f_prime, all_f_i = [f(x0)]
np.r_[x_i, y_i], -np.r_[dx_i, dy_i], def store(X):
np.r_[dx_i, dy_i], c2=.05) x, y = X
step = step[0] all_x_i.append(x)
if step is None: all_y_i.append(y)
step = 0 all_f_i.append(f(X))
else: optimize.minimize(f, x0, method="Powell", callback=store, options={"ftol": 1e-12})
step = 1 return all_x_i, all_y_i, all_f_i
x_i += - step*dx_i
y_i += - step*dy_i
if np.abs(all_f_i[-1]) < 1e-16: def nelder_mead(x0, f, f_prime, hessian=None):
break all_x_i = [x0[0]]
return all_x_i, all_y_i, all_f_i all_y_i = [x0[1]]
all_f_i = [f(x0)]
def store(X):
def gradient_descent_adaptative(x0, f, f_prime, hessian=None): x, y = X
13.4. Examples for the mathematical optimization chapter 420 13.4. Examples for the mathematical optimization chapter 421
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
13.4. Examples for the mathematical optimization chapter 422 13.4. Examples for the mathematical optimization chapter 423
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• •
• •
• •
• •
• •
• •
• •
13.4. Examples for the mathematical optimization chapter 424 13.4. Examples for the mathematical optimization chapter 425
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
•
•
13.4. Examples for the mathematical optimization chapter 426 13.4. Examples for the mathematical optimization chapter 427
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• •
• •
• •
• •
Total running time of the script: ( 0 minutes 12.552 seconds)
Download Python source code: plot_gradient_descent.py
Download Jupyter notebook: plot_gradient_descent.ipynb
Generated by Sphinx-Gallery
Download all examples in Python source code: auto_examples_python.zip
• Download all examples in Jupyter notebooks: auto_examples_jupyter.zip
Generated by Sphinx-Gallery
13.4. Examples for the mathematical optimization chapter 428 13.4. Examples for the mathematical optimization chapter 429
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
L-BFGS: Limited-memory BFGS Sits between BFGS and conjugate gradient: in very high dimensions (> 250)
the Hessian matrix is too costly to compute and invert. L-BFGS keeps a low-rank version. In addition, box
bounds are also supported by L-BFGS-B:
An ill-conditioned non-
>>> def f(x): # The rosenbrock function
quadratic function:
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2
>>> def jacobian(x):
... return np.array((-2*.5*(1 - x[0]) - 4*x[0]*(x[1] - x[0]**2), 2*(x[1] - x[0]**2)))
>>> optimize.minimize(f, [2, 2], method="L-BFGS-B", jac=jacobian)
fun: 1.4417...e-15
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
jac: array([ 1.0233...e-07, -2.5929...e-08])
message: ...'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
nfev: 17
nit: 16
status: 0 An ill-conditioned very non-
success: True quadratic function:
x: array([ 1.0000..., 1.0000...])
Using the Nelder-Mead solver in scipy.optimize.minimize():
13.4. Examples for the mathematical optimization chapter 430 13.4. Examples for the mathematical optimization chapter 431
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• In general, prefer BFGS or L-BFGS, even if you have to approximate numerically gra-
>>> def f(x): # The rosenbrock function
... return .5*(1 - x[0])**2 + (x[1] - x[0]**2)**2 dients. These are also the default if you omit the parameter method - depending if the
>>> optimize.minimize(f, [2, -1], method="Nelder-Mead") problem has constraints or bounds
final_simplex: (array([[ 1.0000..., 1.0000...], • On well-conditioned problems, Powell and Nelder-Mead, both gradient-free methods,
[ 0.99998... , 0.99996... ],
work well in high dimension, but they collapse for ill-conditioned problems.
[ 1.0000..., 1.0000... ]]), array([ 1.1152...e-10, 1.5367...e-10, 4.9883...e-10]))
fun: 1.1152...e-10 With knowledge of the gradient
message: ...'Optimization terminated successfully.'
nfev: 111 • BFGS or L-BFGS.
nit: 58 • Computational overhead of BFGS is larger than that L-BFGS, itself larger than that of
status: 0
conjugate gradient. On the other side, BFGS usually needs less function evaluations than
success: True
CG. Thus conjugate gradient method is better than BFGS at optimizing computationally
x: array([ 1.0000..., 1.0000...])
cheap functions.
With the Hessian
13.4.13 Global optimizers • If you can compute the Hessian, prefer the Newton method (Newton-CG or TCG).
If your problem does not admit a unique local minimum (which can be hard to test unless the function is If you have noisy measurements
convex), and you do not have prior information to initialize the optimization close to the solution, you may • Use Nelder-Mead or Powell.
need a global optimizer.
13.5 Practical guide to optimization with scipy Computing gradients, and even more Hessians, is very tedious but worth the effort. Symbolic computation
with Sympy may come in handy.
13.5.1 Choosing a method Warning: 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
All methods are exposed as the method argument of scipy.optimize.minimize().
returns the norm of the different between the gradient given, and a gradient computed numerically:
>>> optimize.check_grad(f, jacobian, [2, -1])
2.384185791015625e-07
13.5. Practical guide to optimization with scipy 432 13.5. Practical guide to optimization with scipy 433
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
This took 67 function evaluations (check it with ‘full_output=1’). What if we compute the norm ourselves and
use a good generic optimizer (BFGS):
13.5. Practical guide to optimization with scipy 434 13.6. Special case: non-linear least-squares 435
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> optimize.curve_fit(f, x, y)
(array([ 1.5185..., 0.92665...]), array([[ 0.00037..., -0.00056...],
[-0.0005..., 0.00123...]]))
Exercise
13.6. Special case: non-linear least-squares 436 13.7. Optimization with constraints 437
Scipy lecture notes, Edition 2017.1
14
nit: 5
njev: 5
status: 0
success: True
x: array([ 1.2500..., 0.2499...])
Warning: The above problem is known as the Lasso problem in statistics, and there exist very efficient
CHAPTER
solvers for it (for instance in scikit-learn). In general do not use generic solvers when specific ones exist.
Lagrange multipliers
If you are ready to do a bit of math, many constrained optimization problems can be converted to non-
constrained optimization problems using a mathematical trick known as Lagrange multipliers.
Interfacing with C
13.8 Full code examples
Chapters contents
• Introduction
• Python-C-Api
• Ctypes
• SWIG
• Cython
• Summary
• Further Reading and References
• Exercises
14.1 Introduction
• Existing code in C/C++ that needs to be leveraged, either because it already exists, or because it is faster. /* Example of wrapping cos function from math.h with the Python-C-API. */
• Python code too slow, push inner loops to native code # include <Python.h>
Each technology is demonstrated by wrapping the cos function from math.h. While this is a mostly a trivial # include <math.h>
example, it should serve us well to demonstrate the basics of the wrapping solution. Since each technique
/* wrapped cosine function */
also includes some form of Numpy support, this is also demonstrated using an example where the cosine is
static PyObject* cos_func(PyObject* self, PyObject* args)
computed on some kind of array. {
Last but not least, two small warnings: double value;
double answer;
• All of these techniques may crash (segmentation fault) the Python interpreter, which is (usually) due to
bugs in the C code. /* parse the input, from python float to c double */
if (!PyArg_ParseTuple(args, "d", &value))
• All the examples have been done on Linux, they should be possible on other operating systems. return NULL;
• You will need a C compiler for most of the examples. /* if the above function returns -1, an appropriate Python exception will
* have been set, and the function simply returns NULL
*/
CosMethods
}; Note: In Python 3, the filename for compiled modules includes metadata on the Python interpreter (see PEP
3149) and is thus longer. The import statement is not affected by this.
PyMODINIT_FUNC
PyInit_cos_module(void)
{ In [1]: import cos_module
return PyModule_Create(&cModPyDem);
} In [2]: cos_module?
Type: module
# else String Form:<module 'cos_module' from 'cos_module.so'>
File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/python_c_api/
,→cos_module.so
/* module initialization */
/* Python version 2 */ Docstring: <no docstring>
PyMODINIT_FUNC
initcos_module(void) In [3]: dir(cos_module)
{ Out[3]: ['__doc__', '__file__', '__name__', '__package__', 'cos_func']
(void) Py_InitModule("cos_module", CosMethods);
} In [4]: cos_module.cos_func(1.0)
Out[4]: 0.5403023058681398
# endif
In [5]: cos_module.cos_func(0.0)
Out[5]: 1.0
As you can see, there is much boilerplate, both to «massage» the arguments and return types into place and for
the module initialisation. Although some of this is amortised, as the extension grows, the boilerplate required In [6]: cos_module.cos_func(3.14159265359)
for each function(s) remains. Out[7]: -1.0
The standard python build system distutils supports compiling C-extensions from a setup.py, which is
rather convenient: Now let’s see how robust this is:
$ ls Analog to the Python-C-API, Numpy, which is itself implemented as a C-extension, comes with the Numpy-C-
cos_module.c setup.py API. This API can be used to create and manipulate Numpy arrays from C, when writing a custom C-extension.
See also: Advanced NumPy.
$ python setup.py build_ext --inplace
running build_ext
Note: If you do ever need to use the Numpy C-API refer to the documentation about Arrays and Iterators.
building 'cos_module' extension
creating build
creating build/temp.linux-x86_64-2.7 The following example shows how to pass Numpy arrays as arguments to functions and how to iterate over
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes - Numpy arrays using the (old) Numpy-C-API. It simply takes an array as argument applies the cosine function
,→fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/
from the math.h and returns a resulting new array.
,→cos_module.o
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib - /* Example of wrapping the cos function from math.h using the Numpy-C-API. */
,→lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/python_c_
,→api/cos_module.so
# include <Python.h>
# include <numpy/arrayobject.h>
$ ls # include <math.h>
build/ cos_module.c cos_module.so setup.py
/* wrapped cosine function */
• build_ext is to build extension modules static PyObject* cos_func_np(PyObject* self, PyObject* args)
{
• --inplace will output the compiled extension module into the current directory
The file cos_module.so contains the compiled extension, which we can now load in the IPython interpreter: PyArrayObject *in_array;
• Requires code to be wrapped to be available as a shared library (roughly speaking *.dll in Windows
*.so in Linux and *.dylib in Mac OSX.) In [4]: cos_module.cos_func(1.0)
• No good support for C++ Out[4]: 0.5403023058681398
In [5]: cos_module.cos_func(0.0)
14.3.1 Example Out[5]: 1.0
In [6]: cos_module.cos_func(3.14159265359)
As advertised, the wrapper code is in pure Python.
Out[6]: -1.0
""" Example of wrapping cos function from math.h using ctypes. """
As with the previous example, this code is somewhat robust, although the error message is not quite as helpful,
import ctypes since it does not tell us what the type should be.
m.PHONY : clean
cos_doubles.cos_doubles_func(x, y)
libcos_doubles.so : cos_doubles.o pylab.plot(x, y)
gcc -shared -Wl,-soname,libcos_doubles.so -o libcos_doubles.so cos_doubles.o pylab.show()
cos_doubles.o : cos_doubles.c
gcc -c -fPIC cos_doubles.c -o cos_doubles.o
clean :
-rm -vf libcos_doubles.so cos_doubles.o cos_doubles.pyc
We can then compile this (on Linux) into the shared library libcos_doubles.so:
$ 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 14.4 SWIG
Now we can proceed to wrap this library via ctypes with direct support for (certain kinds of) Numpy arrays: SWIG, the Simplified Wrapper Interface Generator, is a software development tool that connects programs
""" Example of wrapping a C library function that accepts a C double array as written in C and C++ with a variety of high-level programming languages, including Python. The important
input using the numpy.ctypeslib. """ thing with SWIG is, that it can autogenerate the wrapper code for you. While this is an advantage in terms of
development time, it can also be a burden. The generated file tend to be quite large and may not be too human
import numpy as np readable and the multiple levels of indirection which are a result of the wrapping process, may be a bit tricky
import numpy.ctypeslib as npct to understand.
from ctypes import c_int
# input type for the cos_doubles function Note: The autogenerated C code uses the Python-C-Api.
# must be a double array, with single dimension that is contiguous
array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS')
Advantages
# load the library, using numpy mechanisms • Can automatically wrap entire libraries given the headers
libcd = npct.load_library("libcos_doubles", ".")
• Works nicely with C++
# setup the return types and argument types Disadvantages
libcd.cos_doubles.restype = None
libcd.cos_doubles.argtypes = [array_1d_double, array_1d_double, c_int] • Autogenerates enormous files
• Hard to debug if something goes wrong
def cos_doubles_func(in_array, out_array): • Steep learning curve
return libcd.cos_doubles(in_array, out_array, len(in_array))
• Note the inherent limitation of contiguous single dimensional Numpy arrays, since the C functions re- 14.4.1 Example
quires this kind of buffer.
• Also note that the output array must be preallocated, for example with numpy.zeros() and the function Let’s imagine that our cos function lives in a cos_module which has been written in c and consists of the
will write into it’s buffer. source file cos_module.c:
• Although the original signature of the cos_doubles function is ARRAY, ARRAY, int the final # include <math.h>
cos_doubles_func takes only two Numpy arrays as arguments.
double cos_func(double arg){
And, as before, we convince ourselves that it worked: return cos(arg);
}
import numpy as np
import pylab
and the header file cos_module.h:
import cos_doubles
double cos_func(double arg);
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x)
And our goal is to expose the cos_func to Python. To achieve this with SWIG, we must write an interface file
In [2]: cos_module?
which contains the instructions for SWIG.
Type: module
/* Example of wrapping cos function from math.h using SWIG. */ String Form:<module 'cos_module' from 'cos_module.py'>
File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/swig/cos_
,→module.py
%module cos_module
%{ Docstring: <no docstring>
/* the resulting C file should be built as a python extension */
# define SWIG_FILE_WITH_INIT In [3]: dir(cos_module)
/* Includes the header in the wrapper code */ Out[3]:
# include "cos_module.h" ['__builtins__',
%} '__doc__',
/* Parse the header file to generate wrappers */ '__file__',
%include "cos_module.h" '__name__',
'__package__',
'_cos_module',
As you can see, not too much code is needed here. For this simple example it is enough to simply include '_newclass',
the header file in the interface file, to expose the function to Python. However, SWIG does allow for more fine '_object',
grained inclusion/exclusion of functions found in header files, check the documentation for details. '_swig_getattr',
'_swig_property',
Generating the compiled wrappers is a two stage process:
'_swig_repr',
1. Run the swig executable on the interface file to generate the files cos_module_wrap.c, which is the '_swig_setattr',
source file for the autogenerated Python C-extension and cos_module.py, which is the autogenerated '_swig_setattr_nondynamic',
pure python module. 'cos_func']
2. Compile the cos_module_wrap.c into the _cos_module.so. Luckily, distutils knows how to handle In [4]: cos_module.cos_func(1.0)
SWIG interface files, so that our setup.py is simply: Out[4]: 0.5403023058681398
We can now load and execute the cos_module as we have done in the previous examples: /* Compute the cosine of each element in in_array, storing the result in
* out_array. */
In [1]: import cos_module void cos_doubles(double * in_array, double * out_array, int size){
int i;
• Observe the call to import_array() which we encountered already in the Numpy-C-API example. cos_doubles.cos_doubles_func(x, y)
pylab.plot(x, y)
• Since the type maps only support the signature ARRAY, SIZE we need to wrap the cos_doubles as
pylab.show()
cos_doubles_func which takes two arrays including sizes as input.
• As opposed to the simple SWIG example, we don’t include the cos_doubles.h header, There is nothing
there that we wish to expose to Python since we expose the functionality through cos_doubles_func.
And, as before we can use distutils to wrap this:
setup(ext_modules=[Extension("_cos_doubles",
sources=["cos_doubles.c", "cos_doubles.i"],
include_dirs=[numpy.get_include()])])
$ ls
cos_doubles.c cos_doubles.h cos_doubles.i
$ python setup.py build_ext -i
numpy.i setup.py test_cos_doubles.py
14.5 Cython
running build_ext
building '_cos_doubles' extension Cython is both a Python-like language for writing C-extensions and an advanced compiler for this language.
The Cython language is a superset of Python, which comes with additional constructs that allow you call C
$ cd advanced/interfacing_with_c/cython
functions and annotate variables and class attributes with c types. In this sense one could also call it a Python $ ls
with types. cos_module.pyx setup.py
In addition to the basic use case of wrapping native code, Cython supports an additional use-case, namely $ python setup.py build_ext --inplace
running build_ext
interactive optimization. Basically, one starts out with a pure-Python script and incrementally adds Cython
cythoning cos_module.pyx to cos_module.c
types to the bottleneck code to optimize only those code paths that really matter.
building 'cos_module' extension
In this sense it is quite similar to SWIG, since the code can be autogenerated but in a sense it also quite similar creating build
to ctypes since the wrapping code can (almost) be written in Python. creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -
While others solutions that autogenerate code can be quite difficult to debug (for example SWIG) Cython ,→fPIC -I/home/esc/anaconda/include/python2.7 -c cos_module.c -o build/temp.linux-x86_64-2.7/
comes with an extension to the GNU debugger that helps debug Python, Cython and C code. ,→cos_module.o
gcc -pthread -shared build/temp.linux-x86_64-2.7/cos_module.o -L/home/esc/anaconda/lib -
,→lpython2.7 -o /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/
Note: The autogenerated C code uses the Python-C-Api. ,→cos_module.so
$ ls
build/ cos_module.c cos_module.pyx cos_module.so* setup.py
Advantages
• Python like language for writing C-extensions And running it:
• Autogenerated code In [1]: import cos_module
• Supports incremental optimization
In [2]: cos_module?
• Includes a GNU debugger extension Type: module
String Form:<module 'cos_module' from 'cos_module.so'>
• Support for C++ (Since version 0.13)
File: /home/esc/git-working/scipy-lecture-notes/advanced/interfacing_with_c/cython/cos_
Disadvantages ,→module.so
Docstring: <no docstring>
• Must be compiled
• Requires an additional library ( but only at build time, at this problem can be overcome by shipping the In [3]: dir(cos_module)
Out[3]:
generated C files)
['__builtins__',
'__doc__',
'__file__',
14.5.1 Example '__name__',
'__package__',
The main Cython code for our cos_module is contained in the file cos_module.pyx: '__test__',
'cos_func']
""" Example of wrapping cos function from math.h using Cython. """
In [4]: cos_module.cos_func(1.0)
cdef extern from "math.h": Out[4]: 0.5403023058681398
double cos(double arg)
In [5]: cos_module.cos_func(0.0)
def cos_func(arg): Out[5]: 1.0
return cos(arg)
In [6]: cos_module.cos_func(3.14159265359)
Note the additional keywords such as cdef and extern. Also the cos_func is then pure Python. Out[6]: -1.0
Again we can use the standard distutils module, but this time we need some additional pieces from the
Cython.Distutils: And, testing a little for robustness, we can see that we get good error messages:
Additionally, it is worth noting that Cython ships with complete declarations for the C math library, which
$ ls
14.5.2 Numpy Support cos_doubles.c cos_doubles.h _cos_doubles.pyx setup.py test_cos_doubles.py
$ python setup.py build_ext -i
Cython has support for Numpy via the numpy.pyx file which allows you to add the Numpy array type to your running build_ext
Cython code. I.e. like specifying that variable i is of type int, you can specify that variable a is of type numpy. cythoning _cos_doubles.pyx to _cos_doubles.c
ndarray with a given dtype. Also, certain optimizations such as bounds checking are supported. Look at the building 'cos_doubles' extension
corresponding section in the Cython documentation. In case you want to pass Numpy arrays as C arrays to creating build
your Cython wrapped C functions, there is a section about this in the Cython wiki. creating build/temp.linux-x86_64-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -
In the following example, we will show how to wrap the familiar cos_doubles function using Cython. ,→fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/
,→anaconda/include/python2.7 -c _cos_doubles.c -o build/temp.linux-x86_64-2.7/_cos_doubles.o
void cos_doubles(double * in_array, double * out_array, int size); In file included from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/
,→ndarraytypes.h:1722,
/* Compute the cosine of each element in in_array, storing the result in from /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/
* out_array. */ ,→arrayobject.h:15,
} /home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include/numpy/__ufunc_api.h:236:␣
} ,→warning: ‘_import_umath’ defined but not used
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -
,→fPIC -I/home/esc/anaconda/lib/python2.7/site-packages/numpy/core/include -I/home/esc/
This is wrapped as cos_doubles_func using the following Cython code:
,→anaconda/include/python2.7 -c cos_doubles.c -o build/temp.linux-x86_64-2.7/cos_doubles.o
""" Example of wrapping a C function that takes C double arrays as input using gcc -pthread -shared build/temp.linux-x86_64-2.7/_cos_doubles.o build/temp.linux-x86_64-2.7/
the Numpy declarations from Cython """ ,→cos_doubles.o -L/home/esc/anaconda/lib -lpython2.7 -o /home/esc/git-working/scipy-lecture-
,→notes/advanced/interfacing_with_c/cython_numpy/cos_doubles.so
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 solu-
tion, 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
14.6 Summary
the correct type, are one dimensional and contiguous in memory.
In this section four different techniques for interfacing with native code have been presented. The table below 14.8.2 Ctypes
roughly summarizes some of the aspects of the techniques.
1. Modify the Numpy example such that cos_doubles_func handles the preallocation for you, thus mak-
ing it more like the Numpy-C-API example.
x Part of CPython Compiled Autogenerated Numpy Support
Python-C-API True True False True
Ctypes True False False True 14.8.3 SWIG
Swig False True True True
Cython False True True True 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 mak-
Of all three presented techniques, Cython is the most modern and advanced. In particular, the ability to opti-
ing it more like the Numpy-C-API example.
mize code incrementally by adding types to your Python code is unique.
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
14.7 Further Reading and References the output array, so it may be possible to construct a Numpy array from the returned double *.)
• Gaël Varoquaux’s blog post about avoiding data copies provides some insight on how to handle memory 14.8.4 Cython
management cleverly. If you ever run into issues with large datasets, this is a reference to come back to
for some inspiration. 1. Look at the code that Cython autogenerates. Take a closer look at some of the comments that Cython
inserts. What do you see?
14.8 Exercises 2. Look at the section Working with Numpy from the Cython documentation to learn how to incrementally
optimize a pure python script that uses Numpy.
3. Modify the Numpy example such that cos_doubles_func handles the preallocation for you, thus mak-
Since this is a brand new section, the exercises are considered more as pointers as to what to look at next, so
ing it more like the Numpy-C-API example.
pick the ones that you find more interesting. If you have good ideas for exercises, please let us know!
1. Download the source code for each example and compile and run them on your machine.
2. Make trivial changes to each example and convince yourself that this works. ( E.g. change cos for sin.)
3. Most of the examples, especially the ones involving Numpy may still be fragile and respond badly to
input errors. Look for ways to crash the examples, figure what the problem is and devise a potential
solution. Here are some ideas:
(a) Numerical overflow.
(b) Input and output arrays that have different lengths.
(c) Multidimensional array.
(d) Empty array
(e) Arrays with non-double types
4. Use the %timeit IPython magic to measure the execution time of the various solutions
This part of the Scipy lecture notes is dedicated to various scientific packages useful for extended needs.
Part III
460 461
Scipy lecture notes, Edition 2017.1
R is a language dedicated to statistics. Python is a general-purpose language with statistics modules. R has
more statistical analysis features than Python, and specialized syntaxes. However, when it comes to building
complex analysis pipelines that mix statistics with e.g. image analysis, text mining, or control of a physical
experiment, the richness of Python is an invaluable asset.
15
Contents
The setting that we consider for statistical analysis is that of multiple observations or samples described by a
set of different attributes or features. The data can than be seen as a 2D table, or matrix, with columns giving
the different attributes of the data, and rows the observations. For instance, the data contained in examples/
brain_size.csv:
Tip: Why Python for statistics?
Creating dataframes: reading data files or converting arrays Other inputs: pandas can input data from SQL, excel files, or other formats. See the pandas documentation.
Separator
The weight of the second individual is missing in the CSV file. If we don’t specify the missing value (NA = >>> # Simpler selector
not available) marker, we will not be able to do statistical analysis. >>> data[data['Gender'] == 'Female']['VIQ'].mean()
109.45
Note: For a quick view on a large dataframe, use its describe method: pandas.DataFrame.describe().
Creating from arrays: A pandas.DataFrame can also be seen as a dictionary of 1D ‘series’, eg arrays or lists. If
we have 3 numpy arrays:
15.1. Data representation and interaction 464 15.1. Data representation and interaction 465
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Plotting data
('Female', 109.45)
('Male', 115.25)
Pandas comes with some plotting tools (pandas.tools.plotting, using matplotlib behind the scene) to dis-
groupby_gender is a powerful object that exposes many operations on the resulting group of dataframes: play statistics of the data in dataframes:
Scatter matrices:
>>> groupby_gender.mean()
Unnamed: 0 FSIQ VIQ PIQ Weight Height MRI_Count >>> from pandas.tools import plotting
Gender >>> plotting.scatter_matrix(data[['Weight', 'Height', 'MRI_Count']])
Female 19.65 111.9 109.45 110.45 137.200000 65.765000 862654.6
Male 21.35 115.0 115.25 111.60 166.444444 71.431579 954855.4
Tip: Use tab-completion on groupby_gender to find more. Other common grouping functions are median,
count (useful for checking to see the amount of missing values in different subsets) or sum. Groupby evalua-
tion is lazy, no work is done until an aggregation function is applied.
Exercise
Two populations
• What is the mean value for VIQ for the full population?
The IQ metrics are bimodal, as if there are 2 sub-populations.
• How many males/females were included in this study?
Hint use ‘tab completion’ to find out the methods that can be called, instead of ‘mean’ in the above
example.
• What is the average value of MRI counts expressed in log units, for males and females?
Note: groupby_gender.boxplot is used for the plots above (see this example).
15.1. Data representation and interaction 466 15.1. Data representation and interaction 467
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
scipy.stats.ttest_1samp() tests if the population mean of data is likely to be equal to a given value (tech-
nically if observations are drawn from a Gaussian distributions of given population mean). It returns the T
statistic, and the p-value (see the function’s help):
Exercise
>>> stats.ttest_1samp(data['VIQ'], 0)
Ttest_1sampResult(statistic=30.088099970..., pvalue=1.32891964...e-28)
Plot the scatter matrix for males only, and for females only. Do you think that the 2 sub-populations corre-
spond to gender?
Tip: With a p-value of 10^-28 we can claim that the population mean for the IQ (VIQ measure) is not 0.
15.2. Hypothesis testing: comparing two groups 468 15.2. Hypothesis testing: comparing two groups 469
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
PIQ, VIQ, and FSIQ give 3 measures of IQ. Let us test if FISQ
15.3 Linear models, multiple factors, and analysis of variance
and PIQ are significantly different. We can use a 2 sample test:
15.3.1 “formulas” to specify statistical models in Python
>>> stats.ttest_ind(data['FSIQ'], data['PIQ'])
Ttest_indResult(statistic=0.46563759638..., pvalue=0.64277250...)
A simple linear regression
The problem with this approach is that it forgets that there are links between observations: FSIQ and PIQ are
measured on the same individuals. Thus the variance due to inter-subject variability is confounding, and can
be removed, using a “paired test”, or “repeated measures test”:
T-tests assume Gaussian errors. We can use a Wilcoxon signed-rank test, that relaxes this assumption:
>>> stats.wilcoxon(data['FSIQ'], data['PIQ']) First, we generate simulated data according to the model:
WilcoxonResult(statistic=274.5, pvalue=0.106594927...)
>>> import numpy as np
>>> x = np.linspace(-5, 5, 20)
Note: The corresponding test in the non paired case is the Mann–Whitney U test, scipy.stats. >>> np.random.seed(1)
>>> # normal distributed noise
mannwhitneyu().
>>> y = -5 + 3*x + 4 * np.random.normal(size=x.shape)
>>> # Create a data frame containing all the relevant variables
>>> data = pandas.DataFrame({'x': x, 'y': y})
15.2. Hypothesis testing: comparing two groups 470 15.3. Linear models, multiple factors, and analysis of variance 471
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
“formulas” for statistics in Python Categorical variables: comparing groups or multiple categories
See the statsmodels documentation Let us go back the data on brain size:
We can write a comparison between IQ of male and female using a linear model:
Exercise
Retrieve the estimated parameters from the model above. Hint: use tab-completion to find the relevent
attribute.
15.3. Linear models, multiple factors, and analysis of variance 472 15.3. Linear models, multiple factors, and analysis of variance 473
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Link to t-tests between different FSIQ and PIQ Such a model can be seen in 3D as fitting a plane to a cloud of (x, y, z) points.
To compare different types of IQ, we need to create a “long-form” table, listing IQs, where the type of IQ is
indicated by a categorical variable:
>>> data_fisq = pandas.DataFrame({'iq': data['FSIQ'], 'type': 'fsiq'})
>>> data_piq = pandas.DataFrame({'iq': data['PIQ'], 'type': 'piq'})
>>> data_long = pandas.concat((data_fisq, data_piq))
>>> print(data_long) Example: the iris data (examples/iris.csv)
iq type
0 133 fsiq
Tip: Sepal and petal size tend to be related: bigger flowers are bigger! But is there in addition a systematic
1 140 fsiq
effect of species?
2 139 fsiq
...
31 137 piq
32 110 piq
33 86 piq
...
We can see that we retrieve the same values for t-test and corresponding p-values for the effect of the type
of iq than the previous t-test:
>>> stats.ttest_ind(data['FSIQ'], data['PIQ'])
Ttest_indResult(statistic=0.46563759638..., pvalue=0.64277250...)
15.3. Linear models, multiple factors, and analysis of variance 474 15.3. Linear models, multiple factors, and analysis of variance 475
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
In the above iris example, we wish to test if the petal length is different between versicolor and virginica, after
removing the effect of sepal width. This can be formulated as testing the difference between the coefficient as-
sociated to versicolor and virginica in the linear model estimated above (it is an Analysis of Variance, ANOVA).
For this, we write a vector of ‘contrast’ on the parameters estimated: we want to test "name[T.versicolor]
- name[T.virginica]", with an F-test:
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.
15.4. More visualization: seaborn for statistical exploration 476 15.4. More visualization: seaborn for statistical exploration 477
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Robust regression
Tip: Given that, in the above plot, there seems to be a couple of data points that are outside of the main
Look and feel and matplotlib settings
cloud to the right, they might be outliers, not representative of the population, but driving the regression.
Seaborn changes the default of matplotlib figures to achieve a more “modern”, “excel-like” look. It does that
upon import. You can reset the default using: To compute a regression that is less sentive to outliers, one must use a robust model. This is done in seaborn
using robust=True in the plotting functions, or in statsmodels by replacing the use of the OLS by a “Robust
>>> from matplotlib import pyplot as plt
>>> plt.rcdefaults() Linear Model”, statsmodels.formula.api.rlm().
Tip: To switch back to seaborn settings, or understand better styling in seaborn, see the relevent section of
the seaborn documentation.
15.4. More visualization: seaborn for statistical exploration 478 15.4. More visualization: seaborn for statistical exploration 479
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Plot boxplots for FSIQ, PIQ, and the paired difference between the two: while the spread (error bars) for FSIQ
and PIQ are very large, there is a systematic (common) effect due to the subjects. This effect is cancelled out
in the difference and the spread of the difference (“paired” by subject) is much smaller than the spread of the
individual measures.
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 to population. This is done via an “interaction”.
Can we conclude that education benefits males more than females? # Boxplot of the difference
plt.figure(figsize=(4, 3))
plt.boxplot(data['FSIQ'] - data['PIQ'])
plt.xticks((1, ), ('FSIQ - PIQ', ))
plt.show()
• Hypothesis testing and p-value give you the significance of an effect / difference Download Python source code: plot_paired_boxplots.py
• Formulas (with categorical variables) enable you to express rich links in your data Download Jupyter notebook: plot_paired_boxplots.ipynb
• Visualizing your data and simple model fits matters! Generated by Sphinx-Gallery
• Conditionning (adding factors that can explain all or part of the variation) is important modeling
aspect that changes the interpretation.
15.5. Testing for interactions 480 15.6. Full code for the figures 481
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
This example loads from a CSV file data with mixed numerical and categorical entries, and plots a few quan-
tities, separately for females and males, thanks to the pandas integrated plotting tool (that uses matplotlib
behind the scene).
See http://pandas.pydata.org/pandas-docs/stable/visualization.html
import pandas
import pandas
from pandas.tools import plotting
15.6. Full code for the figures 482 15.6. Full code for the figures 483
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Testing the difference between effect of versicolor and virginica
<F test: F=array([[ 3.24533535]]), p=0.07369058781700738, df_denom=146, df_num=1>
import numpy as np
import matplotlib.pyplot as plt
Statistical analysis import pandas
# Let us try to explain the sepal length as a function of the petal
# For statistics. Requires statsmodels 5.0 or more
# width and the category of iris
from statsmodels.formula.api import ols
# Analysis of Variance (ANOVA) on linear models
model = ols('sepal_width ~ name + petal_length', data).fit()
from statsmodels.stats.anova import anova_lm
print(model.summary())
# Now formulate a "contrast", to test if the offset for versicolor and Generate and show the data
# virginica are identical
x = np.linspace(-5, 5, 20)
print('Testing the difference between effect of versicolor and virginica')
# To get reproducable values, provide a seed value
print(model.f_test([0, 1, -1, 0]))
np.random.seed(1)
plt.show()
y = -5 + 3*x + 4 * np.random.normal(size=x.shape)
Out:
# Plot the data
OLS Regression Results
plt.figure(figsize=(5, 4))
==============================================================================
plt.plot(x, y, 'o')
Dep. Variable: sepal_width R-squared: 0.478
Model: OLS Adj. R-squared: 0.468
15.6. Full code for the figures 484 15.6. Full code for the figures 485
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
==============================================================================
Omnibus: 0.100 Durbin-Watson: 2.956
Prob(Omnibus): 0.951 Jarque-Bera (JB): 0.322
Skew: -0.058 Prob(JB): 0.851
Kurtosis: 2.390 Cond. No. 3.03
==============================================================================
Warnings:
[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 1588.873443 1588.873443 74.029383 8.560649e-08
Residual 18.0 386.329330 21.462741 NaN NaN
plt.show()
# Convert the data into a Pandas DataFrame to use the formulas framework
# in statsmodels
data = pandas.DataFrame({'x': x, 'y': y})
print('\nANOVA results')
print(anova_results)
Out:
15.6. Full code for the figures 486 15.6. Full code for the figures 487
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Calculate using ‘statsmodels’ just the best fit, or all the corresponding statistical parameters.
Also shows how to make 3d plots.
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)
# Plot the data Multilinear regression model, calculating fit, P-values, confidence intervals etc.
fig = plt.figure()
ax = fig.gca(projection='3d') # Convert the data into a Pandas DataFrame to use the formulas framework
surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, # in statsmodels
rstride=1, cstride=1)
ax.view_init(20, -120) # First we need to flatten the data: it's 2D layout is not relevent.
ax.set_xlabel('X') X = X.flatten()
ax.set_ylabel('Y') Y = Y.flatten()
ax.set_zlabel('Z') Z = Z.flatten()
print('\nANOVA results')
print(anova_results)
plt.show()
Out:
15.6. Full code for the figures 488 15.6. Full code for the figures 489
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
ANOVA results
df sum_sq mean_sq F PR(>F)
x 1.0 39284.301219 39284.301219 623.962799 2.888238e-86
y 1.0 1055.220089 1055.220089 16.760336 5.050899e-05
Residual 438.0 27576.201607 62.959364 NaN NaN
Wages depend mostly on education. Here we investigate how this dependence is related to gender: not only
does gender create an offset in wages, it also seems that wages increase more with education for males than
females.
Does our data support this last hypothesis? We will test this using statsmodels’ formulas (http://statsmodels.
sourceforge.net/stable/example_formulas.html).
Load and massage the data
import pandas
import urllib
import os
15.6. Full code for the figures 490 15.6. Full code for the figures 491
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
15.6. Full code for the figures 492 15.6. Full code for the figures 493
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import seaborn
seaborn.pairplot(data, vars=['WAGE', 'AGE', 'EDUCATION'],
kind='reg')
15.6. Full code for the figures 494 15.6. Full code for the figures 495
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
•
Load the data
Plot a simple regression
import pandas
seaborn.lmplot(y='WAGE', x='EDUCATION', data=data)
if not os.path.exists('airfares.txt'):
plt.show() # Download the file if it is not present
urllib.urlretrieve(
'http://www.stat.ufl.edu/~winner/data/airq4.dat',
'airfares.txt')
15.6. Full code for the figures 496 15.6. Full code for the figures 497
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
import seaborn
seaborn.pairplot(data_flat, vars=['fare', 'dist', 'nb_passengers'],
kind='reg', markers='.')
# A second plot, to show the effect of the year (ie the 9/11 effect)
seaborn.pairplot(data_flat, vars=['fare', 'dist', 'nb_passengers'],
kind='reg', hue='year', markers='.')
•
Plot the difference in fare
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()
•
Statistical testing: dependence of fare on distance and number of passengers
import statsmodels.formula.api as sm
Out:
15.6. Full code for the figures 498 15.6. Full code for the figures 499
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Warnings:
[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 Out:
Scale Est.: mad
Cov Type: H1 OLS Regression Results
Date: Tue, 03 Oct 2017 ==============================================================================
Time: 16:00:28 Dep. Variable: fare_2001 R-squared: 0.159
No. Iterations: 12 Model: OLS Adj. R-squared: 0.159
================================================================================= Method: Least Squares F-statistic: 791.7
coef std err z P>|z| [95.0% Conf. Int.] Date: Tue, 03 Oct 2017 Prob (F-statistic): 1.20e-159
--------------------------------------------------------------------------------- Time: 16:00:28 Log-Likelihood: -22640.
Intercept 215.0848 2.448 87.856 0.000 210.287 219.883 No. Observations: 4176 AIC: 4.528e+04
dist 0.0460 0.001 46.166 0.000 0.044 0.048 Df Residuals: 4174 BIC: 4.530e+04
nb_passengers -35.2686 1.119 -31.526 0.000 -37.461 -33.076 Df Model: 1
================================================================================= Covariance Type: nonrobust
==============================================================================
If the model instance has been used for another fit with different fit coef std err t P>|t| [95.0% Conf. Int.]
parameters, then the fit options might not be the correct ones anymore . ------------------------------------------------------------------------------
Intercept 148.0279 1.673 88.480 0.000 144.748 151.308
Statistical testing: regression of fare on distance: 2001/2000 difference dist 0.0388 0.001 28.136 0.000 0.036 0.041
==============================================================================
result = sm.ols(formula='fare_2001 - fare_2000 ~ 1 + dist', data=data).fit() Omnibus: 136.558 Durbin-Watson: 1.544
print(result.summary()) Prob(Omnibus): 0.000 Jarque-Bera (JB): 149.624
Skew: 0.462 Prob(JB): 3.23e-33
# Plot the corresponding regression Kurtosis: 2.920 Cond. No. 2.40e+03
data['fare_difference'] = data['fare_2001'] - data['fare_2000'] ==============================================================================
seaborn.lmplot(x='dist', y='fare_difference', data=data)
Warnings:
plt.show() [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 2.4e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
15.6. Full code for the figures 500 15.6. Full code for the figures 501
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Download Jupyter notebook: plot_airfare.ipynb Here we plot a scatter matrix to get intuitions on our results. This goes beyond what was asked in the exercise
Generated by Sphinx-Gallery
# This plotting is useful to get an intuitions on the relationships between
# our different variables
15.7.1 Relating Gender and IQ # Fill in the missing values for Height for plotting
data['Height'].fillna(method='pad', inplace=True)
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. # The parameter 'c' is passed to plt.scatter and will control the color
# The same holds for parameters 'marker', 'alpha' and 'cmap', that
Notice that here ‘Gender’ is a categorical value. As it is a non-float data type, statsmodels is able to automati- # control respectively the type of marker used, their transparency and
cally infer this. # the colormap
plotting.scatter_matrix(data[['VIQ', 'MRI_Count', 'Height']],
import pandas c=(data['Gender'] == 'Female'), marker='o',
from statsmodels.formula.api import ols alpha=1, cmap='winter')
data = pandas.read_csv('../brain_size.csv', sep=';', na_values='.') fig = plt.gcf()
fig.suptitle("blue: male, green: female", size=13)
model = ols('VIQ ~ Gender + MRI_Count + Height', data).fit()
print(model.summary()) plt.show()
# Here, we don't need to define a contrast, as we are testing a single
# coefficient of our model, and not a combination of coefficients.
# However, defining a contrast, which would then be a 'unit contrast',
# will give us the same results
print(model.f_test([0, 1, 0, 0]))
Out:
15.7. Solutions to this chapter’s exercises 502 15.7. Solutions to this chapter’s exercises 503
Scipy lecture notes, Edition 2017.1
Generated by Sphinx-Gallery
Download all examples in Python source code: auto_examples_python.zip
Download all examples in Jupyter notebooks: auto_examples_jupyter.zip
Generated by Sphinx-Gallery
CHAPTER 16
Sympy : Symbolic Mathematics in
Python
Objectives
What is SymPy? SymPy is a Python library for symbolic mathematics. It aims to be an alternative to systems
such as Mathematica or Maple while keeping the code as simple as possible and easily extensible. SymPy is
written entirely in Python and does not require any external libraries.
Sympy documentation and packages for installation can be found on http://www.sympy.org/
Chapters contents
• Algebraic manipulations
Exercises
– Expand
p
– Simplify 1. Calculate 2 with 100 decimals.
– Limits
– Differentiation
16.1.2 Symbols
– Series expansion
In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly:
– Integration
• Equation solving >>> x = sym.Symbol('x')
>>> y = sym.Symbol('y')
• Linear Algebra
– Matrices Then you can manipulate them:
>>> (x + y) ** 2
(x + y)**2
16.1 First Steps with SymPy
Symbols can now be manipulated using some of python operators: +, -`, ``*, ** (arithmetic), &, |, ~ , >>, <<
16.1.1 Using SymPy as a calculator (boolean).
SymPy defines three numerical types: Real, Rational and Integer. Printing
The Rational class represents a rational number as a pair of two Integers: the numerator and the denominator,
Sympy allows for control of the display of the output. From here we use the following setting for printing:
so Rational(1, 2) represents 1/2, Rational(5, 2) 5/2 and so on:
>>> sym.init_printing(use_unicode=False, wrap_line=True)
>>> import sympy as sym
>>> a = sym.Rational(1, 2)
>>> a
1/2 16.2 Algebraic manipulations
>>> a*2
1 SymPy is capable of performing powerful algebraic manipulations. We’ll take a look into some of the most
frequently used: expand and simplify.
SymPy uses mpmath in the background, which makes it possible to perform computations using arbitrary-
precision arithmetic. That way, some special constants, like e, pi , oo (Infinity), are treated as symbols and can
be evaluated with arbitrary precision: 16.2.1 Expand
>>> sym.pi**2 Use this to expand an algebraic expression. It will try to denest powers and multiplications:
pi**2
>>> sym.expand((x + y) ** 3)
>>> sym.pi.evalf() 3 2 2 3
3.14159265358979 x + 3*x *y + 3*x*y + y
>>> 3 * x * y ** 2 + 3 * y * x ** 2 + x ** 3 + y ** 3
>>> (sym.pi + sym.exp(1)).evalf() 3 2 2 3
5.85987448204884 x + 3*x *y + 3*x*y + y
as you see, evalf evaluates the expression to a floating-point number. Further options can be given in form on keywords:
There is also a class representing mathematical infinity, called oo: >>> sym.expand(x + y, complex=True)
re(x) + re(y) + I*im(x) + I*im(y)
>>> sym.oo > 99999 >>> sym.I * sym.im(x) + sym.I * sym.im(y) + sym.re(x) + sym.re(y)
True re(x) + re(y) + I*im(x) + I*im(y)
>>> sym.oo + 1
oo >>> sym.expand(sym.cos(x + y), trig=True)
16.1. First Steps with SymPy 506 16.2. Algebraic manipulations 507
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
16.2.2 Simplify Higher derivatives can be calculated using the diff(func, var, n) method:
Exercises
16.3.3 Series expansion
1. Calculate the expanded form of (x + y)6 .
2. Simplify the trigonometric expression sin(x)/ cos(x) SymPy also knows how to compute the Taylor series of an expression at a point. Use series(expr, var):
>>> sym.series(sym.cos(x), x)
2 4
x x / 6\
16.3 Calculus 1 - -- + -- + O\x /
2 24
>>> sym.series(1/sym.cos(x), x)
16.3.1 Limits 2 4
x 5*x / 6\
Limits are easy to use in SymPy, they follow the syntax limit(function, variable, point), so to compute 1 + -- + ---- + O\x /
the limit of f (x) as x → 0, you would issue limit(f, x, 0): 2 24
>>> sym.limit(sym.sin(x) / x, x, 0)
1 Exercises
you can also calculate the limit at infinity: 1. Calculate limx→0 sin(x)/x
>>> sym.limit(x, x, sym.oo) 2. Calculate the derivative of l og (x) for x.
oo
SymPy is also able to solve boolean equations, that is, to decide if a certain boolean expression is satisfiable or
>>> sym.integrate(sym.exp(-x ** 2) * sym.erf(x), x)
____ 2 not. For this, we use the function satisfiable:
\/ pi *erf (x)
>>> sym.satisfiable(x & y)
--------------
{x: True, y: True}
4
This tells us that (x & y) is True whenever x and y are both True. If an expression cannot be true, i.e. no
It is possible to compute definite integral:
values of its arguments can make the expression True, it will return False:
>>> sym.integrate(x**3, (x, -1, 1))
>>> sym.satisfiable(x & ~x)
0
False
>>> sym.integrate(sym.sin(x), (x, 0, sym.pi / 2))
1
>>> sym.integrate(sym.cos(x), (x, -sym.pi / 2, sym.pi / 2))
2 Exercises
Also improper integrals are supported as well: 1. Solve the system of equations x + y = 2, 2 · x + y = 0
>>> sym.integrate(sym.exp(-x), (x, 0, sym.oo)) 2. Are there boolean values x, y that make (~x | y) & (~y | x) true?
1
>>> sym.integrate(sym.exp(-x ** 2), (x, -sym.oo, sym.oo))
____
\/ pi 16.5 Linear Algebra
16.5.1 Matrices
16.4 Equation solving
Matrices are created as instances from the Matrix class:
SymPy is able to solve algebraic equations, in one and several variables using solveset(): >>> sym.Matrix([[1, 0], [0, 1]])
[1 0]
>>> sym.solveset(x ** 4 - 1, x)
[ ]
{-1, 1, -I, I}
[0 1]
As you can see it takes as first argument an expression that is supposed to be equaled to 0. It also has (limited)
unlike a NumPy array, you can also put Symbols in it:
support for transcendental equations:
>>> x, y = sym.symbols('x, y')
>>> sym.solveset(sym.exp(x) + 1, x)
>>> A = sym.Matrix([[1, x], [y, 1]])
{I*(2*n*pi + pi) | n in Integers()}
>>> A
[1 x]
[ ]
Systems of linear equations [y 1]
Sympy is able to solve a large part of polynomial equations, and is also capable of solving multiple equa- >>> A**2
tions with respect to multiple variables giving a tuple as second argument. To do this you use the solve() [x*y + 1 2*x ]
command: [ ]
[ 2*y x*y + 1]
>>> solution = sym.solve((x + 5 * y - 2, -3 * x + 6 * y - 15), (x, y))
>>> solution[x], solution[y]
Another alternative in the case of polynomial equations is factor. factor returns the polynomial factorized into SymPy is capable of solving (some) Ordinary Differential. To solve differential equations, use dsolve. First,
irreducible terms, and is capable of computing the factorization over various domains: create an undefined function by passing cls=Function to the symbols function:
2
d
f(x) + ---(f(x))
2
dx
17
>>> sym.dsolve(f(x).diff(x, x) + f(x), f(x))
f(x) = C1*sin(x) + C2*cos(x)
Keyword arguments can be given to this function in order to help if find the best possible resolution system.
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:
CHAPTER
>>> sym.dsolve(sym.sin(x) * sym.cos(f(x)) + sym.cos(x) * sym.sin(f(x)) * f(x).diff(x), f(x),␣
,→hint='separable')
/ _________________\ / ________________
| / C1 | | / C1
[f(x) = - asin| / ----------- + 1 | + pi, f(x) = asin| / ----------- + 1
| / 2 | | / 2
\\/ sin (x) - 1 / \\/ sin (x) - 1
___\
|
1 |]
|
/ Author: Emmanuelle Gouillart
scikit-image is a Python package dedicated to image processing, and using natively NumPy arrays as image
objects. This chapter describes how to use scikit-image on various image processing tasks, and insists on
Exercises the link with other scientific Python modules such as NumPy and SciPy.
Chapters contents
Images are NumPy’s arrays np.ndarray Other Python packages are available for image processing and work with NumPy arrays:
image np.ndarray • scipy.ndimage : for nd-arrays. Basic filtering, mathematical morphology, regions properties
channels array dimensions Also, powerful image processing libraries have Python bindings:
filters functions (numpy, skimage, scipy) • ITK (3D images and registration)
• and many others
>>> import numpy as np
>>> check = np.zeros((9, 9)) (but they are less Pythonic and NumPy friendly, to a variable extent).
>>> check[::2, 1::2] = 1
>>> check[1::2, ::2] = 1
>>> import matplotlib.pyplot as plt 17.1.2 What’s to be found in scikit-image
>>> plt.imshow(check, cmap='gray', interpolation='nearest')
• Website: http://scikit-image.org/
• Gallery of examples: http://scikit-image.org/docs/stable/auto_examples/
Different kinds of functions, from boilerplate utility functions to high-level recent algorithms.
• Filters: functions transforming images into other images.
– NumPy machinery
– Common filtering algorithms
• Data reduction functions: computation of image histogram, position of local maxima, of corners, etc.
• Other actions: I/O, visualization, etc.
>>> import os
>>> filename = os.path.join(skimage.data_dir, 'camera.png')
>>> camera = io.imread(filename)
17.1. Introduction and concepts 514 17.2. Input/output, data types and colorspaces 515
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Some image processing routines need to work with float arrays, and may hence output an array with a different
type and the data range from the input array
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.
Works with all data formats supported by the Python 17.2.2 Colorspaces
Imaging Library (or any other I/O plugin provided to imread with the plugin keyword argument).
Also works with URL image paths: Color images are of shape (N, M, 3) or (N, M, 4) (when an alpha channel encodes transparency)
>>> io.imsave('local_logo.png', logo) Routines converting between different colorspaces (RGB, HSV, LAB etc.) are available in skimage.color :
color.rgb2hsv, color.lab2rgb, etc. Check the docstring for the expected dtype (and data range) of input
(imsave also uses an external plugin such as PIL) images.
3D images
17.2.1 Data types
Most functions of skimage can take 3D images as input arguments. Check the docstring to know if a func-
tion can be used on 3D images (for example MRI or CT images).
Exercise
17.2. Input/output, data types and colorspaces 516 17.3. Image preprocessing / enhancement 517
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Neighbourhood: square (choose size), disk, or more complicated structuring element. Default structuring element: 4-connectivity of a pixel
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 ele-
ment.:
17.3. Image preprocessing / enhancement 518 17.3. Image preprocessing / enhancement 519
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Mathematical morphology operations are also available for (non-binary) grayscale images (int or float type).
Erosion and dilation correspond to minimum (resp. maximum) filters.
>>> n = 20
>>> l = 256
>>> im = np.zeros((l, l))
>>> points = l * np.random.random((2, n ** 2))
>>> im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
>>> im = filters.gaussian(im, sigma=l / (4. * n))
>>> blobs = im > im.mean()
>>> from skimage import measure >>> from skimage import segmentation
>>> all_labels = measure.label(blobs) >>> # Transform markers image so that 0-valued pixels are to
>>> # be labelled, and -1-valued pixels represent background
Label only foreground connected components: >>> markers[~image] = -1
>>> labels_rw = segmentation.random_walker(image, markers)
>>> blobs_labels = measure.label(blobs, background=0)
skimage provides several utility functions that can be used on label images (ie images where
See also: different discrete values identify different regions). Functions names are often self-explaining:
skimage.segmentation.clear_border(), skimage.segmentation.relabel_from_one(), skimage.
scipy.ndimage.find_objects() is useful to return slices on object in an image. morphology.remove_small_objects(), etc.
Watershed segmentation • Separate the coins from the background by testing several segmentation methods: Otsu thresholding,
adaptive thresholding, and watershed or random walker segmentation.
The Watershed (skimage.morphology.watershed()) is a region-growing approach that fills “basins” in the • If necessary, use a postprocessing function to improve the coins / background segmentation.
image
Exercise (continued)
Random walker segmentation
• Use the binary image of the coins and background from the previous exercise.
The random walker algorithm (skimage.segmentation.random_walker()) is similar to the Watershed, but
• Compute an image of labels for the different coins.
with a more “probabilistic” approach. It is based on the idea of the diffusion of labels in the image:
• Compute the size and eccentricity of all coins. >>> new_viewer = viewer.ImageViewer(coins)
>>> from skimage.viewer.plugins import lineprofile
>>> new_viewer += lineprofile.LineProfile()
>>> new_viewer.show()
17.6 Data visualization and interaction
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> plt.imshow(clean_border, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
Visualize contour
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> plt.imshow(coins, cmap='gray')
<matplotlib.image.AxesImage object at 0x...>
>>> plt.contour(clean_border, [0.5])
<matplotlib.contour.QuadContourSet ...>
The (ex-
perimental) scikit-image viewer
skimage.viewer = matplotlib-based canvas for displaying images + experimental Qt-based GUI-toolkit
Useful for displaying pixel values. 17.7 Feature extraction for computer vision
For more interaction, plugins can be added to the viewer:
Geometric or textural descriptor can be extracted from images in order to
17.6. Data visualization and interaction 524 17.7. Feature extraction for computer vision 525
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• classify parts of the image (e.g. sky vs. buildings) This examples show how to create a simple checkerboard.
• match parts of different images (e.g. for object detection)
• and many other applications of Computer Vision
import numpy as np
import matplotlib.pyplot as plt
17.8. Full code examples 526 17.9. Examples for the scikit-image chapter 527
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
camera = data.camera()
camera_multiply = 3 * camera
Total running time of the script: ( 0 minutes 0.062 seconds) Download Python source code: plot_camera_uint.py
Download Python source code: plot_camera.py Download Jupyter notebook: plot_camera_uint.ipynb
Download Jupyter notebook: plot_camera.ipynb Generated by Sphinx-Gallery
Generated by Sphinx-Gallery
17.9.4 Computing horizontal gradients with the Sobel filter
17.9.3 Integers can overflow This example illustrates the use of the horizontal Sobel filter, to compute horizontal gradients.
17.9. Examples for the scikit-image chapter 528 17.9. Examples for the scikit-image chapter 529
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
coins = data.coins()
mask = coins > filters.threshold_otsu(coins)
clean_border = segmentation.clear_border(mask).astype(np.int)
plt.figure(figsize=(8, 3.5))
plt.subplot(121)
plt.imshow(clean_border, cmap='gray')
plt.axis('off')
from skimage import data, exposure
plt.subplot(122)
import matplotlib.pyplot as plt
plt.imshow(coins_edges)
plt.axis('off')
camera = data.camera()
camera_equalized = exposure.equalize_hist(camera)
plt.tight_layout()
plt.show()
plt.figure(figsize=(7, 3))
17.9. Examples for the scikit-image chapter 530 17.9. Examples for the scikit-image chapter 531
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
n = 12
import matplotlib.pyplot as plt l = 256
from skimage import data np.random.seed(1)
from skimage import filters im = np.zeros((l, l))
from skimage import exposure points = l * np.random.random((2, n ** 2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
camera = data.camera() im = filters.gaussian_filter(im, sigma= l / (4. * n))
val = filters.threshold_otsu(camera) blobs = im > 0.7 * im.mean()
17.9. Examples for the scikit-image chapter 532 17.9. Examples for the scikit-image chapter 533
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
This example compares several denoising filters available in scikit-image: a Gaussian filter, a median filter, and
total variation denoising.
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import filters
from skimage import restoration
coins = data.coins()
gaussian_filter_coins = filters.gaussian(coins, sigma=2)
med_filter_coins = filters.median(coins, np.ones((3, 3)))
tv_filter_coins = restoration.denoise_tv_chambolle(coins, weight=0.1)
plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest')
plt.axis('off')
plt.title('Image')
from matplotlib import pyplot as plt
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap='gray',
from skimage import data
interpolation='nearest')
from skimage.feature import corner_harris, corner_subpix, corner_peaks
plt.axis('off')
from skimage.transform import warp, AffineTransform
plt.title('Gaussian filter')
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370], cmap='gray',
tform = AffineTransform(scale=(1.3, 1.1), rotation=1, shear=0.7,
interpolation='nearest')
translation=(210, 50))
plt.axis('off')
image = warp(data.checkerboard(), tform.inverse, output_shape=(350, 350))
plt.title('Median filter')
plt.subplot(144)
coords = corner_peaks(corner_harris(image), min_distance=5)
plt.imshow(tv_filter_coins[10:80, 300:370], cmap='gray',
coords_subpix = corner_subpix(image, coords, window_size=13)
interpolation='nearest')
plt.axis('off')
plt.gray()
plt.title('TV filter')
plt.imshow(image, interpolation='nearest')
plt.show()
plt.plot(coords_subpix[:, 1], coords_subpix[:, 0], '+r', markersize=15, mew=5)
plt.plot(coords[:, 1], coords[:, 0], '.b', markersize=7)
plt.axis('off') Total running time of the script: ( 0 minutes 0.285 seconds)
plt.show() Download Python source code: plot_filter_coins.py
Total running time of the script: ( 0 minutes 0.072 seconds) Download Jupyter notebook: plot_filter_coins.ipynb
This example compares two segmentation methods in order to separate two connected disks: the watershed
algorithm, and the random walker algorithm.
17.9. Examples for the scikit-image chapter 534 17.9. Examples for the scikit-image chapter 535
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Both segmentation methods require seeds, that are pixels belonging unambigusouly to a reagion. Here, local Total running time of the script: ( 0 minutes 0.250 seconds)
maxima of the distance map to the background are used as seeds.
Download Python source code: plot_segmentations.py
Download Jupyter notebook: plot_segmentations.ipynb
Generated by Sphinx-Gallery
Download all examples in Python source code: auto_examples_python.zip
Download all examples in Jupyter notebooks: auto_examples_jupyter.zip
Generated by Sphinx-Gallery
import numpy as np
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from skimage import measure
from skimage.segmentation import random_walker
import matplotlib.pyplot as plt
from scipy import ndimage
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='spectral', interpolation='nearest')
plt.axis('off')
plt.title('watershed segmentation')
plt.subplot(144)
plt.imshow(labels_rw, cmap='spectral', interpolation='nearest')
plt.axis('off')
plt.title('random walker segmentation')
plt.tight_layout()
plt.show()
17.9. Examples for the scikit-image chapter 536 17.9. Examples for the scikit-image chapter 537
Scipy lecture notes, Edition 2017.1
Tutorial content
• Introduction
• Example
18
• What are Traits
– Initialisation
– Validation
– Documentation
18.1 Introduction
Traits: building interactive dialogs
Tip: The Enthought Tool Suite enable the construction of sophisticated application frameworks for data anal-
ysis, 2D plotting and 3D visualization. These powerful, reusable components are released under liberal BSD-
style licenses.
Tip: In this tutorial we will explore the Traits toolset and learn how to dramatically reduce the amount of
boilerplate code you write, do rapid GUI application development, and understand the ideas which underly
other parts of the Enthought Tool Suite.
Traits and the Enthought Tool Suite are open source projects licensed under a BSD-style license.
Intended Audience
Requirements
18.2 Example A class can freely mix trait-based attributes with normal Python attributes, or can opt to allow the use of only
a fixed or open set of trait attributes within the class. Trait attributes defined by a class are automatically
inherited by any subclass derived from the class.
Throughout this tutorial, we will use an example based on a water resource management simple case. We will
try to model a dam and reservoir system. The reservoir and the dams do have a set of parameters : The common way of creating a traits class is by extending from the HasTraits base class and defining class
traits :
• Name
from traits.api import HasTraits, Str, Float
• Minimal and maximal capacity of the reservoir [hm3]
• Height and length of the dam [m] class Reservoir(HasTraits):
• Efficiency of the turbines If using Traits 3.x, you need to adapt the namespace of the traits packages:
The reservoir has a known behaviour. One part is related to the energy production based on the water released. • traits.api should be enthought.traits.api
A simple formula for approximating electric power production at a hydroelectric plant is P = ρhr g k, where: • traitsui.api should be enthought.traits.ui.api
• P is Power in watts,
• ρ is the density of water (~1000 kg/m3), Using a traits class like that is as simple as any other Python class. Note that the trait value are passed using
keyword arguments:
• h is height in meters,
reservoir = Reservoir(name='Lac de Vouglans', max_storage=605)
• r is flow rate in cubic meters per second,
• g is acceleration due to gravity of 9.8 m/s2,
• k is a coefficient of efficiency ranging from 0 to 1. 18.3.1 Initialisation
All the traits do have a default value that initialise the variables. For example, the basic python types do have
Tip: Annual electric energy production depends on the available water supply. In some installations the water
the following trait equivalents:
flow rate can vary by a factor of 10:1 over the course of a year.
18.3 What are Traits A number of other predefined trait type do exist : Array, Enum, Range, Event, Dict, List, Color, Set, Expression,
Code, Callable, Type, Tuple, etc.
A trait is a type definition that can be used for normal Python object attributes, giving the attributes some Custom default values can be defined in the code:
additional characteristics: from traits.api import HasTraits, Str, Float
• Standardization:
class Reservoir(HasTraits):
name = Str
name = Str max_storage = Float(100, desc='Maximal storage [hm3]')
max_storage = Float(100)
Let’s now define the complete reservoir class:
reservoir = Reservoir(name='Lac de Vouglans')
from traits.api import HasTraits, Str, Float, Range
18.3.2 Validation
if __name__ == '__main__':
Every trait does validation when the user tries to set its content: reservoir = Reservoir(
name = 'Project A',
reservoir = Reservoir(name='Lac de Vouglans', max_storage=605) max_storage = 30,
max_release = 100.0,
reservoir.max_storage = '230' head = 60,
--------------------------------------------------------------------------- efficiency = 0.8
TraitError Traceback (most recent call last) )
.../scipy-lecture-notes/advanced/traits/<ipython-input-7-979bdff9974a> in <module>()
----> 1 reservoir.max_storage = '230' release = 80
print 'Releasing {} m3/s produces {} kWh'.format(
.../traits/trait_handlers.pyc in error(self, object, name, value) release, reservoir.energy_production(release)
166 """ )
167 raise TraitError( object, name, self.full_info( object, name, value ),
--> 168 value )
169
170 def arg_error ( self, method, arg_num, object, name, value ): 18.3.4 Visualization: opening a dialog
TraitError: The 'max_storage' trait of a Reservoir instance must be a float, but a value of '23 The Traits library is also aware of user interfaces and can pop up a default view for the Reservoir class:
,→' <type 'str'> was specified.
reservoir1 = Reservoir()
reservoir1.edit_traits()
18.3.3 Documentation
By essence, all the traits do provide documentation about the model itself. The declarative approach to the
creation of classes makes it self-descriptive:
class Reservoir(HasTraits):
name = Str
max_storage = Float(100)
The desc metadata of the traits can be used to provide a more descriptive information about the trait :
class Reservoir(HasTraits):
18.3. What are Traits 542 18.3. What are Traits 543
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
TraitsUI simplifies the way user interfaces are created. Every trait on a HasTraits class has a default editor that
class ReservoirState(HasTraits):
will manage the way the trait is rendered to the screen (e.g. the Range trait is displayed as a slider, etc.). """Keeps track of the reservoir state given the initial storage.
In the very same vein as the Traits declarative way of creating classes, TraitsUI provides a declarative interface """
to build user interfaces code: reservoir = Instance(Reservoir, ())
min_storage = Float
from traits.api import HasTraits, Str, Float, Range max_storage = DelegatesTo('reservoir')
from traitsui.api import View min_release = Float
max_release = DelegatesTo('reservoir')
class Reservoir(HasTraits):
name = Str # state attributes
max_storage = Float(1e6, desc='Maximal storage [hm3]') storage = Range(low='min_storage', high='max_storage')
max_release = Float(10, desc='Maximal release [m3/s]')
head = Float(10, desc='Hydraulic head [m]') # control attributes
efficiency = Range(0, 1.) inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
traits_view = View( spillage = Float(desc='Spillage [hm3]')
'name', 'max_storage', 'max_release', 'head', 'efficiency',
title = 'Reservoir', def print_state(self):
resizable = True, print 'Storage\tRelease\tInflows\tSpillage'
) str_format = '\t'.join(['{:7.2f} 'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
def energy_production(self, release): self.spillage)
''' Returns the energy production [Wh] for the given release [m3/s] print '-' * 79
'''
power = 1000 * 9.81 * self.head * release * self.efficiency
return power * 3600 if __name__ == '__main__':
projectA = Reservoir(
name = 'Project A',
if __name__ == '__main__': max_storage = 30,
reservoir = Reservoir( max_release = 100.0,
name = 'Project A', hydraulic_head = 60,
max_storage = 30, efficiency = 0.8
max_release = 100.0, )
head = 60,
efficiency = 0.8 state = ReservoirState(reservoir=projectA, storage=10)
) state.release = 90
state.inflows = 0
reservoir.configure_traits() state.print_state()
A special trait allows to manage events and trigger function calls using the magic _xxxx_fired method:
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage.
from traits.api import HasTraits, Instance, DelegatesTo, Float, Range # state attributes
storage = Range(low='min_storage', high='max_storage')
from reservoir import Reservoir
# control attributes
18.3. What are Traits 544 18.3. What are Traits 545
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
18.3. What are Traits 546 18.3. What are Traits 547
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
hydraulic_head = 60,
from reservoir import Reservoir efficiency = 0.8
)
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage. state = ReservoirState(reservoir=projectA, storage=25)
state.release = 4
For the simplicity of the example, the release is considered in state.inflows = 0
hm3/timestep and not in m3/s.
""" state.print_state()
reservoir = Instance(Reservoir, ()) state.configure_traits()
name = DelegatesTo('reservoir')
max_storage = DelegatesTo('reservoir')
max_release = DelegatesTo('reservoir')
min_release = Float
# state attributes
storage = Property(depends_on='inflows, release')
# control attributes
inflows = Float(desc='Inflows [hm3]')
release = Range(low='min_release', high='max_release')
spillage = Property(
desc='Spillage [hm3]', depends_on=['storage', 'inflows', 'release']
)
def print_state(self):
if __name__ == '__main__':
print 'Storage\tRelease\tInflows\tSpillage'
turbine = Turbine(turbine_type='type1', power=5.0)
str_format = '\t'.join(['{:7.2f} 'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
reservoir = Reservoir(
self.spillage)
name = 'Project A',
print '-' * 79
max_storage = 30,
max_release = 100.0,
if __name__ == '__main__':
head = 60,
projectA = Reservoir(
efficiency = 0.8,
name = 'Project A',
turbine = turbine,
max_storage = 30,
)
max_release = 5,
18.3. What are Traits 548 18.3. What are Traits 549
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
if __name__ == '__main__':
print 'installed capacity is initialised with turbine.power' projectA = Reservoir(
print reservoir.installed_capacity name = 'Project A',
max_storage = 30,
print '-' * 15 max_release = 100.0,
print 'updating the turbine power updates the installed capacity' hydraulic_head = 60,
turbine.power = 10 efficiency = 0.8
print reservoir.installed_capacity )
class ReservoirState(HasTraits): In many situations, you do not know in advance what type of listeners need to be activated. Traits offers the
"""Keeps track of the reservoir state given the initial storage. ability to register listeners on the fly with the dynamic listeners
"""
reservoir = Instance(Reservoir, ()) from reservoir import Reservoir
min_storage = Float from reservoir_state_property import ReservoirState
max_storage = DelegatesTo('reservoir')
min_release = Float def wake_up_watchman_if_spillage(new_value):
max_release = DelegatesTo('reservoir') if new_value > 0:
print 'Wake up watchman! Spilling {} hm3'.format(new_value)
# state attributes
storage = Range(low='min_storage', high='max_storage') if __name__ == '__main__':
projectA = Reservoir(
# control attributes name = 'Project A',
inflows = Float(desc='Inflows [hm3]') max_storage = 30,
release = Range(low='min_release', high='max_release') max_release = 100.0,
spillage = Float(desc='Spillage [hm3]') hydraulic_head = 60,
efficiency = 0.8
def print_state(self): )
print 'Storage\tRelease\tInflows\tSpillage'
str_format = '\t'.join(['{:7.2f} 'for i in range(4)]) state = ReservoirState(reservoir=projectA, storage=10)
print str_format.format(self.storage, self.release, self.inflows,
self.spillage) #register the dynamic listener
print '-' * 79 state.on_trait_change(wake_up_watchman_if_spillage, name='spillage')
18.3. What are Traits 550 18.3. What are Traits 551
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
The dynamic trait notification signatures are not the same as the static ones :
print 'Storage\tRelease\tInflows\tSpillage'
• def wake_up_watchman(): pass str_format = '\t'.join(['{:7.2f} 'for i in range(4)])
print str_format.format(self.storage, self.release, self.inflows,
• def wake_up_watchman(new): pass self.spillage)
print '-' * 79
• def wake_up_watchman(name, new): pass
• def wake_up_watchman(object, name, new): pass if __name__ == '__main__':
projectA = Reservoir(
• def wake_up_watchman(object, name, old, new): pass name = 'Project A',
Removing a dynamic listener can be done by: max_storage = 30,
max_release = 5,
• calling the remove_trait_listener method on the trait with the listener method as argument, hydraulic_head = 60,
efficiency = 0.8
• calling the on_trait_change method with listener method and the keyword remove=True, )
• deleting the instance that holds the listener.
state = ReservoirState(reservoir=projectA, storage=25)
Listeners can also be added to classes using the on_trait_change decorator: state.release = 4
state.inflows = 0
from traits.api import HasTraits, Instance, DelegatesTo, Float, Range
from traits.api import Property, on_trait_change
The patterns supported by the on_trait_change method and decorator are powerful. The reader should look at
from reservoir import Reservoir the docstring of HasTraits.on_trait_change for the details.
class ReservoirState(HasTraits):
"""Keeps track of the reservoir state given the initial storage. 18.3.7 Some more advanced traits
For the simplicity of the example, the release is considered in The following example demonstrate the usage of the Enum and List traits :
hm3/timestep and not in m3/s.
""" from traits.api import HasTraits, Str, Float, Range, Enum, List
reservoir = Instance(Reservoir, ()) from traitsui.api import View, Item
max_storage = DelegatesTo('reservoir')
min_release = Float class IrrigationArea(HasTraits):
max_release = DelegatesTo('reservoir') name = Str
surface = Float(desc='Surface [ha]')
# state attributes crop = Enum('Alfalfa', 'Wheat', 'Cotton')
storage = Property(depends_on='inflows, release')
18.3. What are Traits 552 18.3. What are Traits 553
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
reservoir = Reservoir(
reservoir = Reservoir( name='Project A',
name='Project A', max_storage=30,
max_storage=30, max_release=100.0,
max_release=100.0, head=60,
head=60, efficiency=0.8,
efficiency=0.8, irrigated_areas=[upper_block],
irrigated_areas=[upper_block] )
)
release = 80
release = 80 print 'Releasing {} m3/s produces {} kWh'.format(
print 'Releasing {} m3/s produces {} kWh'.format( release, reservoir.energy_production(release)
release, reservoir.energy_production(release) )
)
The next example shows how the Array trait can be used to feed a specialised TraitsUI Item, the ChacoPlotItem:
Trait listeners can be used to listen to changes in the content of the list to e.g. keep track of the total crop
surface on linked to a given reservoir. import numpy as np
from traits.api import HasTraits, Str, Float, Range, Enum, List, Property from traits.api import HasTraits, Array, Instance, Float, Property
from traitsui.api import View, Item from traits.api import DelegatesTo
from traitsui.api import View, Item, Group
class IrrigationArea(HasTraits): from chaco.chaco_plot_editor import ChacoPlotItem
name = Str
surface = Float(desc='Surface [ha]') from reservoir import Reservoir
crop = Enum('Alfalfa', 'Wheat', 'Cotton')
class ReservoirEvolution(HasTraits):
class Reservoir(HasTraits): reservoir = Instance(Reservoir)
name = Str
max_storage = Float(1e6, desc='Maximal storage [hm3]') name = DelegatesTo('reservoir')
max_release = Float(10, desc='Maximal release [m3/s]')
head = Float(10, desc='Hydraulic head [m]') inflows = Array(dtype=np.float64, shape=(None))
efficiency = Range(0, 1.) releass = Array(dtype=np.float64, shape=(None))
18.3. What are Traits 554 18.3. What are Traits 555
Scipy lecture notes, Edition 2017.1
max_release = 100.0,
head = 60,
efficiency = 0.8
)
19
initial_stock = 10.
inflows_ts = np.array([6., 6, 4, 4, 1, 2, 0, 0, 3, 1, 5, 3])
releases_ts = np.array([4., 5, 3, 5, 3, 5, 5, 3, 2, 1, 3, 3])
view = ReservoirEvolution(
reservoir = reservoir,
inflows = inflows_ts,
releases = releases_ts CHAPTER
)
view.configure_traits()
Tip: Mayavi is an interactive 3D plotting package. matplotlib can also do simple 3D plotting, but Mayavi relies
on a more powerful engine ( VTK ) and is more suited to displaying large or complex data.
See also:
References
Chapters contents
• ETS repositories
• Mlab: the scripting interface
• Traits manual
– 3D plotting functions
• Traits UI manual
* Points
• Mailing list : enthought-dev@enthought.com
* Lines
* Elevation surface
* Arbitrary regular mesh
* Volumetric data
– Figures and decorations
* Figure management
* Changing plot properties
* Decorations
• Interactive work
– The “pipeline dialog”
The mayavi.mlab module provides simple plotting functions to apply to numpy arrays, similar to matplotlib
Elevation surface
or matlab’s plotting interface. Try using them in IPython, by starting IPython with the switch --gui=wx.
Points
mlab.clf()
x, y = np.mgrid[-10:10:100j, -10:10:100j]
r = np.sqrt(x**2 + y**2)
z = np.sin(r)/r
Hint: Points in 3D, represented with markers (or “glyphs”) and optionaly different sizes. mlab.surf(z, warp_scale='auto')
19.1. Mlab: the scripting interface 558 19.1. Mlab: the scripting interface 559
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
This function works with a regular orthogonal grid: the value array is a 3D array that gives the shape of the
Hint: A surface mesh given by x, y, z positions of its node points grid.
Note: A surface is defined by points connected to form triangles or polygones. In mayavi.mlab.surf() and Get the current figure: mlab.gcf()
mayavi.mlab.mesh(), the connectivity is implicity given by the layout of the arrays. See also mayavi.mlab. Clear the current figure: mlab.clf()
triangular_mesh(). Set the current figure: mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5)
Save figure to image file: mlab.savefig(‘foo.png’, size=(300, 300))
Change the view: mlab.view(azimuth=45, elevation=54, distance=1.)
Our data is often more than points and values: it needs some connectivity information
Tip: In general, many properties of the various objects on the figure can be changed. If these visualization are
created via mlab functions, the easiest way to change them is to use the keyword arguments of these functions,
as described in the docstrings.
Hint: If your data is dense in 3D, it is more difficult to display. One option is to take iso-contours of the data. x, y, z are 2D arrays, all of the same shape, giving the positions of the vertices of the surface. The connectivity
between these points is implied by the connectivity on the arrays.
mlab.clf() For simple structures (such as orthogonal grids) prefer the surf function, as it will create more efficient data
x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j] structures.
values = x*x*0.5 + y*y + z*z*2.0 Keyword arguments:
mlab.contour3d(values)
color the color of the vtk object. Overides the colormap, if any, when specified. This
is specified as a triplet of float ranging from 0 to 1, eg (1, 1, 1) for white.
19.1. Mlab: the scripting interface 560 19.1. Mlab: the scripting interface 561
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
transparent make the opacity of the actor depend on the scalar. In [4]: y = r * np.sin(theta)
tube_radius radius of the tubes used to represent the lines, in mesh mode. If None,
In [5]: z = np.sin(r)/r
simple lines are used.
tube_sides number of sides of the tubes used to represent the lines. Must be an In [6]: from mayavi import mlab
integer. Default: 6
In [7]: mlab.mesh(x, y, z, colormap='gist_earth', extent=[0, 1, 0, 1, 0, 1])
vmax vmax is used to scale the colormap If None, the max of the data will be used Out[7]: <mayavi.modules.surface.Surface object at 0xde6f08c>
vmin vmin is used to scale the colormap If None, the min of the data will be used
In [8]: mlab.mesh(x, y, z, extent=[0, 1, 0, 1, 0, 1],
...: representation='wireframe', line_width=1, color=(0.5, 0.5, 0.5))
Out[8]: <mayavi.modules.surface.Surface object at 0xdd6a71c>
Decorations
Tip: Different items can be added to the figure to carry extra information, such as a colorbar or a title.
In [11]: mlab.outline(Out[7])
Out[11]: <enthought.mayavi.modules.outline.Outline object at 0xdd21b6c>
In [12]: mlab.axes(Out[7])
Out[12]: <enthought.mayavi.modules.axes.Axes object at 0xd2e4bcc>
19.1. Mlab: the scripting interface 562 19.1. Mlab: the scripting interface 563
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
To find out what code can be used to program these changes, click on the red button as you modify those
Warning: extent: If we specified extents for a plotting object, mlab.outline’ and ‘mlab.axes don’t get them properties, and it will generate the corresponding lines of code.
by default.
Suppose we are simulating the magnetic field generated by Helmholtz coils. The examples/compute_field.
Tip: The quickest way to create beautiful visualization with Mayavi is probably to interactively tweak the py script does this computation and gives you a B array, that is (3 x n), where the first axis is the direction of
various settings. the field (Bx, By, Bz), and the second axis the index number of the point. Arrays X, Y and Z give the positions
of these data points.
Click on the ‘Mayavi’ button in the scene, and you can control properties of objects with dialogs. Visualize this field. Your goal is to make sure that the simulation code is correct.
19.2. Interactive work 564 19.3. Slicing and dicing data: sources, modules and filters 565
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• A 3D block of regularly-spaced value is structured: it is easy to know how one measurement is related to
another neighboring and how to continuously interpolate between these. We can call such data a field,
borrowing from terminology used in physics, as it is continuously defined in space.
• A set of data points measured at random positions in a random order gives rise to much more difficult
and ill-posed interpolation problems: the data structure itself does not tell us what are the neighbors of
a data point. We call such data a scatter.
Unstructured and unconnected data: a scatter Structured and connected data: a field
mlab.points3d, mlab.quiver3d mlab.contour3d
See also:
Mayavi visualization are created by loading the data in a data source and then displayed on the screen using
modules. Sources are described in details in the Mayavi manual.
This can be seen by looking at the “pipeline” view. By right-clicking on the nodes of the pipeline, you can add
new modules. Transforming data: filters
Quiz If you create a vector field, you may want to visualize the iso-contours of its magnitude. But the isosurface
module can only be applied to scalar data, and not vector data. We can use a filter, ExtractVectorNorm to
Why is it not possible to add a VectorCutPlane to the vectors created by mayavi.mlab.quiver3d()? add this scalar value to the vector field.
Filters apply a transformation to data, and can be added between sources and modules
Using the GUI, add the ExtractVectorNorm filter to display iso-contours of the field magnitude.
Tip: Data comes in different descriptions.
19.3. Slicing and dicing data: sources, modules and filters 566 19.3. Slicing and dicing data: sources, modules and filters 567
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
It is very simple to make interactive dialogs with Mayavi using the Traits library (see the dedicated chapter
Traits: building interactive dialogs).
def curve(n_turns):
"The function creating the x, y, z coordinates needed to plot"
phi = np.linspace(0, 2*np.pi, 2000)
return [np.cos(phi) * (1 + 0.5*np.cos(n_turns*phi)),
np.sin(phi) * (1 + 0.5*np.cos(n_turns*phi)),
0.5*np.sin(n_turns*phi)]
19.4. Animating the data 568 19.5. Making interactive dialogs 569
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Second, the dialog is defined by an object inheriting from HasTraits, as it is done with Traits. The important
view = View(Item('scene', height=300, show_label=False,
point here is that a Mayavi scene is added as a specific Traits attribute (Instance). This is important for editor=SceneEditor()),
embedding it in the dialog. The view of this dialog is defined by the view attribute of the object. In the init of HGroup('n_turns'), resizable=True)
this object, we populate the 3D scene with a curve.
# Fire up the dialog
Finally, the configure_traits method creates the dialog and starts the event loop.
Visualization().configure_traits()
See also:
Tip: Full code of the example: examples/mlab_dialog.py.
There are a few things to be aware of when doing dialogs with Mayavi. Please read the Mayavi documentation
You can look at the example_coil_application.py to see a full-blown application for coil design in 270 lines of
code.
class Visualization(HasTraits):
n_turns = Range(0, 30, 11)
scene = Instance(MlabSceneModel, ())
def __init__(self):
HasTraits.__init__(self)
x, y, z = curve(self.n_turns)
self.plot = self.scene.mlab.plot3d(x, y, z)
@on_trait_change('n_turns')
def update_plot(self):
x, y, z = curve(self.n_turns)
self.plot.mlab_source.set(x=x, y=y, z=z)
Chapters contents
20
• Supervised Learning: Classification of Handwritten Digits
• Supervised Learning: Regression of Housing Data
• Measuring prediction performance
• Unsupervised Learning: Dimensionality Reduction and Visualization
CHAPTER
• The eigenfaces example: chaining PCA and SVMs
• Parameter selection, Validation, and Testing
• Examples for the scikit-learn chapter
Tip: Machine Learning is about building programs with tunable parameters that are adjusted automatically
so as to improve their behavior by adapting to previously seen data.
Machine Learning can be considered a subfield of Artificial Intelligence since those algorithms can be seen
as building blocks to make computers learn to behave more intelligently by somehow generalizing rather that
Authors: Gael Varoquaux
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. Fig. 20.1: A classification problem
See also:
We’ll take a look at two very simple machine learning tasks here. The first is a classification task: the figure
Data science in Python shows a collection of two-dimensional data, colored according to two different class labels. A classification
algorithm may be used to draw a dividing boundary between the two clusters of points:
• The Statistics in Python chapter may also be of interest for readers looking into machine learning.
By drawing this separating line, we have learned a model which can generalize to new data: if you were to drop
• The documentation of scikit-learn is very complete and didactic.
another point onto the plane which is unlabeled, this algorithm could now predict whether it’s a blue or a red
point.
Quick Question:
If we want to design an algorithm to recognize iris species, what might the data be?
Remember: we need a 2D array of size [n_samples x n_features].
Fig. 20.2: A regression problem • What would the n_samples refer to?
• What might the n_features refer to?
Remember that there must be a fixed number of features for each sample, and feature number i must be a
similar kind of quantity for each sample.
The next simple task we’ll look at is a regression task: a simple best-fit line to a set of data.
Again, this is an example of fitting a model to data, but our focus here is that the model can make general- Loading the Iris Data with Scikit-learn
izations about new data. The model has been learned from the training data, and can be used to predict the
result of test data: here, we might be given an x-value, and the model would allow us to predict the y value. Scikit-learn has a very straightforward set of data on these iris species. The data consist of the following:
• Features in the Iris dataset:
20.1.2 Data in scikit-learn
– sepal length (cm)
• n_features: The number of features or distinct traits that can be used to describe each item in a quanti- – Virginica
tative manner. Features are generally real-valued, but may be boolean or discrete-valued in some cases. scikit-learn embeds a copy of the iris CSV file along with a function to load it into numpy arrays:
>>> from sklearn.datasets import load_iris
Tip: The number of features must be fixed in advance. However it can be very high dimensional (e.g. millions
>>> iris = load_iris()
of features) with most of them being zeros for a given sample. This is a case where scipy.sparse matrices
can be useful, in that they are much more memory-efficient than numpy arrays.
Note: Import sklearn Note that scikit-learn is imported as sklearn
A Simple Example: the Iris Dataset The features of each sample flower are stored in the data attribute of the dataset:
20.1. Introduction: problem settings 574 20.1. Introduction: problem settings 575
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> X = x[:, np.newaxis] # The input data for sklearn is 2D: (samples == 3 x features == 1)
>>> X
array([[0],
[1],
[2]])
>>> model.fit(X, y)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=True)
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.])
In Supervised Learning, we have a dataset consisting of both features and labels. The task is to construct an
estimator which is able to predict the label of an object given the set of features. A relatively simple example
is predicting the species of iris given a set of measurements of its flower. This is a relatively simple task. Some
more complicated examples are:
Excercise: • given a multicolor image of an object through a telescope, determine whether that object is a star, a
quasar, or a galaxy.
Can you choose 2 features to find a plot where it is easier to seperate the different classes of irises? • given a photograph of a person, identify the person in the photo.
Hint: click on the figure above to see the code that generates it, and modify this code. • 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.
20.1. Introduction: problem settings 576 20.2. Basic principles of machine learning with scikit-learn 577
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Supervised learning is further broken down into two categories, classification and regression. In classifica-
tion, 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 ob-
servation, 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:
• model.fit() : fit training data. For supervised learning applications, this accepts two
arguments: the data X and the labels y (e.g. model.fit(X, y)). For unsupervised learn-
ing applications, this accepts only a single argument, the data X (e.g. model.fit(X)).
In supervised estimators
• model.predict() : given a trained model, predict the label of a new set of data. This
method accepts one argument, the new data X_new (e.g. model.predict(X_new)), and
returns the learned label for each object in the array.
• model.predict_proba() : For classification problems, some estimators also provide
this method, which returns the probability that a new observation has each categor-
ical 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 imple-
ment 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 representation of the
data based on the unsupervised model.
• model.fit_transform() : some estimators implement this method, which more effi-
ciently performs a fit and a transform on the same input data.
Fig. 20.3: A plot of the sepal space and the prediction of the KNN
20.2.4 Regularization: what it is and why it is necessary
Regression: The simplest possible regression setting is the linear regression one:
Prefering simpler models
20.2.3 A recap on Scikit-learn’s estimator interface Train errors Suppose you are using a 1-nearest neighbor estimator. How many errors do you expect on your
train set?
Scikit-learn strives to have a uniform interface across all methods, and we’ll see examples of these below. Given • Train set error is not a good measurement of prediction performance. You need to leave out a test set.
a scikit-learn estimator object named model, the following methods are available:
• In general, we should accept errors on the train set.
In all Estimators
20.2. Basic principles of machine learning with scikit-learn 578 20.2. Basic principles of machine learning with scikit-learn 579
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
An example of regularization The core idea behind regularization is that we are going to prefer models that
are simpler, for a certain definition of ‘’simpler’‘, even if they lead to more errors on the train set.
As an example, let’s generate with a 9th order polynomial, with noise:
the decision. k=1 amounts to no regularization: 0 error on the training set, whereas large k will push toward
smoother decision boundaries in the feature space.
And now, let’s fit a 4th order and a 9th order polynomial to the data.
Simple versus complex models for classification
Tip: For classification models, the decision boundary, that separates the class expresses the complexity of the
With your naked eyes, which model do you prefer, the 4th order one, or the 9th order one? model. For instance, a linear model, that makes a decision based on a linear combination of features, is more
Let’s look at the ground truth: complex than a non-linear one.
Tip: Regularization is ubiquitous in machine learning. Most scikit-learn estimators have a parameter to tune
the amount of regularization. For instance, with k-NN, it is ‘k’, the number of nearest neighbors used to make
20.2. Basic principles of machine learning with scikit-learn 580 20.2. Basic principles of machine learning with scikit-learn 581
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Code and notebook A good first-step for many problems is to visualize the data using a Dimensionality Reduction technique. We’ll
start with the most straightforward one, Principal Component Analysis (PCA).
Python code and Jupyter notebook for this section are found here
PCA seeks orthogonal linear combinations of the features which show the greatest variance, and as such, can
help give you a good idea of the structure of the data set.
In this section we’ll apply scikit-learn to the classification of handwritten digits. This will go a bit beyond
>>> from sklearn.decomposition import PCA
the iris classification we saw before: we’ll discuss some of the metrics which can be used in evaluating the
>>> pca = PCA(n_components=2)
effectiveness of a classification model.
>>> proj = pca.fit_transform(digits.data)
>>> from sklearn.datasets import load_digits >>> plt.scatter(proj[:, 0], proj[:, 1], c=digits.target)
>>> digits = load_digits() <matplotlib.collections.PathCollection object at ...>
>>> plt.colorbar()
<matplotlib.colorbar.Colorbar object at ...>
Question
Given these projections of the data, which numbers do you think a classifier might have trouble distinguish-
ing?
Let
us visualize the data and remind us what we’re looking at (click on the figure for the full code):
20.3. Supervised Learning: Classification of Handwritten Digits 582 20.3. Supervised Learning: Classification of Handwritten Digits 583
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
For most classification problems, it’s nice to have a simple, fast method to provide a quick baseline classifi-
cation. If the simple and fast method is sufficient, then we don’t have to waste CPU cycles on more complex
models. If not, we can use the results of the simple method to give us clues about our data.
One good method to keep in mind is Gaussian Naive Bayes (sklearn.naive_bayes.GaussianNB).
Tip: Gaussian Naive Bayes fits a Gaussian distribution to each training label independantly 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.
>>> # use the model to predict the labels of the test data
>>> predicted = clf.predict(X_test)
>>> expected = y_test
>>> print(predicted)
[1 7 7 7 8 2 8 0 4 8 7 7 0 8 2 3 5 8 5 3 7 9 6 2 8 2 2 7 3 5...]
>>> print(expected)
[1 0 4 7 8 2 2 0 4 3 7 7 0 8 2 3 4 8 5 3 7 9 6 3 8 2 2 9 3 5...]
As above, we plot the digits with the predicted labels to get an idea of how well the classification is working.
Question
Why did we split the data into training and validation sets?
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:
We see that more than 80% of the 450 predictions match the input. But there are other more sophisticated
metrics that can be used to judge the performance of a classifier: several are available in the sklearn.metrics
20.3. Supervised Learning: Classification of Handwritten Digits 584 20.3. Supervised Learning: Classification of Handwritten Digits 585
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
submodule.
>>> print(data.target.shape)
One of the most useful metrics is the classification_report, which combines several measures and prints (506,)
a table with the results:
We can see that there are just over 500 data points.
>>> from sklearn import metrics
>>> print(metrics.classification_report(expected, predicted)) The DESCR variable has a long description of the dataset:
precision recall f1-score support
>>> print(data.DESCR)
Boston House Prices dataset
0 1.00 0.91 0.95 46
===========================
1 0.76 0.64 0.69 44
2 0.85 0.62 0.72 47
Notes
3 0.98 0.82 0.89 49
------
4 0.89 0.86 0.88 37
Data Set Characteristics:
5 0.97 0.93 0.95 41
6 1.00 0.98 0.99 44
:Number of Instances: 506
7 0.73 1.00 0.84 45
8 0.50 0.90 0.64 49
:Number of Attributes: 13 numeric/categorical predictive
9 0.93 0.54 0.68 48
:Median Value (attribute 14) is usually the target
avg / total 0.86 0.82 0.82 450
:Attribute Information (in order):
Another enlightening metric for this sort of multi-label classification is a confusion matrix: it helps us visualize - CRIM per capita crime rate by town
which labels are being interchanged in the classification errors: - ZN proportion of residential land zoned for lots over 25,000 sq.ft.
- INDUS proportion of non-retail business acres per town
>>> print(metrics.confusion_matrix(expected, predicted))
- CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
[[42 0 0 0 3 0 0 1 0 0]
- NOX nitric oxides concentration (parts per 10 million)
[ 0 28 0 0 0 0 0 1 13 2]
- RM average number of rooms per dwelling
[ 0 3 29 0 0 0 0 0 15 0]
- AGE proportion of owner-occupied units built prior to 1940
[ 0 0 2 40 0 0 0 2 5 0]
- DIS weighted distances to five Boston employment centres
[ 0 0 1 0 32 1 0 3 0 0]
- RAD index of accessibility to radial highways
[ 0 0 0 0 0 38 0 2 1 0]
- TAX full-value property-tax rate per $10,000
[ 0 0 1 0 0 0 43 0 0 0]
- PTRATIO pupil-teacher ratio by town
[ 0 0 0 0 0 0 0 45 0 0]
- B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
[ 0 3 1 0 0 0 0 1 44 0]
- LSTAT % lower status of the population
[ 0 3 0 1 1 0 0 7 10 26]]
- MEDV Median value of owner-occupied homes in $1000's
...
We see here that in particular, the numbers 1, 2, 3, and 9 are often being labeled 8.
It often helps to quickly visualize pieces of the data using histograms, scatter plots, or other plot types. With
pylab, let us show a histogram of the target values: the median price in each neighborhood:
20.4 Supervised Learning: Regression of Housing Data
>>> plt.hist(data.target)
(array([...
Here we’ll do a short example of a regression problem: learning a continuous value from a set of features.
Python code and Jupyter notebook for this section are found here
We’ll use the simple Boston house prices set, available in scikit-learn. This records measurements of 13 at-
tributes of housing markets around Boston, as well as the median price. The question is: can you predict the
price of a new market given its attributes?:
Let’s have a quick look to see if some features are more rele-
>>> from sklearn.datasets import load_boston vant than others for our problem:
>>> data = load_boston()
>>> print(data.data.shape) >>> for index, feature_name in enumerate(data.feature_names):
(506, 13) ... plt.figure()
... plt.scatter(data.data[:, index], data.target)
20.4. Supervised Learning: Regression of Housing Data 586 20.4. Supervised Learning: Regression of Housing Data 587
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
<matplotlib.figure.Figure object...
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.
Use the GradientBoostingRegressor class to fit the housing data.
This is a manual version of a technique called feature selection. hint You can copy and paste some of the above code, replacing LinearRegression with
GradientBoostingRegressor:
Tip: Sometimes, in Machine Learning it is useful to use feature selection to decide which features are the most from sklearn.ensemble import GradientBoostingRegressor
useful for a particular problem. Automated methods exist which quantify this sort of exercise of choosing the # Instantiate the model, fit the results, and scatter in vs. out
most informative features.
Solution The solution is found in the code of this chapter
>>> from sklearn.model_selection import train_test_split Here we’ll continue to look at the digits data, but we’ll switch to the K-Neighbors classifier. The K-neighbors
>>> X_train, X_test, y_train, y_test = train_test_split(data.data, data.target) classifier is an instance-based classifier. The K-neighbors classifier predicts the label of an unknown point
>>> from sklearn.linear_model import LinearRegression based on the labels of the K nearest points in the parameter space.
>>> clf = LinearRegression()
>>> clf.fit(X_train, y_train) >>> # Get the data
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) >>> from sklearn.datasets import load_digits
>>> predicted = clf.predict(X_test) >>> digits = load_digits()
>>> expected = y_test >>> X = digits.data
>>> print("RMS: %s " % np.sqrt(np.mean((predicted - expected) ** 2))) >>> y = digits.target
RMS: 5.0059...
>>> # Instantiate and train the classifier
>>> from sklearn.neighbors import KNeighborsClassifier
>>> clf = KNeighborsClassifier(n_neighbors=1)
>>> clf.fit(X, y)
KNeighborsClassifier(...)
20.4. Supervised Learning: Regression of Housing Data 588 20.5. Measuring prediction performance 589
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
This problem also occurs with regression models. In the following we fit an other instance-based model named
“decision tree” to the Boston Housing price dataset we introduced previously: >>> print("%r , %r , %r " % (X.shape, X_train.shape, X_test.shape))
>>> from sklearn.datasets import load_boston (1797, 64), (1347, 64), (450, 64)
>>> from sklearn.tree import DecisionTreeRegressor
Now we train on the training data, and test on the testing data:
>>> data = load_boston()
>>> clf = DecisionTreeRegressor().fit(data.data, data.target) >>> clf = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train)
>>> predicted = clf.predict(data.data) >>> y_pred = clf.predict(X_test)
>>> expected = data.target
>>> print(metrics.confusion_matrix(y_test, y_pred))
>>> plt.scatter(expected, predicted) [[37 0 0 0 0 0 0 0 0 0]
<matplotlib.collections.PathCollection object at ...> [ 0 43 0 0 0 0 0 0 0 0]
>>> plt.plot([0, 50], [0, 50], '--k') [ 0 0 43 1 0 0 0 0 0 0]
[<matplotlib.lines.Line2D object at ...] [ 0 0 0 45 0 0 0 0 0 0]
[ 0 0 0 0 38 0 0 0 0 0]
[ 0 0 0 0 0 47 0 0 0 1]
[ 0 0 0 0 0 0 52 0 0 0]
[ 0 0 0 0 0 0 0 48 0 0]
[ 0 0 0 0 0 0 0 0 48 0]
[ 0 0 0 1 0 1 0 0 0 45]]
>>> print(metrics.classification_report(y_test, y_pred))
precision recall f1-score support
The over-fitting we saw previously can be quantified by computing the f1-score on the training data itself:
20.5.2 A correct approach: Using a validation set >>> metrics.f1_score(y_train, clf.predict(X_train), average="macro")
1.0
Learning the parameters of a prediction function and testing it on the same data is a methodological mistake:
a model that would just repeat the labels of the samples that it has just seen would have a perfect score but
would fail to predict anything useful on yet-unseen data. Note: Regression metrics In the case of regression models, we need to use different metrics, such as explained
To avoid over-fitting, we have to define two different sets: variance.
• a training set X_train, y_train which is used for learning the parameters of a predictive model
• a testing set X_test, y_test which is used for evaluating the fitted predictive model
20.5.3 Model Selection via Validation
In scikit-learn such a random split can be quickly computed with the train_test_split() function:
20.5. Measuring prediction performance 590 20.5. Measuring prediction performance 591
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
• With the default hyper-parameters for each estimator, which gives the best f1 score on the validation account non iid datasets.
set? Recall that hyperparameters are the parameters set when you instantiate the classifier: for example,
the n_neighbors in clf = KNeighborsClassifier(n_neighbors=1)
>>> from sklearn.naive_bayes import GaussianNB 20.5.5 Hyperparameter optimization with cross-validation
>>> from sklearn.neighbors import KNeighborsClassifier
>>> from sklearn.svm import LinearSVC Consider regularized linear models, such as Ridge Regression, which uses l2 regularlization, and Lasso Regres-
sion, which uses l1 regularization. Choosing their regularization parameter is important.
>>> X = digits.data
>>> y = digits.target Let us set these parameters on the Diabetes dataset, a simple regression problem. The diabetes data consists
>>> X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, of 10 physiological variables (age, sex, weight, blood pressure) measure on 442 patients, and an indication of
... test_size=0.25, random_state=0) disease progression after one year:
>>> for Model in [GaussianNB, KNeighborsClassifier, LinearSVC]: >>> from sklearn.datasets import load_diabetes
... clf = Model().fit(X_train, y_train) >>> data = load_diabetes()
... y_pred = clf.predict(X_test) >>> X, y = data.data, data.target
... print('%s : %s ' % >>> print(X.shape)
... (Model.__name__, metrics.f1_score(y_test, y_pred, average="macro"))) (442, 10)
GaussianNB: 0.8332741681...
KNeighborsClassifier: 0.9804562804... With the default hyper-parameters: we compute the cross-validation score:
LinearSVC: 0.93...
>>> from sklearn.linear_model import Ridge, Lasso
• For each classifier, which value for the hyperparameters gives the best results for the digits data? For
LinearSVC, use loss='l2' and loss='l1'. For KNeighborsClassifier we use n_neighbors be- >>> for Model in [Ridge, Lasso]:
tween 1 and 10. Note that GaussianNB does not have any adjustable hyperparameters. ... model = Model()
... print('%s : %s ' % (Model.__name__, cross_val_score(model, X, y).mean()))
LinearSVC(loss='l1'): 0.930570687535 Ridge: 0.409427438303
LinearSVC(loss='l2'): 0.933068826918 Lasso: 0.353800083299
-------------------
KNeighbors(n_neighbors=1): 0.991367521884
KNeighbors(n_neighbors=2): 0.984844206884 Basic Hyperparameter Optimization
KNeighbors(n_neighbors=3): 0.986775344954
KNeighbors(n_neighbors=4): 0.980371905382
KNeighbors(n_neighbors=5): 0.980456280495 We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso and
KNeighbors(n_neighbors=6): 0.975792419414 Ridge. We choose 20 values of alpha between 0.0001 and 1:
KNeighbors(n_neighbors=7): 0.978064579214
>>> alphas = np.logspace(-3, -1, 30)
KNeighbors(n_neighbors=8): 0.978064579214
KNeighbors(n_neighbors=9): 0.978064579214
>>> for Model in [Lasso, Ridge]:
KNeighbors(n_neighbors=10): 0.975555089773
... scores = [cross_val_score(Model(alpha), X, y, cv=3).mean()
... for alpha in alphas]
Solution: code source ... plt.plot(alphas, scores, label=Model.__name__)
[<matplotlib.lines.Line2D object at ...
20.5.4 Cross-validation
Cross-validation consists in repetively splitting the data in pairs of train and test sets, called ‘folds’. Scikit-learn
comes with a function to automatically compute score on all these folds. Here we do KFold with k=5.
20.5. Measuring prediction performance 592 20.5. Measuring prediction performance 593
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> from sklearn.grid_search import GridSearchCV Tip: PCA computes linear combinations of the original features using a truncated Singular Value Decomposi-
>>> for Model in [Ridge, Lasso]: tion of the matrix X, to project the data onto a base of the top singular vectors.
... gscv = GridSearchCV(Model(), dict(alpha=alphas), cv=3).fit(X, y)
... print('%s : %s ' % (Model.__name__, gscv.best_params_))
Ridge: {'alpha': 0.062101694189156162} >>> from sklearn.decomposition import PCA
Lasso: {'alpha': 0.01268961003167922} >>> pca = PCA(n_components=2, whiten=True)
>>> pca.fit(X)
PCA(..., n_components=2, ...)
Built-in Hyperparameter Search Once fitted, PCA exposes the singular vectors in the components_ attribute:
For some models within scikit-learn, cross-validation can be performed more efficiently on large datasets. In >>> pca.components_
this case, a cross-validated version of the particular model is included. The cross-validated versions of Ridge array([[ 0.36158..., -0.08226..., 0.85657..., 0.35884...],
and Lasso are RidgeCV and LassoCV, respectively. Parameter search on these estimators can be performed as [ 0.65653..., 0.72971..., -0.17576..., -0.07470...]])
follows:
Other attributes are available as well:
>>> from sklearn.linear_model import RidgeCV, LassoCV
>>> for Model in [RidgeCV, LassoCV]: >>> pca.explained_variance_ratio_
... model = Model(alphas=alphas, cv=3).fit(X, y) array([ 0.92461..., 0.05301...])
... print('%s : %s ' % (Model.__name__, model.alpha_))
RidgeCV: 0.0621016941892 Let us project the iris dataset along those first two dimensions::
LassoCV: 0.0126896100317
>>> X_pca = pca.transform(X)
We see that the results match those returned by GridSearchCV >>> X_pca.shape
(150, 2)
Nested cross-validation PCA normalizes and whitens the data, which means that the data is now centered on both components with
unit variance:
How do we measure the performance of these estimators? We have used data to set the hyperparameters, so
we need to test on actually new data. We can do this by running cross_val_score() on our CV objects. Here >>> X_pca.mean(axis=0)
there are 2 cross-validation loops going on, this is called ‘nested cross validation’: array([ ...e-15, ...e-15])
>>> X_pca.std(axis=0)
for Model in [RidgeCV, LassoCV]: array([ 1., 1.])
scores = cross_val_score(Model(alphas=alphas, cv=3), X, y, cv=3)
print(Model.__name__, np.mean(scores)) Furthermore, the samples components do no longer carry any linear correlation:
>>> np.corrcoef(X_pca.T)
Note: Note that these results do not match the best results of our curves above, and LassoCV seems to under- array([[ 1.00000000e+00, ...],
[ ..., 1.00000000e+00]])
perform RidgeCV. The reason is that setting the hyper-parameter is harder for Lasso, thus the estimation error
on this hyper-parameter is larger.
With a number of retained components 2 or 3, PCA is useful to visualize the dataset:
Unsupervised learning is applied on X without y: data without labels. A typical use case is to find hidden
structure in the data.
Dimensionality reduction derives a set of new artificial features smaller than the original feature set. Here we’ll
use Principal Component Analysis (PCA), a dimensionality reduction that strives to retain most of the variance
of the original data. We’ll use sklearn.decomposition.PCA on the iris dataset:
20.6. Unsupervised Learning: Dimensionality Reduction and Visualization 594 20.6. Unsupervised Learning: Dimensionality Reduction and Visualization 595
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Tip: Note that this projection was determined without any information about the labels (represented by the fit_transform
colors): this is the sense in which the learning is unsupervised. Nevertheless, we see that the projection gives
us insight into the distribution of the different flowers in parameter space: notably, iris setosa is much more As TSNE cannot be applied to new data, we need to use its fit_transform method.
distinct than the other two species.
For visualization, more complex embeddings can be useful (for statistical analysis, they are harder to control). sklearn.manifold.TSNE separates quite well the different classes of digits eventhough it had no access to
sklearn.manifold.TSNE is such a powerful manifold learning method. We apply it to the digits dataset, as the class information.
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 Exercise: Other dimension reduction of digits
>>> X = digits.data[:500]
>>> y = digits.target[:500] 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?
>>> # Fit and transform with a TSNE
>>> from sklearn.manifold import TSNE >>> from sklearn.datasets import load_digits
>>> tsne = TSNE(n_components=2, random_state=0) >>> digits = load_digits()
>>> X_2d = tsne.fit_transform(X) >>> # ...
Python code and Jupyter notebook for this section are found here
The goal of this example is to show how an unsupervised method and a supervised one can be chained for
better prediction. It starts with a didactic but lengthy way of doing things, and finishes with the idiomatic
approach to pipelining in scikit-learn.
20.6. Unsupervised Learning: Dimensionality Reduction and Visualization 596 20.7. The eigenfaces example: chaining PCA and SVMs 597
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Here we’ll take a look at a simple facial recognition example. Ideally, we would use a dataset consisting of a
subset of the Labeled Faces in the Wild data that is available with sklearn.datasets.fetch_lfw_people(). print(X_train.shape, X_test.shape)
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.
Out:
from sklearn import datasets
(300, 4096) (100, 4096)
faces = datasets.fetch_olivetti_faces()
faces.data.shape
Let’s visualize these faces to see what we’re working with 20.7.1 Preprocessing: Principal Component Analysis
from matplotlib import pyplot as plt 1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable size, while
fig = plt.figure(figsize=(8, 6)) maintaining most of the information in the dataset.
# plot several images
for i in range(15): from sklearn import decomposition
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) pca = decomposition.PCA(n_components=150, whiten=True)
ax.imshow(faces.images[i], cmap=plt.cm.bone) pca.fit(X_train)
One interesting part of PCA is that it computes the “mean” face, which can be interesting to examine:
plt.imshow(pca.mean_.reshape(faces.images[0].shape),
cmap=plt.cm.bone)
Tip: Note is that these faces have already been localized and scaled to a common size. This is an important
preprocessing piece for facial recognition, and is a process that can require a large collection of training data.
This can be done in scikit-learn, but the challenge is gathering a sufficient amount of training data for the
algorithm to work. Fortunately, this piece is common enough that it has been done. One good resource is
OpenCV, the Open Computer Vision Library. The principal components measure deviations about this mean along orthogonal axes.
print(pca.components_.shape)
We’ll perform a Support Vector classification of the images. We’ll do a typical train-test split on the images:
Out:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(faces.data, (150, 4096)
faces.target, random_state=0)
20.7. The eigenfaces example: chaining PCA and SVMs 598 20.7. The eigenfaces example: chaining PCA and SVMs 599
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
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)
Out:
(300, 150)
print(X_test_pca.shape)
Out: The classifier is correct on an impressive number of images given the simplicity of its learning model! Using
a linear classifier on 150 features derived from the pixel-level data, the algorithm correctly identifies a large
(100, 150) number of the people in the images.
Again, we can quantify this effectiveness using one of several measures from sklearn.metrics. First we can
These projected components correspond to factors in a linear combination of component images such that
do the classification report, which shows the precision, recall and other measures of the “goodness” of the
the combination approaches the original face.
classification:
20.7. The eigenfaces example: chaining PCA and SVMs 600 20.7. The eigenfaces example: chaining PCA and SVMs 601
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
print(metrics.confusion_matrix(y_test, y_pred)) Python code and Jupyter notebook for this section are found here
Out:
Let us start with a simple 1D regression problem. This will help us to easily visualize the data and the model,
[[4 0 0 ..., 0 0 0] and the results generalize easily to higher-dimensional datasets. We’ll explore a simple linear regression prob-
[0 4 0 ..., 0 0 0] lem, with sklearn.linear_model.
[0 0 2 ..., 0 0 0]
..., X = np.c_[ .5, 1].T
[0 0 0 ..., 3 0 0] y = [.5, 1]
[0 0 0 ..., 0 1 0] X_test = np.c_[ 0, 2].T
[0 0 0 ..., 0 0 3]]
Without noise, as linear regression fits the data perfectly
20.7. The eigenfaces example: chaining PCA and SVMs 602 20.8. Parameter selection, Validation, and Testing 603
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
In real life situation, we have noise (e.g. measurement noise) in our data: As we can see, the estimator displays much less variance. However it systematically under-estimates the coef-
ficient. It displays a biased behavior.
np.random.seed(0)
for _ in range(6): This is a typical example of bias/variance tradeof: non-regularized estimator are not biased, but they can
noisy_X = X + np.random.normal(loc=0, scale=.1, size=X.shape) display a lot of bias. Highly-regularized models have little variance, but high bias. This bias is not necessarily
plt.plot(noisy_X, y, 'o') a bad thing: what matters is choosing the tradeoff between bias and variance that leads to the best prediction
regr.fit(noisy_X, y) performance. For a specific dataset there is a sweet spot corresponding to the highest complexity that the data
plt.plot(X_test, regr.predict(X_test)) can support, depending on the amount of noise and of observations available.
Tip: Given a particular dataset and a model (e.g. a polynomial), we’d like to understand whether bias (underfit)
or variance limits prediction, and how to tune the hyperparameter (here d, the degree of the polynomial) to give
the best fit.
On a given data, let us fit a simple polynomial regression model with varying degrees:
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=.1)
np.random.seed(0)
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=.1, size=X.shape)
plt.plot(noisy_X, y, 'o')
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))
plt.show()
Tip: In the above figure, we see fits for three different values of d. For d = 1, the data is under-fit. This means
that the model is too simplistic: no straight line will ever be a good fit to this data. In this case, we say that the
model suffers from high bias. The model itself is biased, and this will be reflected in the fact that the data is
poorly fit. At the other extreme, for d = 6 the data is over-fit. This means that the model has too many free
parameters (6 in this case) which can be adjusted to perfectly fit the training data. If we add a new point to this
plot, though, chances are it will be very far from the curve representing the degree-6 fit. In this case, we say
that the model suffers from high variance. The reason for the term “high variance” is that if any of the input
points are varied slightly, it could result in a very different model.
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
20.8. Parameter selection, Validation, and Testing 604 20.8. Parameter selection, Validation, and Testing 605
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
identify bias and variance, and optimize the metaparameters (in this case, the polynomial degree d) in order
... model, x[:, np.newaxis], y,
to determine the best algorithm. ... param_name='polynomialfeatures__degree',
... param_range=degrees)
>>> # Plot the mean train score and validation score across folds
Polynomial regression with scikit-learn
>>> plt.plot(degrees, validation_scores.mean(axis=1), label='cross-validation')
[<matplotlib.lines.Line2D object at ...>]
A polynomial regression is built by pipelining PolynomialFeatures and a LinearRegression: >>> plt.plot(degrees, train_scores.mean(axis=1), label='training')
>>> from sklearn.pipeline import make_pipeline [<matplotlib.lines.Line2D object at ...>]
>>> from sklearn.preprocessing import PolynomialFeatures >>> plt.legend(loc='best')
>>> from sklearn.linear_model import LinearRegression <matplotlib.legend.Legend object at ...>
>>> model = make_pipeline(PolynomialFeatures(degree=2), LinearRegression())
Validation Curves
Tip: The astute reader will realize that something is amiss here: in the above plot, d = 4 gives the best results.
But in the previous plot, we found that d = 6 vastly over-fits the data. What’s going on here? The difference
is the number of training points used. In the previous example, there were only eight training points. In this
example, we have 100. As a general rule of thumb, the more training points used, the more complicated model
can be used. But how can you determine for a given model whether more training points will be helpful? A
useful diagnostic for this are learning curves.
20.8. Parameter selection, Validation, and Testing 606 20.8. Parameter selection, Validation, and Testing 607
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
>>> # 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 ...>]
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:
Fig. 20.5: For a degree=1 model
• Gathering more training samples.
Note that the validation score generally increases with a growing training set, while the training score generally • Using a less-sophisticated model (i.e. in this case, make d smaller)
decreases with a growing training set. As the training size increases, they will converge to a single value. • Increasing regularization.
From the above discussion, we know that d = 1 is a high-bias estimator which under-fits the data. This is In particular, gathering more features for each sample will not help the results.
indicated by the fact that both the training and validation scores are low. When confronted with this type of
learning curve, we can expect that adding more training data will not help: both lines converge to a relatively
low score. 20.8.3 Summary on model selection
When the learning curves have converged to a low score, we have a high bias model.
We’ve seen above that an under-performing algorithm can be due to two possible situations: high bias (under-
A high-bias model can be improved by: fitting) and high variance (over-fitting). In order to evaluate our algorithm, we set aside a portion of our training
• Using a more sophisticated model (i.e. in this case, increase d) data for cross-validation. Using the technique of learning curves, we can train on progressively larger subsets
of the data, evaluating the training error and cross-validation error to determine whether our algorithm has
• Gather more features for each sample. high variance or high bias. But what do we do with this information?
• Decrease regularization in a regularized model.
Increasing the number of samples, however, does not improve a high-bias model. High Bias
Now let’s look at a high-variance (i.e. over-fit) model: If a model shows high bias, the following actions might help:
• Add more features. In our example of predicting home prices, it may be helpful to make use of infor-
mation such as the neighborhood the house is in, the year the house was built, the size of the lot, etc.
Adding these features to the training and test sets can improve a high-bias estimator
• Use a more sophisticated model. Adding complexity to the model can help improve on bias. For a
polynomial fit, this can be accomplished by increasing the degree d. Each learning technique has its
own methods of adding complexity.
• Use fewer samples. Though this will not improve the classification, a high-bias algorithm can attain
nearly the same error with a smaller training sample. For algorithms which are computationally expen-
sive, reducing the training sample size can lead to very large improvements in speed.
20.8. Parameter selection, Validation, and Testing 608 20.8. Parameter selection, Validation, and Testing 609
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Using validation schemes to determine hyper-parameters means that we are fitting the hyper-parameters to
the particular validation set. In the same way that parameters can be over-fit to the training set, hyperpa-
rameters can be over-fit to the validation set. Because of this, the validation error tends to under-predict the
classification error of new data.
For this reason, it is recommended to split the data into three sets:
• The training set, used to train the model (usually ~60% of the data)
• The validation set, used to validate the model (usually ~20% of the data)
• The test set, used to evaluate the expected error of the validated model (usually ~20% of the data)
Pretty much no errors!
Many machine learning practitioners do not separate test set and validation set. But if your goal is to gauge
the error of a model on unknown data, using an independent test set is vital. This is too good to be true: we are testing the model on the train data, which is not a mesure of generalization.
The results are not valid
Total running time of the script: ( 0 minutes 0.069 seconds)
Download Python source code: plot_measuring_performance.py
Download Jupyter notebook: plot_measuring_performance.ipynb
20.9 Examples for the scikit-learn chapter
Generated by Sphinx-Gallery
20.9. Examples for the scikit-learn chapter 610 20.9. Examples for the scikit-learn chapter 611
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
X_pca = pca.transform(X)
target_ids = range(len(iris.target_names))
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# x from 0 to 30
x = 30 * np.random.random((20, 1))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.axis('tight')
plt.show()
Total running time of the script: ( 0 minutes 0.043 seconds)
Total running time of the script: ( 0 minutes 0.122 seconds)
Download Python source code: plot_pca.py
Download Python source code: plot_linear_regression.py
Download Jupyter notebook: plot_pca.ipynb
Download Jupyter notebook: plot_linear_regression.ipynb
Generated by Sphinx-Gallery
Generated by Sphinx-Gallery
20.9. Examples for the scikit-learn chapter 612 20.9. Examples for the scikit-learn chapter 613
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
20.9.4 Plot 2D views of the iris dataset 20.9.5 tSNE to visualize digits
Plot a simple scatter plot of 2 features of the iris dataset. Here we use sklearn.manifold.TSNE to visualize the digits datasets. Indeed, the digits are vectors in a 8*8
= 64 dimensional space. We want to project them in 2D for visualization. tSNE is often a good solution, as it
Note that more elaborate visualization of this dataset is detailed in the Statistics in Python chapter.
groups and separates data points based on their local relationship.
Load the iris data
X_2d = tsne.fit_transform(X)
target_ids = range(len(digits.target_names))
# this formatter will label the colorbar with the correct target names
formatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])
plt.figure(figsize=(5, 4))
plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)
plt.colorbar(ticks=[0, 1, 2], format=formatter)
plt.xlabel(iris.feature_names[x_index])
plt.ylabel(iris.feature_names[y_index])
plt.tight_layout()
plt.show()
20.9. Examples for the scikit-learn chapter 614 20.9. Examples for the scikit-learn chapter 615
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Out:
Ridge: 0.409427438303
Lasso: 0.353800083299
We compute the cross-validation score as a function of alpha, the strength of the regularization for Lasso and
Ridge
import numpy as np
from matplotlib import 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()
20.9.6 Use the RidgeCV and LassoCV to set the regularization parameter
20.9. Examples for the scikit-learn chapter 616 20.9. Examples for the scikit-learn chapter 617
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
np.random.seed(0)
for _ in range(6):
noisy_X = X + np.random.normal(loc=0, scale=.1, size=X.shape)
plt.plot(noisy_X, y, 'o')
regr.fit(noisy_X, y)
plt.plot(X_test, regr.predict(X_test))
As we can see, our linear model captures and amplifies the noise in the data. It displays a lot of variance. import numpy as np
import matplotlib.pyplot as plt
We can use another linear estimator that uses regularization, the Ridge estimator. This estimator regularizes from sklearn.linear_model import SGDClassifier
the coefficients by shrinking them to zero, under the assumption that very high correlations are often spurious. from sklearn.datasets.samples_generator import make_blobs
The alpha parameter controls the amount of shrinkage used.
# we create 50 separable synthetic points
regr = linear_model.Ridge(alpha=.1) X, Y = make_blobs(n_samples=50, centers=2,
np.random.seed(0) random_state=0, cluster_std=0.60)
20.9. Examples for the scikit-learn chapter 618 20.9. Examples for the scikit-learn chapter 619
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
20.9. Examples for the scikit-learn chapter 620 20.9. Examples for the scikit-learn chapter 621
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
rng = np.random.RandomState(0)
x = 2*rng.rand(100) - 1
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")
plt.axis('tight')
plt.title('Ground truth (9th order polynomial)')
plt.show()
plt.figure(figsize=(6, 4))
plt.scatter(x, y, s=4)
plt.legend(loc='best')
plt.axis('tight')
plt.title('Fitting a 4th and a 9th order polynomial')
20.9. Examples for the scikit-learn chapter 622 20.9. Examples for the scikit-learn chapter 623
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Here we perform a simple regression analysis on the Boston housing data, exploring two types of regressors.
20.9. Examples for the scikit-learn chapter 624 20.9. Examples for the scikit-learn chapter 625
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
plt.figure(figsize=(4, 3))
• plt.scatter(expected, predicted)
plt.plot([0, 50], [0, 50], '--k')
plt.axis('tight')
plt.xlabel('True price ($1000s)')
plt.ylabel('Predicted price ($1000s)')
plt.tight_layout()
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, 50], [0, 50], '--k')
plt.axis('tight')
plt.xlabel('True price ($1000s)')
plt.ylabel('Predicted price ($1000s)')
plt.tight_layout()
•
Simple prediction
20.9. Examples for the scikit-learn chapter 626 20.9. Examples for the scikit-learn chapter 627
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
import numpy as np
print("RMS: %r " % np.sqrt(np.mean((predicted - expected) ** 2)))
plt.show()
Out:
RMS: 3.3940265988986305
Plot the decision boundary of nearest neighbor decision on iris, first with a single nearest neighbor, and then
using 3 nearest neighbors.
import numpy as np
from matplotlib import pyplot as plt
from sklearn import neighbors, datasets
from matplotlib.colors import ListedColormap
And now, redo the analysis with 3 neighbors
# Create color maps for 3-class classification problem, as with iris
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) knn = neighbors.KNeighborsClassifier(n_neighbors=3)
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) knn.fit(X, y)
iris = datasets.load_iris() Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])
X = iris.data[:, :2] # we only take the first two features. We could
# avoid this ugly slicing by using a two-dim dataset # Put the result into a color plot
y = iris.target Z = Z.reshape(xx.shape)
plt.figure()
knn = neighbors.KNeighborsClassifier(n_neighbors=1) plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
knn.fit(X, y)
# Plot also the training points
x_min, x_max = X[:, 0].min() - .1, X[:, 0].max() + .1 plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
20.9. Examples for the scikit-learn chapter 628 20.9. Examples for the scikit-learn chapter 629
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Plot the first few samples of the digits dataset and a 2D representation built using PCA, then do a simple clas-
Plot a projection on the 2 first principal axis
sification
20.9. Examples for the scikit-learn chapter 630 20.9. Examples for the scikit-learn chapter 631
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
20.9. Examples for the scikit-learn chapter 632 20.9. Examples for the scikit-learn chapter 633
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
print(metrics.confusion_matrix(expected, predicted))
plt.show()
Out:
[[37 0 0 0 2 0 0 1 0 0]
[ 0 41 0 0 0 0 1 0 4 2]
[ 0 2 31 0 0 0 1 0 11 0]
[ 0 0 2 48 0 1 0 2 4 1]
[ 0 1 1 0 32 0 0 1 1 0]
[ 0 1 0 1 1 41 0 4 0 0]
[ 0 0 0 0 0 1 42 0 0 0]
[ 0 0 0 0 0 1 0 46 0 0]
[ 0 4 0 0 0 1 0 3 34 0]
[ 0 1 0 1 0 0 1 4 4 32]]
20.9.14 The eigenfaces example: chaining PCA and SVMs We’ll perform a Support Vector classification of the images. We’ll do a typical train-test split on the images:
The goal of this example is to show how an unsupervised method and a supervised one can be chained for from sklearn.model_selection import train_test_split
better prediction. It starts with a didactic but lengthy way of doing things, and finishes with the idiomatic X_train, X_test, y_train, y_test = train_test_split(faces.data,
approach to pipelining in scikit-learn. faces.target, random_state=0)
Here we’ll take a look at a simple facial recognition example. Ideally, we would use a dataset consisting of a print(X_train.shape, X_test.shape)
subset of the Labeled Faces in the Wild data that is available with sklearn.datasets.fetch_lfw_people().
However, this is a relatively large download (~200MB) so we will do the tutorial on a simpler, less rich dataset. Out:
Feel free to explore the LFW dataset.
20.9. Examples for the scikit-learn chapter 634 20.9. Examples for the scikit-learn chapter 635
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
1850 dimensions is a lot for SVM. We can use PCA to reduce these 1850 features to a manageable size, while
maintaining most of the information in the dataset.
One interesting part of PCA is that it computes the “mean” face, which can be interesting to examine:
plt.imshow(pca.mean_.reshape(faces.images[0].shape),
cmap=plt.cm.bone)
The components (“eigenfaces”) are ordered by their importance from top-left to bottom-right. We see that the
first few components seem to primarily take care of lighting conditions; the remaining components pull out
certain identifying features: the nose, eyes, eyebrows, etc.
With this projection computed, we can now project our original training and test data onto the PCA basis:
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print(X_train_pca.shape)
Out:
(300, 150)
print(X_test_pca.shape)
Out:
(100, 150)
These projected components correspond to factors in a linear combination of component images such that
the combination approaches the original face.
print(pca.components_.shape)
Finally, we can evaluate how well this classification did. First, we might plot a few of the test-cases with the
labels learned from the training set:
Out:
import numpy as np
(150, 4096) fig = plt.figure(figsize=(8, 6))
for i in range(15):
It is also interesting to visualize these principal components: ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(X_test[i].reshape(faces.images[0].shape),
fig = plt.figure(figsize=(16, 6)) cmap=plt.cm.bone)
for i in range(30): y_pred = clf.predict(X_test_pca[i, np.newaxis])[0]
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[]) color = ('black' if y_pred == y_test[i] else 'red')
20.9. Examples for the scikit-learn chapter 636 20.9. Examples for the scikit-learn chapter 637
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Another interesting metric is the confusion matrix, which indicates how often any two items are mixed-up.
The confusion matrix of a perfect classifier would only have nonzero entries on the diagonal, with zeros on the
off-diagonal:
print(metrics.confusion_matrix(y_test, y_pred))
The classifier is correct on an impressive number of images given the simplicity of its learning model! Using Out:
a linear classifier on 150 features derived from the pixel-level data, the algorithm correctly identifies a large
[[4 0 0 ..., 0 0 0]
number of the people in the images. [0 4 0 ..., 0 0 0]
Again, we can quantify this effectiveness using one of several measures from sklearn.metrics. First we can [0 0 2 ..., 0 0 0]
do the classification report, which shows the precision, recall and other measures of the “goodness” of the ...,
[0 0 0 ..., 3 0 0]
classification:
[0 0 0 ..., 0 1 0]
from sklearn import metrics [0 0 0 ..., 0 0 3]]
y_pred = clf.predict(X_test_pca)
print(metrics.classification_report(y_test, y_pred))
Pipelining
Out:
Above we used PCA as a pre-processing step before applying our support vector machine classifier. Plugging
precision recall f1-score support
the output of one estimator directly into the input of a second estimator is a commonly used pattern; for this
0 1.00 0.67 0.80 6
reason scikit-learn provides a Pipeline object which automates this process. The above problem can be re-
1 1.00 1.00 1.00 4 expressed as a pipeline as follows:
2 0.50 1.00 0.67 2
from sklearn.pipeline import Pipeline
3 1.00 1.00 1.00 1
clf = Pipeline([('pca', decomposition.PCA(n_components=150, whiten=True)),
4 1.00 1.00 1.00 1
('svm', svm.LinearSVC(C=1.0))])
5 1.00 1.00 1.00 5
6 1.00 1.00 1.00 4
clf.fit(X_train, y_train)
7 1.00 0.67 0.80 3
9 1.00 1.00 1.00 1
y_pred = clf.predict(X_test)
10 1.00 1.00 1.00 4
print(metrics.confusion_matrix(y_pred, y_test))
11 1.00 1.00 1.00 1
plt.show()
12 0.67 1.00 0.80 2
20.9. Examples for the scikit-learn chapter 638 20.9. Examples for the scikit-learn chapter 639
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Out:
s=80, edgecolors="k", facecolors="none")
[[5 0 0 ..., 0 0 0]
[0 4 0 ..., 0 0 0] delta = 1
[0 0 1 ..., 0 0 0] y_min, y_max = -50, 50
..., x_min, x_max = -50, 50
[0 0 0 ..., 3 0 0] x = np.arange(x_min, x_max + delta, delta)
[0 0 0 ..., 0 1 0] y = np.arange(y_min, y_max + delta, delta)
[0 0 0 ..., 0 0 3]] X1, X2 = np.meshgrid(x, y)
Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
Z = Z.reshape(X1.shape)
This is an example plot from the tutorial which accompanies an explanation of the support vector machine
GUI.
import numpy as np
from matplotlib import pyplot as plt
ax.scatter(clf.support_vectors_[:, 0],
clf.support_vectors_[:, 1], X, y = nonlinear_model()
clf = svm.SVC(kernel='rbf', gamma=0.001, coef0=0, degree=3)
20.9. Examples for the scikit-learn chapter 640 20.9. Examples for the scikit-learn chapter 641
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Fit polynomes of different degrees to a dataset: for too small a degree, the model underfits, while for too large
clf.fit(X, y)
a degree, it overfits.
plt.figure(figsize=(6, 4))
import numpy as np
ax = plt.subplot(1, 1, 1, xticks=[], yticks=[])
import matplotlib.pyplot as plt
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone, zorder=2)
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])
Demo overfitting, underfitting, and validation and learning curves with polynomial regression.
20.9. Examples for the scikit-learn chapter 642 20.9. Examples for the scikit-learn chapter 643
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
n_samples = 200
test_size = 0.4
error = 1.0
# Plot the mean train error and validation error across folds
plt.figure(figsize=(6, 4))
plt.plot(degrees, validation_scores.mean(axis=1), lw=2,
label='cross-validation')
plt.plot(degrees, train_scores.mean(axis=1), lw=2, label='training')
plt.legend(loc='best')
plt.xlabel('degree of fit')
plt.ylabel('explained variance')
plt.title('Validation curve')
plt.tight_layout()
20.9. Examples for the scikit-learn chapter 644 20.9. Examples for the scikit-learn chapter 645
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
Learning curves
plt.legend(loc='best') This script plots the flow-charts used in the scikit-learn tutorials.
plt.xlabel('number of train samples')
plt.ylabel('explained variance')
plt.title('Learning curve (degree=%i )' % d)
plt.tight_layout()
plt.show()
20.9. Examples for the scikit-learn chapter 646 20.9. Examples for the scikit-learn chapter 647
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
arrow1 = '#88CCFF',
arrow2 = '#88FF88',
supervised=True):
fig = pl.figure(figsize=(9, 6), facecolor='w')
ax = pl.axes((0, 0, 1, 1),
xticks=[], yticks=[], frameon=False)
ax.set_xlim(0, 9)
ax.set_ylim(0, 6)
Polygon([[5.5, 1.7],
[6.1, 1.1],
[5.5, 0.5],
[4.9, 1.1]], fc=box_bg),
if supervised:
patches += [Rectangle((0.3, 2.4), 1.5, 0.5, zorder=1, fc=box_bg),
Rectangle((0.5, 2.6), 1.5, 0.5, zorder=2, fc=box_bg),
Rectangle((0.7, 2.8), 1.5, 0.5, zorder=3, fc=box_bg),
FancyArrow(2.3, 2.9, 2.0, 0, fc=arrow1,
width=0.25, head_width=0.5, head_length=0.2),
Rectangle((7.3, 0.85), 1.5, 0.5, fc=box_bg)]
else:
patches += [Rectangle((7.3, 0.2), 1.5, 1.8, fc=box_bg)]
•
for p in patches:
import numpy as np ax.add_patch(p)
import pylab as pl
from matplotlib.patches import Circle, Rectangle, Polygon, Arrow, FancyArrow pl.text(1.45, 4.9, "Training\nText,\nDocuments,\nImages,\netc.",
ha='center', va='center', fontsize=14)
def create_base(box_bg = '#CCCCCC',
pl.text(3.6, 4.9, "Feature\nVectors",
20.9. Examples for the scikit-learn chapter 648 20.9. Examples for the scikit-learn chapter 649
Scipy lecture notes, Edition 2017.1 Scipy lecture notes, Edition 2017.1
else:
pl.text(8.05, 1.1,
"Likelihood\nor Cluster ID\nor Better\nRepresentation",
ha='center', va='center', fontsize=12)
pl.text(8.8, 5.8, "Unsupervised Learning Model",
ha='right', va='top', fontsize=18)
def plot_supervised_chart(annotate=False):
create_base(supervised=True)
if annotate:
fontdict = dict(color='r', weight='bold', size=14)
pl.text(1.9, 4.55, 'X = vec.fit_transform(input)',
fontdict=fontdict,
rotation=20, ha='left', va='bottom')
pl.text(3.7, 3.2, 'clf.fit(X, y)',
fontdict=fontdict,
rotation=20, ha='left', va='bottom')
pl.text(1.7, 1.5, 'X_new = vec.transform(input)',
fontdict=fontdict,
rotation=20, ha='left', va='bottom')
pl.text(6.1, 1.5, 'y_new = clf.predict(X_new)',
fontdict=fontdict,
rotation=20, ha='left', va='bottom')
def plot_unsupervised_chart():
create_base(supervised=False)
if __name__ == '__main__':
plot_supervised_chart(False)
plot_supervised_chart(True)
plot_unsupervised_chart()
pl.show()
20.9. Examples for the scikit-learn chapter 650 20.9. Examples for the scikit-learn chapter 651
Index
D
diff, 508, 511
differentiation, 508
dsolve, 511
E
equations
algebraic, 510
differential, 511
I
integration, 509
M
Matrix, 511
P
Python Enhancement Proposals
PEP 255, 268
PEP 3118, 304
PEP 3129, 277
PEP 318, 270, 277
PEP 342, 268
PEP 343, 278
PEP 380, 269
PEP 380#id13, 269
PEP 8, 272
S
solve, 510
652