Docsity

introduction statistics with python, Notas de estudo de Engenharia Elétrica

Toggle sidebar
bg1
Statistics and Computing
ThomasHaslwanter
An Introduction
to Statistics
with Python
With Applications in the Life Sciences
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe introduction statistics with python e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

Statistics and Computing

Thomas Haslwanter

An Introduction

to Statistics

with Python

With Applications in the Life Sciences

Statistics and Computing

Series editor W.K. Härdle

Thomas Haslwanter

An Introduction to Statistics

with Python

With Applications in the Life Sciences

123

Thomas Haslwanter School of Applied Health and Social Sciences University of Applied Sciences Upper Austria Linz, Austria

Series Editor: W.K. Härdle C.A.S.E. Centre for Applied Statistics and Economics School of Business and Economics Humboldt-Universität zu Berlin Unter den Linden 6 10099 Berlin Germany

The Python code samples accompanying the book are available at www.quantlet.de. All Python programs and data sets can be found on GitHub: https://github.com/thomas- haslwanter/statsintro_python.git. Links to all material are available at http://www.springer. com/de/book/9783319283159. The Python solution codes in the appendix are published under the Creative Commons Attribution-ShareAlike 4.0 International License.

ISSN 1431-8784 ISSN 2197-1706 (electronic) Statistics and Computing ISBN 978-3-319-28315-9 ISBN 978-3-319-28316-6 (eBook) DOI 10.1007/978-3-319-28316-

Library of Congress Control Number: 2016939946

© 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

Preface

In the data analysis for my own research work, I was often slowed down by two things: (1) I did not know enough statistics, and (2) the books available would provide a theoretical background, but no real practical help. The book you are holding in your hands (or on your tablet or laptop) is intended to be the book that will solve this very problem. It is designed to provide enough basic understanding so that you know what you are doing, and it should equip you with the tools you need. I believe that the Python solutions provided in this book for the most basic statistical problems address at least 90 % of the problems that most physicists, biologists, and medical doctors encounter in their work. So if you are the typical graduate student working on a degree, or a medical researcher analyzing the latest experiments, chances are that you will find the tools you require here—explanation and source-code included. This is the reason I have focused on statistical basics and hypothesis tests in this book and refer only briefly to other statistical approaches. I am well aware that most of the tests presented in this book can also be carried out using statistical modeling. But in many cases, this is not the methodology used in many life science journals. Advanced statistical analysis goes beyond the scope of this book and—to be frank— exceeds my own knowledge of statistics. My motivation for providing the solutions in Python is based on two considera- tions. One is that I would like them to be available to everyone. While commercial solutions like Matlab , SPSS , Minitab , etc., offer powerful tools, most can only use them legally in an academic setting. In contrast, Python is completely free (“as in free beer” is often heard in the Python community). The second reason is that Python is the most beautiful coding language that I have yet encountered; and around 2010 Python and its documentation matured to the point where one can use it without being a serious coder. Together, this book, Python , and the tools that the Python ecosystem offers today provide a beautiful, free package that covers all the statistics that most researchers will need in their lifetime.

vii

Preface ix

with a working example for each test presented in this book. They also include the code used to generate the pictures in this book, as well as the data used to run the programs. The Python code samples accompanying the book are available at http://www. quantlet.de. All Python programs and data sets can be found on GitHub: https:// github.com/thomas-haslwanter/statsintro_python.git. Links to all material are avail- able at http://www.springer.com/de/book/9783319283159.

Acknowledgments

