Docsity

python probability statistics and machine learning, Notas de estudo de Engenharia Elétrica

Pré-visualização parcial do texto

Baixe python probability statistics and machine learning e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

José Unpingco

Python for

Probability,

Statistics,

and Machine

Learning

Python for Probability, Statistics, and Machine

Learning

José Unpingco San Diego, CA USA

Additional material to this book can be downloaded from http://extras.springer.com.

ISBN 978-3-319-30715-2 ISBN 978-3-319-30717-6 (eBook) DOI 10.1007/978-3-319-30717-

Library of Congress Control Number: 2016933108

© Springer International Publishing Switzerland 2016 This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, express or implied, with respect to the material contained herein or for any errors or omissions that may have been made.

Printed on acid-free paper

This Springer imprint is published by Springer Nature The registered company is Springer International Publishing AG Switzerland

To Irene, Nicholas, and Daniella, for all their

patient support.

work, especially when you must explain the results of your methods to a nontechnical audience. We have tried to use the Python language in the most expressive way possible while encouraging good Python coding practices.

Acknowledgments

I would like to acknowledge the help of Brian Granger and Fernando Perez, two of the originators of the Jupyter/IPython Notebook, for all their great work, as well as the Python community as a whole, for all their contributions that made this book possible. Additionally, I would also like to thank Juan Carlos Chavez for his thoughtful review. Hans Petter Langtangen is the author of the Doconce [19] document preparation system that was used to write this text. Thanks to Geoffrey Poore [31] for his work with PythonTeX and LATEX.

San Diego, California February 2016

viii Preface

Contents

  • 1 Getting Started with Scientific Python.
    • 1.1 Installation and Setup
    • 1.2 Numpy
      • 1.2.1 Numpy Arrays and Memory
      • 1.2.2 Numpy Matrices
      • 1.2.3 Numpy Broadcasting
      • 1.2.4 Numpy Masked Arrays
      • 1.2.5 Numpy Optimizations and Prospectus
    • 1.3 Matplotlib
      • 1.3.1 Alternatives to Matplotlib
      • 1.3.2 Extensions to Matplotlib
    • 1.4 IPython.
      • 1.4.1 IPython Notebook
    • 1.5 Scipy
    • 1.6 Pandas
      • 1.6.1 Series
      • 1.6.2 Dataframe
    • 1.7 Sympy
    • 1.8 Interfacing with Compiled Libraries
    • 1.9 Integrated Development Environments
    • 1.10 Quick Guide to Performance and Parallel Programming
    • 1.11 Other Resources.
    • References
  • 2 Probability
    • 2.1 Introduction.
      • 2.1.1 Understanding Probability Density
      • 2.1.2 Random Variables
      • 2.1.3 Continuous Random Variables
      • 2.1.4 Transformation of Variables Beyond Calculus
        • 2.1.5 Independent Random Variables
        • 2.1.6 Classic Broken Rod Example
    • 2.2 Projection Methods - 2.2.1 Weighted Distance
    • 2.3 Conditional Expectation as Projection - 2.3.1 Appendix
    • 2.4 Conditional Expectation and Mean Squared Error
      • Error Optimization 2.5 Worked Examples of Conditional Expectation and Mean Square
        • 2.5.1 Example
        • 2.5.2 Example
        • 2.5.3 Example
        • 2.5.4 Example
        • 2.5.5 Example
        • 2.5.6 Example
    • 2.6 Information Entropy - 2.6.1 Information Theory Concepts - 2.6.2 Properties of Information Entropy - 2.6.3 Kullback-Leibler Divergence
    • 2.7 Moment Generating Functions
    • 2.8 Monte Carlo Sampling Methods. - 2.8.1 Inverse CDF Method for Discrete Variables - 2.8.2 Inverse CDF Method for Continuous Variables - 2.8.3 Rejection Method.
    • 2.9 Useful Inequalities - 2.9.1 Markov’s Inequality - 2.9.2 Chebyshev’s Inequality - 2.9.3 Hoeffding’s Inequality
    • References
  • 3 Statistics
    • 3.1 Introduction.
    • 3.2 Python Modules for Statistics - 3.2.1 Scipy Statistics Module. - 3.2.2 Sympy Statistics Module. - 3.2.3 Other Python Modules for Statistics
    • 3.3 Types of Convergence - 3.3.1 Almost Sure Convergence - 3.3.2 Convergence in Probability - 3.3.3 Convergence in Distribution - 3.3.4 Limit Theorems
    • 3.4 Estimation Using Maximum Likelihood - 3.4.1 Setting Up the Coin Flipping Experiment - 3.4.2 Delta Method
    • 3.5 Hypothesis Testing and P-Values
      • 3.5.1 Back to the Coin Flipping Example
      • 3.5.2 Receiver Operating Characteristic.
      • 3.5.3 P-Values
      • 3.5.4 Test Statistics
      • 3.5.5 Testing Multiple Hypotheses
    • 3.6 Confidence Intervals
    • 3.7 Linear Regression
      • 3.7.1 Extensions to Multiple Covariates
    • 3.8 Maximum A-Posteriori
    • 3.9 Robust Statistics
    • 3.10 Bootstrapping
      • 3.10.1 Parametric Bootstrap
    • 3.11 Gauss Markov
    • 3.12 Nonparametric Methods
      • 3.12.1 Kernel Density Estimation.
      • 3.12.2 Kernel Smoothing
      • 3.12.3 Nonparametric Regression Estimators
      • 3.12.4 Nearest Neighbors Regression
      • 3.12.5 Kernel Regression
      • 3.12.6 Curse of Dimensionality
    • References
  • 4 Machine Learning
    • 4.1 Introduction.
    • 4.2 Python Machine Learning Modules
    • 4.3 Theory of Learning
      • 4.3.1 Introduction to Theory of Machine Learning
      • 4.3.2 Theory of Generalization.
        • Complexity 4.3.3 Worked Example for Generalization/Approximation
      • 4.3.4 Cross-Validation
      • 4.3.5 Bias and Variance
      • 4.3.6 Learning Noise
    • 4.4 Decision Trees.
      • 4.4.1 Random Forests
    • 4.5 Logistic Regression
      • 4.5.1 Generalized Linear Models
    • 4.6 Regularization
      • 4.6.1 Ridge Regression
      • 4.6.2 Lasso
    • 4.7 Support Vector Machines
      • 4.7.1 Kernel Tricks
    • 4.8 Dimensionality Reduction
      • 4.8.1 Independent Component Analysis.
    • 4.9 Clustering
    • 4.10 Ensemble Methods
      • 4.10.1 Bagging
      • 4.10.2 Boosting
    • References
  • Index