Python is built on the contributions from the user community, and some of the sections in this book are based on some of the excellent information available on the web. (Permission has been granted by the authors to reprint their contributions here.) I especially want to thank the following people:

  • Paul E. Johnson read the whole manuscript and provided invaluable feedback on the general structure of the book, as well as on statistical details.
  • Connor Johnson wrote a very nice blog explaining the results of the statsmodels OLS command, which provided the basis for the section on Statistical Models.
  • Cam Davidson Pilon wrote the excellent open source e-book Probabilistic- Programming-and-Bayesian-Methods-for-Hackers. From there I took the exam- ple of the Challenger disaster to demonstrate Bayesian statistics.
  • Fabian Pedregosa’s blog on ordinal logistic regression allowed me to include this topic, which otherwise would be admittedly beyond my own skills. I also want to thank Carolyn Mayer for reading the manuscript and replacing colloquial expressions with professional English. And a special hug goes to my wife, who not only provided important suggestions for the structure of the book, but also helped with tips on how to teach programming, and provided support with all the tea-related aspects of the book. If you have a suggestion or correction, please send an email to my work address [email protected]. If I make a change based on your feedback, I will add you to the list of contributors unless advised otherwise. If you include at least part of the sentence the error appears in, that makes it easy for me to search. Page and section numbers are fine, too, but not as easy to work with. Thanks!

Linz, Austria Thomas Haslwanter December 2015

  • More information about this series at http://www.springer.com/series/
  • 1 Why Statistics? Part I Python and Statistics
  • 2 Python
  • 2.1 Getting Started..
  • 2.1.1 Conventions
  • 2.1.2 Distributions and Packages..
  • 2.1.3 Installation of Python
  • 2.1.4 Installation of R and rpy2
  • 2.1.5 Personalizing IPython/ Jupyter
  • 2.1.6 Python Resources
  • 2.1.7 First Python Programs
  • 2.2 Python Data Structures
  • 2.2.1 Python Datatypes
  • 2.2.2 Indexing and Slicing
  • 2.2.3 Vectors and Arrays
  • 2.3 IPython/ Jupyter : An Interactive Programming Environment
  • 2.3.1 First Session with the Qt Console
  • 2.3.2 Notebook and rpy2
  • 2.3.3 IPython Tips
  • 2.4 Developing Python Programs
  • Python Program.. 2.4.1 Converting Interactive Commands into a
  • 2.4.2 Functions, Modules, and Packages
  • 2.4.3 Python Tips
  • 2.4.4 Code Versioning
  • 2.5 Pandas: Data Structures for Statistics
  • 2.5.1 Data Handling
  • 2.5.2 Grouping
  • 2.6 Statsmodels: Tools for Statistical Modeling
  • 2.7 Seaborn: Data Visualization
  • 2.8 General Routines xii Contents
  • 2.9 Exercises
  • 3 Data Input
  • 3.1 Input from Text Files
  • 3.1.1 Visual Inspection
  • 3.1.2 Reading ASCII-Data into Python
  • 3.2 Input from MS Excel
  • 3.3 Input from Other Formats
  • 3.3.1 Matlab
  • 4 Display of Statistical Data
  • 4.1 Datatypes
  • 4.1.1 Categorical
  • 4.1.2 Numerical
  • 4.2 Plotting in Python
  • to Plotting 4.2.1 Functional and Object-Oriented Approaches
  • 4.2.2 Interactive Plots
  • 4.3 Displaying Statistical Datasets.
  • 4.3.1 Univariate Data
  • 4.3.2 Bivariate and Multivariate Plots
  • 4.4 Exercises
  • 5 Background Part II Distributions and Hypothesis Tests
  • 5.1 Populations and Samples
  • 5.2 Probability Distributions
  • 5.2.1 Discrete Distributions
  • 5.2.2 Continuous Distributions
  • 5.2.3 Expected Value and Variance
  • 5.3 Degrees of Freedom
  • 5.4 Study Design
  • 5.4.1 Terminology
  • 5.4.2 Overview
  • 5.4.3 Types of Studies
  • 5.4.4 Design of Experiments
  • 5.4.5 Personal Advice
  • 5.4.6 Clinical Investigation Plan
  • 6 Distributions of One Variable
  • 6.1 Characterizing a Distribution
  • 6.1.1 Distribution Center
  • 6.1.2 Quantifying Variability
  • 6.1.3 Parameters Describing the Form of a Distribution
  • 6.1.4 Important Presentations of Probability Densities
  • 6.2 Discrete Distributions Contents xiii
  • 6.2.1 Bernoulli Distribution
  • 6.2.2 Binomial Distribution
  • 6.2.3 Poisson Distribution
  • 6.3 Normal Distribution
  • 6.3.1 Examples of Normal Distributions
  • 6.3.2 Central Limit Theorem
  • 6.3.3 Distributions and Hypothesis Tests
  • Distribution 6.4 Continuous Distributions Derived from the Normal
  • 6.4.1 t -Distribution..
  • 6.4.2 Chi-Square Distribution
  • 6.4.3 F -Distribution..
  • 6.5 Other Continuous Distributions
  • 6.5.1 Lognormal Distribution
  • 6.5.2 Weibull Distribution
  • 6.5.3 Exponential Distribution
  • 6.5.4 Uniform Distribution
  • 6.6 Exercises
  • 7 Hypothesis Tests
  • 7.1 Typical Analysis Procedure
  • 7.1.1 Data Screening and Outliers
  • 7.1.2 Normality Check..
  • 7.1.3 Transformation..
  • 7.2 Hypothesis Concept, Errors, p -Value, and Sample Size
  • 7.2.1 An Example
  • 7.2.2 Generalization and Applications
  • 7.2.3 The Interpretation of the p -Value
  • 7.2.4 Types of Error..
  • 7.2.5 Sample Size
  • 7.3 Sensitivity and Specificity
  • 7.3.1 Related Calculations
  • 7.4 Receiver-Operating-Characteristic (ROC) Curve
  • 8 Tests of Means of Numerical Data
  • 8.1 Distribution of a Sample Mean
  • 8.1.1 One Sample t -Test for a Mean Value
  • 8.1.2 Wilcoxon Signed Rank Sum Test
  • 8.2 Comparison of Two Groups
  • 8.2.1 Paired t -Test.
  • 8.2.2 t -Test between Independent Groups
  • Mann–Whitney Test 8.2.3 Nonparametric Comparison of Two Groups:
  • 8.2.4 Statistical Hypothesis Tests vs Statistical Modeling
  • 8.3 Comparison of Multiple Groups xiv Contents
  • 8.3.1 Analysis of Variance (ANOVA)..
  • 8.3.2 Multiple Comparisons
  • 8.3.3 Kruskal–Wallis Test
  • 8.3.4 Two-Way ANOVA
  • 8.3.5 Three-Way ANOVA
  • 8.4 Summary: Selecting the Right Test for Comparing Groups
  • 8.4.1 Typical Tests
  • 8.4.2 Hypothetical Examples
  • 8.5 Exercises
  • 9 Tests on Categorical Data
  • 9.1 One Proportion
  • 9.1.1 Confidence Intervals
  • 9.1.2 Explanation
  • 9.1.3 Example
  • 9.2 Frequency Tables
  • 9.2.1 One-Way Chi-Square Test.
  • 9.2.2 Chi-Square Contingency Test
  • 9.2.3 Fisher’s Exact Test
  • 9.2.4 McNemar’s Test
  • 9.2.5 Cochran’s Q Test
  • 9.3 Exercises
  • 10 Analysis of Survival Times
  • 10.1 Survival Distributions
  • 10.2 Survival Probabilities
  • 10.2.1 Censorship
  • 10.2.2 Kaplan–Meier Survival Curve
  • 10.3 Comparing Survival Curves in Two Groups
  • 11 Linear Regression Models Part III Statistical Modeling
  • 11.1 Linear Correlation
  • 11.1.1 Correlation Coefficient
  • 11.1.2 Rank Correlation..
  • 11.2 General Linear Regression Model
  • 11.2.1 Example 1: Simple Linear Regression..
  • 11.2.2 Example 2: Quadratic Fit.
  • 11.2.3 Coefficient of Determination
  • 11.3 Patsy: The Formula Language
  • 11.3.1 Design Matrix..
  • 11.4 Linear Regression Analysis with Python
  • 11.4.1 Example 1: Line Fit with Confidence Intervals
  • 11.4.2 Example 2: Noisy Quadratic Polynomial..
  • 11.5 Model Results of Linear Regression Models
  • 11.5.1 Example: Tobacco and Alcohol in the UK Contents xv
  • 11.5.2 Definitions for Regression with Intercept
  • 11.5.3 The R^2 Value
  • 11.5.4 R N^2 : The Adjusted R^2 Value
  • 11.5.5 Model Coefficients and Their Interpretation
  • 11.5.6 Analysis of Residuals.
  • 11.5.7 Outliers
  • 11.5.8 Regression Using Sklearn
  • 11.5.9 Conclusion
  • 11.6 Assumptions of Linear Regression Models
  • 11.7 Interpreting the Results of Linear Regression Models
  • 11.8 Bootstrapping
  • 11.9 Exercises
  • 12 Multivariate Data Analysis
  • 12.1 Visualizing Multivariate Correlations
  • 12.1.1 Scatterplot Matrix
  • 12.1.2 Correlation Matrix
  • 12.2 Multilinear Regression
  • 13 Tests on Discrete Data
  • 13.1 Comparing Groups of Ranked Data
  • 13.2 Logistic Regression
  • 13.2.1 Example: The Challenger Disaster
  • 13.3 Generalized Linear Models
  • 13.3.1 Exponential Family of Distributions
  • 13.3.2 Linear Predictor and Link Function
  • 13.4 Ordinal Logistic Regression
  • 13.4.1 Problem Definition
  • 13.4.2 Optimization
  • 13.4.3 Code
  • 13.4.4 Performance..
  • 14 Bayesian Statistics
  • 14.1 Bayesian vs. Frequentist Interpretation
  • 14.1.1 Bayesian Example
  • 14.2 The Bayesian Approach in the Age of Computers..
  • with a Markov-Chain–Monte-Carlo Simulation 14.3 Example: Analysis of the Challenger Disaster
  • 14.4 Summing Up
  • Solutions
  • Glossary
  • References
  • Index