∝ Proportional to ≜ Equal by definition :¼ Equal by definition ⊥ Perpendicular to ∴ Therefore ⟹ Implies ≡ Equivalent to X Matrix X x Vector x sgn(x) Sign of x R Real line Rn^ n-dimensional vector space Rmn^ m × n-dimensional matrix space U (^) ða;bÞ Uniform distribution on the interval (a, b) N (^) ðμ; σ (^2) Þ Normal distribution with mean μ and variance σ^2

! as (^) Converges almost surely

! d (^) Converges in distribution

! P (^) Converges in probability

xiv Notation

About the Author

Dr. José Unpingco earned his PhD from the University of California, San Diego in 1998 and has since worked in industry as an engineer, consultant, and instructor on a wide-variety of advanced data processing and analysis topics, with a rich experience in multiple machine learning technologies. He has been the onsite technical director for large-scale signal and image processing for the Department of Defense (DoD), where he also spearheaded the DoD-wide adoption of the Scientific Python. As the primary Scientific Python instructor for the DoD, he has taught Python to over 600 scientists and engineers. He is currently the technical director for data science for a non-profit medical research organization in San Diego, California.

xv

2 1 Getting Started with Scientific Python

example, the same script that runs on a Windows laptop can also run on a Linux-based supercomputer or on a mobile phone. This makes programming easier because the virtual machine handles the low-level details of implementing the business logic of the script on the underlying platform. Python is a dynamically typed language, which means that the interpreter itself figures out the representative types (e.g., floats, integers) interactively or at run-time. This is in contrast to a language like Fortran that have compilers that study the code from beginning to end, perform many compiler-level optimizations, link intimately with the existing libraries on a specific platform, and then create an executable that is henceforth liberated from the compiler. As you may guess, the compiler’s access to the details of the underlying platform means that it can utilize optimizations that exploit chip-specific features and cache memory. Because the virtual machine abstracts away these details, it means that the Python language does not have pro- grammable access to these kinds of optimizations. So, where is the balance between the ease of programming the virtual machine and these key numerical optimizations that are crucial for scientific work? The balance comes from Python’s native ability to bind to compiled Fortran and C libraries. This means that you can send intensive computations to compiled libraries directly from the interpreter. This approach has two primary advantages. First, it give you the fun of programming in Python, with its expressive syntax and lack of visual clutter. This is a particular boon to scientists who typically want to use software as a tool as opposed to developing software as a product. The second advantage is that you can mix-and-match different compiled libraries from diverse research areas that were not otherwise designed to work together. This works because Python makes it easy to allocate and fill memory in the interpreter, pass it as input to compiled libraries, and then retrieve the output back at the interpreter. Moreover, Python provides a multiplatform solution for scientific codes. As an open-source project, Python itself is available anywhere you can build it, even though it typically comes standard nowadays, as part of many operating systems. This means that once you have written your code in Python, you can just transfer the script to another platform and run it, as long as the compiled libraries are also available there. What if the compiled libraries are absent? Building and configuring compiled libraries across multiple systems used to be a painstaking job, but as scientific Python has matured, a wide range of libraries have now become available across all of the major platforms (i.e., Windows, MacOS, Linux, Unix) as prepackaged distributions. Finally, scientific Python facilitates maintainability of scientific codes because Python syntax is clean, free of semi-colon litter and other visual distractions that makes code hard to read and easy to obfuscate. Python has many built-in testing, documentation, and development tools that ease maintenance. Scientific codes are usually written by scientists unschooled in software development, so having solid software development tools built into the language itself is a particular boon.

1.1 Installation and Setup 3

1.1 Installation and Setup

The easiest way to get started is to download the freely available Anaconda distrib- ution provided by Continuum Analytics (continuum.io), which is available for all of the major platforms. On Linux, even though most of the toolchain is available via the built-in Linux package manager, it is still better to install the Anaconda distri- bution because it provides its own powerful package manager (i.e., conda) that can keep track of changes in the software dependencies of the packages that it supports. Note that if you do not have administrator privileges, there is also a corresponding miniconda distribution that does not require these privileges. Regardless of your platform, we recommend Python version 2.7. Python 2.7 is the last of the Python 2.x series and guarantees backwards compatibility with legacy codes. Python 3.x makes no such guarantees. Although all of the key components of scientific Python are available in version 3.x, the safest bet is to stick with version 2.7. Alternatively, one compromise is to write in a hybrid dialect of Python that is the intersection of elements of versions 2.7 and 3.x. The six module enables this transition by providing utility functions for 2.5 and newer codes. There is also a Python 2.7 to 3.x converter available as the 2to3 module but it may be hard to debug or maintain the so-converted code; nonetheless, this might be a good option for small, self-contained libraries that do not require further development or maintenance. You may have encountered other Python variants on the web, such as IronPython (Python implemented in C#) and Jython (Python implemented in Java). In this text, we focus on the C-implementation of Python (i.e., known as CPython ), which is, by far, the most popular implementation. These other Python variants permit specialized, native interaction with libraries in C# or Java (respec- tively), which is still possible (but clunky) using the CPython. Even more Python variants exist that implement the low-level machinery of Python differently for vari- ous reasons, beyond interacting with native libraries in other languages. Most notable of these is Pypy that implements a just-in-time compiler (JIT) and other powerful optimizations that can substantially speed up pure Python codes. The downside of Pypy is that its coverage of some popular scientific modules (e.g., Matplotlib, Scipy) is limited or non-existent which means that you cannot use those modules in code meant for Pypy. You may later want to use a Python module that is not maintained by Anaconda’s conda manager. Because Anaconda comes with the pip package manager, which is the main one used outside of scientific Python, you can simply do

Terminal> pip install package_name

and pip will run out to the web and download the package you want and its dependen- cies and install them in the existing Anaconda directory tree. This works beautifully in the case where the package in question is pure-Python, without any system-specific dependencies. Otherwise, this can be a real nightmare, especially on Windows, which lacks freely available Fortran compilers. If the module in question is a C-library, one way to cope is to install the freely available Visual Studio Community Edition,

1.2 Numpy 5

Numpy provides specification of byte-sized arrays in Python. For example, below we create an array of three numbers, each of four-bytes long (32 bits at 8 bits per byte) as shown by the itemsize property. The first line imports Numpy as np, which is the recommended convention. The next line creates an array of 32 bit floating point numbers. The itemize property shows the number of bytes per item.

import numpy as np # recommended convention x = np.array([1,2,3],dtype=np.float32) x array([ 1., 2., 3.], dtype=float32) x.itemsize 4

In addition to providing uniform containers for numbers, Numpy provides a com- prehensive set of unary functions (i.e., ufuncs ) that process arrays element-wise with- out additional looping semantics. Below, we show how to compute the element-wise sine using Numpy,

np.sin(np.array([1,2,3],dtype=np.float32) ) array([ 0.84147096, 0.90929741, 0.14112 ], dtype=float32)

This computes the sine of the input array [1,2,3], using Numpy’s unary function, np.sin. There is another sine function in the built-in math module, but the Numpy version is faster because it does not require explicit looping (i.e., using a for loop) over each of the elements in the array. That looping happens in the compiled np.sin function itself. Otherwise, we would have to do looping explicitly as in the following:

from math import sin [sin(i) for i in [1,2,3]] # list comprehension [0.8414709848078965, 0.9092974268256817, 0.1411200080598672]

Numpy uses common-sense casting rules to resolve the output types. For example, if the inputs had been an integer-type, the output would still have been a floating point type. In this example, we provided a Numpy array as input to the sine function. We could have also used a plain Python list instead and Numpy would have built the intermediate Numpy array (e.g., np.sin([1,1,1])). The Numpy documentation provides a comprehensive (and very long) list of available ufuncs. Numpy arrays come in many dimensions. For example, the following shows a two-dimensional 2 × 3 array constructed from two conforming Python lists.

x=np.array([ [1,2,3],[4,5,6] ]) x.shape (2, 3)

Note that Numpy is limited to 32 dimensions unless you build it for more. 2 Numpy arrays follow the usual Python slicing rules in multiple dimensions as shown below where the : colon character selects all elements along a particular axis.

x=np.array([ [1,2,3],[4,5,6] ]) x[:,0] # 0th column array([1, 4]) x[:,1] # 1st column array([2, 5])

(^2) See arrayobject.h in the Numpy source code.

6 1 Getting Started with Scientific Python

x[0,:] # 0th row array([1, 2, 3]) x[1,:] # 1st row array([4, 5, 6])

You can also select sub-sections of arrays by using slicing as shown below.

x=np.array([ [1,2,3],[4,5,6] ]) x array([[1, 2, 3], [4, 5, 6]]) x[:,1:] # all rows, 1st thru last column array([[2, 3], [5, 6]]) x[:,::2] # all rows, every other column array([[1, 3], [4, 6]]) x[:,::-1] # reverse order of columns array([[3, 2, 1], [6, 5, 4]])

1.2.1 Numpy Arrays and Memory

Some interpreted languages implicitly allocate memory. For example, in Matlab, you can extend a matrix by simply tacking on another dimension as in the following Matlab session:

x=ones(3,3) x = 1 1 1 1 1 1 1 1 1 x(:,4)=ones(3,1) % tack on extra dimension x = 1 1 1 1 1 1 1 1 1 1 1 1 size(x) ans = 3 4

This works because Matlab arrays use pass-by-value semantics so that slice opera- tions actually copy parts of the array as needed. By contrast, Numpy uses pass-by- reference semantics so that slice operations are views into the array without implicit copying. This is particularly helpful with large arrays that already strain available memory. In Numpy terminology, slicing creates views (no copying) and advanced indexing creates copies. Let’s start with advanced indexing. If the indexing object (i.e., the item between the brackets) is a non-tuple sequence object, another Numpy array (of type integer or boolean), or a tuple with at least one sequence object or Numpy array, then indexing creates copies. For the above example, to accomplish the same array extension in Numpy, you have to do something like the following