Part I

Python and Statistics

The first part of the book presents an introduction to statistics based on Python. It is impossible to cover the whole language in 30 or 40 pages, so if you are a beginner, please see one of the excellent Python introductions available in the internet for details. Links are given below. This part is a kick-start for Python ; it shows how to install Python under Windows, Linux, or MacOS, and goes step-by-step through documented programming examples. Tips are included to help avoid some of the problems frequently encountered while learning Python. Because most of the data for statistical analysis are commonly obtained from text files, Excel files, or data preprocessed by Matlab, the second chapter presents simple ways to import these types of data into Python. The last chapter of this part illustrates various ways of visualizing data in Python. Since the flexibility of Python for interactive data analysis has led to a certain complexity that can frustrate new Python programmers, the code samples presented in Chap. 3 for various types of interactive plots should help future Pythonistas avoid these problems.

Chapter 1

Why Statistics?

Statistics is the explanation of variance in the light of what remains unexplained. Every day we are confronted with situations with uncertain outcomes, and must make decisions based on incomplete data: “Should I run for the bus? Which stock should I buy? Which man should I marry? Should I take this medication? Should I have my children vaccinated?” Some of these questions are beyond the realm of statistics (“Which person should I marry?”), because they involve too many unknown variables. But in many situations, statistics can help extract maximum knowledge from information given, and clearly spell out what we know and what we don’t know. For example, it can turn a vague statement like “This medication may cause nausea,” or “You could die if you don’t take this medication” into a specific statement like “Three patients in one thousand experience nausea when taking this medication,” or “If you don’t take this medication, there is a 95 % chance that you will die.” Without statistics, the interpretation of data can quickly become massively flawed. Take, for example, the estimated number of German tanks produced during World War II, also known as the “German Tank Problem.” The estimate of the number of German tanks produced per month from standard intelligence data was 1,550 ; however, the statistical estimate based on the number of tanks observed was 327 , which was very close to the actual production number of 342 (http://en. wikipedia.org/wiki/German_tank_problem). Similarly, using the wrong tests can also lead to erroneous results. In general, statistics will help to

  • Clarify the question.
  • Identify the variable and the measure of that variable that will answer that question.
  • Determine the required sample size.

© Springer International Publishing Switzerland 2016 T. Haslwanter, An Introduction to Statistics with Python , Statistics and Computing, DOI 10.1007/978-3-319-28316-6_

3