Big Data

profileramswork
2015DataScienceBigDataAnalytics.pdf

Data Science & Big Data Analytics

Discovering, Analyzing, Visualizing and Presenting Data

EMC Education Services

WILEY

'

Data Science & Big Data Analytics: Discovering, Analyzing, Visualizing and Presenting Data

Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www. wiley. com

Copyright© 2015 by John Wiley & Sons, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-1-118-87613-8 ISBN: 978-1-118-87622-0 (ebk) ISBN: 978-1-118-87605-3 (ebk)

Manufactured in the United States of America

10987654321

No part ofthis publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis- sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http: I /www. wiley. com/ go/permissions.

limit ofliability/DisclaimerofWarranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or website may provide or recommendations it may make. Further, readers should be aware that Internet websites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 orfax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand.lf this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http: I /book support. wiley. com. For more information about Wiley products, visit www. wiley. com.

library of Congress Control Number: 2014946681

Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other coun- tries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.

Credits

Executive Editor

Carol Long

Project Editor

Kelly Talbot Production Manager

Kathleen Wisor Copy Editor

Karen Gill Manager of Content Development

and Assembly

Mary Beth Wakefield Marketing Director

David Mayhew

Marketing Manager

Carrie Sherrill

Professional Technology and Strategy Director

Barry Pruett

Business Manager

Amy Knies Associate Publisher

Jim Minatel Project Coordinator, Cover

Patrick Redmond Proofreader

Nancy Carrasco Indexer

Johnna Van Hoose Dinse Cover Designer

Mallesh Gurram

About the Key Contributors

David Dietrich heads the data science education team within EMC Education Services, where he leads the

curriculum, strategy and course development related to Big Data Analytics and Data Science. He co-au- thored the first course in EMC's Data Science curriculum, two additional EMC courses focused on teaching leaders and executives about Big Data and data science, and is a contributing author and editor of this

book. He has filed 14 patents in the areas of data science, data privacy, and cloud computing. David has been an advisor to severa l universities looking to develop academic programs related to data

analytics, and has been a frequent speaker at conferences and industry events. He also has been a a guest lecturer at universi- ties in the Boston area. His work has been featured in major publications including Forbes, Harvard Business Review, and the 2014 Massachusetts Big Data Report, commissioned by Governor Deval Patrick.

Involved with analytics and technology for nearly 20 years, David has worked with many Fortune 500 companies over his career, holding multiple roles involving analytics, including managing analytics and operations teams, delivering analytic con-

sulting engagements, managing a line of analytical software products for regulating the US banking industry, and developing Sohware-as-a-Service and BI-as-a-Service offerings. Additionally, David collaborated with the U.S. Federal Reserve in develop-

ing predictive models for monitoring mortgage portfolios. Barry Heller is an advisory technical education consultant at EMC Education Services. Barry is a course developer and cur-

riculum advisor in the emerging technology areas of Big Data and data science. Prior to his current role, Barry was a consul- tant research scientist leading numerous analytical initiatives within EMC's Total Customer Experience organization. Early in his EMC career, he managed the statistical engineering group as well as led the

data warehousing efforts in an Enterprise Resource Planning (ERP) implementation. Prior to joining EMC,

Barry held managerial and analytical roles in reliability engineering functions at medical diagnostic and technology companies. During his career, he has applied his quantitative skill set to a myriad of business applications in the Customer Service, Engineering, Manufacturing, Sales/Marketing, Finance, and Legal

arenas. Underscoring the importance of strong executive stakeholder engagement, many of his successes

have resulted from not only focusing on the technical details of an analysis, but on the decisions that will be resulting from the analysis. Barry earned a B.S. in Computational Mathematics from the Rochester Institute ofTechnology and an M.A. in

Mathematics from the State University of New York (SUNY) New Paltz. Beibei Yang is a Technical Education Consultant of EMC Education Services, responsible for developing severa l open courses

at EMC related to Data Science and Big Data Analytics. Beibei has seven years of experience in the IT industry. Prior to EMC she worked as a sohware engineer, systems manager, and network manager for a Fortune 500 company where she introduced

new technologies to improve efficiency and encourage collaboration. Beibei has published papers to

prestigious conferences and has filed multiple patents. She received her Ph.D. in computer science from the University of Massachusetts Lowell. She has a passion toward natural language processing and data

mining, especially using various tools and techniques to find hidden patterns and tell stories with data. Data Science and Big Data Analytics is an exciting domain where the potential of digital information is maximized for making intelligent business decisions. We believe that this is an area that will attract a lot of talented students and professionals in the short, mid, and long term.

Acknowledgments

EMC Education Services embarked on learning this subject with the intent to develop an "open" curriculum and certification. It was a challenging journey at the time as not many understood what it would take to be a true

data scientist. After initial research (and struggle), we were able to define what was needed and attract very talented professionals to work on the project. The course, "Data Science and Big Data Analytics," has become

well accepted across academia and the industry. Led by EMC Education Services, this book is the result of efforts and contributions from a number of key EMC organizations and supported by the office of the CTO, IT, Global Services, and Engineering. Many sincere

thanks to many key contributors and subject matter experts David Dietrich, Barry Heller, and Beibei Yang for their work developing content and graphics for the chapters. A special thanks to subject matter experts John Cardente and Ganesh Rajaratnam for their active involvement reviewing multiple book chapters and

providing valuable feedback throughout the project.

We are also grateful to the fol lowing experts from EMC and Pivotal for their support in reviewing and improving the content in this book:

Aidan O'Brien Joe Kambourakis

Alexander Nunes Joe Milardo

Bryan Miletich John Sopka

Dan Baskette Kathryn Stiles

Daniel Mepham Ken Taylor

Dave Reiner Lanette Wells

Deborah Stokes Michael Hancock

Ellis Kriesberg Michael Vander Donk

Frank Coleman Narayanan Krishnakumar

Hisham Arafat Richard Moore

Ira Schild Ron Glick

Jack Harwood Stephen Maloney

Jim McGroddy Steve Todd

Jody Goncalves Suresh Thankappan

Joe Dery Tom McGowan

We also thank Ira Schild and Shane Goodrich for coordinating this project, Mallesh Gurram for the cover design, Chris Conroy and Rob Bradley for graphics, and the publisher, John Wiley and Sons, for timely support in bringing this book to the

industry.

Nancy Gessler

Director, Education Services, EMC Corporation

Alok Shrivastava

Sr. Director, Education Services, EMC Corporation

Contents Introduction ................ . .. . .....• . •.. ... .... •..... .. .. . .. . .......... .. ... . ..................... •.•...... xvii

Chapter 1 • Introduction to Big Data Analytics ................... . . . ....................... 1

1.1 Big Data Overview ..................... ....... .....•... • ...... . . . ........ • .. ... . . ... ....... ....... 2 1.1.1 Data Structures .. . .. . . . .. ................ ... ... . .. . ...... . .. .. .... . .................... ..... . .. . . . .. 5 1.1.2 Analyst Perspective on Data Repositories . ............................. . .......... .......•. ... ... .. .. 9

1.2 State of the Practice in Analytics ................................................................. . 11 1.2.1 Bl Versus Data Science .............. .... ....... . .. . ........... . . . .... . ....................... .. .... 12 1.2.2 Current Analytical Architecture ... . .... .• . . ................ .... .............. .... .... ...... •.. . ..... 13 1.2.3 Drivers of Big Data .................................................... . . . .. ................. .. ... . . 15 1.2.4 Emerging Big Data Ecosystem and a New Approach to Analytics .. ....... ...... . ............ .. ....... 16

1.3 Key Roles for the New Big Data Ecosystem ....... ..... ......... . ....... . ..... .. .................... 19 1.4 Examples of Big Data Analytics ... .... .......... .... . ... ....... ... .... . ...... . .................... 22 Summary .............. ............ ... ... ......... .... • ... •....... ........ .. • ..•... . ................ 23 Exercises ..................... .... ..... .. ...... . ......•......... .. .. . ... .... . ..•.................... 23 Bibliography ........................... .... .. ... ... ... •................... .. • ...... ..... ..... ....... 24

Chapter 2 • Data Analytics Lifecycle ..................................................... . 25 2.1 Data Analytics Lifecycle Overview ... ..... . ............. • ...... •.. ..... ...... • ... •............. . . . 26

2.1.1 Key Roles for a Successful Anolytics Project .... . .. . .... .... . ........ . .. .. . ..•......... •. •....... . .. . . 26 2.1.2 Background and Overview of Data Analytics Lifecyc/e .......................... . .......•... . ..... ... 28

2.2 Phase 1: Discovery ..... .. .. .. . ............................. . ..•..................... •........... . 30 2.2.1 Learning the Business Domain .. . ....... ... ..•.•. •.... . .. ..... . . .. . ...................•........... .30 2.2.2 Resources . . ... . ................... . ...... . ......................... ..... ............. •.......•.... 31 2.2.3 Framing the Problem ............•.... . ...................................•......... •.•.... . . ...... 32 2.2.41dentifying Key Stakeholders ... .. ....................... ... . ... ......... .... . ....... •. . .......... . . 33 2.2.51nterviewing the Analytics Sponsor ...... ........ ...... .. .......... .... ... .. ... ..... .. ........... ... 33 2.2.6 Developing Initial Hypotheses ................. .. . . . .. . . . .. . . . . ... .... .. ........... . . •............ . . 35 2.2.71dentifying Potential Data Sources . ... ...•. •.. .... . . .. . ......•. •.......... . ....... . ..... . ... . .. .. . . 35

2.3 Phase 2: Data Preparation ...........................................................•...•..•..... 36 2.3.1 Preparing the Analytic Sandbox ............... . ...................... ... •. •.......•.......... .. .... 37 2.3.2 Performing ETLT ..................................................................•.•.......•... .. . 38 2.3.3 Learning About the Data .. ..... . .............. .. ........................•.•.......•.•........ ..... . 39 2.3.4 Data Conditioning ....... .. ....•.......... . ....................... .. . .. . . . ......•. •............. .. .40 2.3.5 Survey and Visualize . . . ... .. .... .. .. ...... . . ..... .. . .................. . . •. ...... . .•.. .. .. .. . . . ..... 41 2.3.6 Common Tools for the Data Preparation Phase . . . .... .. ..... ....... . •......... •.• .•.. .. ..... .. .. . . .42

2.4 Phase 3: Model Planning ............................•................. . ... . .. •..... .....•........ 42 2.4.1 Data Exploration and Variable Selection . . ... . . .. . ......... •... . ... . . ........ . .............. .. .. . . . .44 2.4.2 Model Selection . ... ................ . .. . . . ................ •.......•...•.......................... . .45 2.4.3 Common Tools for the Model Planning Phase . ...........•....... . . •. ........................... . . . .45

CONTENTS

2.5 Phase 4: Model Building ...... .................. ...... •. ... ..... .... • ... •. . •. .. •.........•...•.... 46 2.5.1 Common Tools for the Mode/Building Phase ...... .. .. . ..... .. ..... . ....... . .. . . .. . . .. . .... . . .. . .... 48

2.6 Phase 5: Communicate Results ......... .... ...... . ... •........ ........ ... . •..... .....•. ..... •.... 49 2.7 Phase 6: Operationalize ... ... ....... ... . .. ........ ....... ... ........... •. . •. . ... ....... .......... SO 2.8 Case Study: Global Innovation Network and Analysis (GINA) ................. •...................... 53

2.8.1 Phase 1: Discovery ................................................................................. 54 2.8.2 Phase 2: Data Preparation .... •........ . ...................................................... . .... 55 2.8.3 Phase 3: Model Planning . . . ...•.•. . . .. . . ..... .. . . .. . ..... .. .. ... ...... . . . ................... . . . .. . . 56 2.8.4 Phase 4: Mode/Building ..... . ....•.. .. .. .......... . .............. . . .. . ... . . ....... .. . .... ... . .. . . . 56 2.8.5 Phase 5: Communicate Results .. . . ..... . ...... .. ...... ... .. . .. . . ..................... ...... ........ 58 2.8.6 Phase 6: Operationalize . . ... ......•..... ..• .. . . . .. . . ..............•................................ 59

Summary ................................. • ................. •..•.. •.......•.....••........ . ....•.... 60 Exercises .................................•.... .. ..............•. . •....................... . . . . . •.... 61 Bibliography ....• . .••...................................•.... . . • ..... .. ............................. 61

Chapter 3 • Review of Basic Data Analytic Methods Using R . . . . . . .. . ... . .. .. . ... . . . . . .. ... . 63

3.1 Introduction toR ............................ ... .................................... ..... ......... 64 3.1.1 R Graphical User Interfaces . ............ . ............................... ...... . .. ... . . . ... ....... ... 67 3.1.2 Data Import and Export. . ......... . .. ............. ........... ........... .................... ....... 69 3.1.3 Attribute and Data Types . .......... .. ...... . ....................................................... 71 3.1.4 Descriptive Statistics ....................... . . . ..................................................... 79

3.2 Exploratory Data Analysis .............. • ... . .• •.............•........... . .................... .... 80 3.2.1 Visualization Before Analysis ........ . ..................................................•........... 82 3.2.2 Dirty Data ............ .. ................................................ . ........... ...•...... .... . 85 3.2.3 Visualizing a Single Variable ........ •.. . ................ .. .. . . ........... . .... ....... •.. . . . .... .. . . 88 3.2.4 Examining Multiple Variables . .... .... ....• . .. . ... .......... .............. ...... . .. .. .............. 91 3.2.5 Data Exploration Versus Presentation ...... . ........ •. . . . .. . . ..... ...... ................... ...... .. 99

3.3 Statistical Methods for Evaluation .................... . .. .• ......... ... . .. .................... . .. 101 3.3.1 Hypothesis Testing ........ ........ .......... .... ............................ . .. . ...... .. ...... . ... 102 3.3.2 Difference of Means ...... . .... .. . .... ..... . ..................................................... 704 3.3.3 Wilcoxon Rank-Sum Test ................•........................ ... .. . ... . .................. •... 108 3.3.4 Type I and Type II Errors ... . ...... . .. . .................. . ........ . .. .... .. ......................... 109 3.3.5 Power and Sample Size .....•.. . . .. . ... ...... . ........ ....... .............. ....... .. .... .......... 110 3.3.6 ANOVA ................. . .. ......... . . .... .. . . ... .... ........ . . .. ..... . ... .. .. .... . •. •.......•... . 110

Summary ...... ............. • ....... ...... ....• .. •... • ............................... •......•...... 114 Exercises ...... ......... ......................... . ............... ...... . ... ... ....... •............. 114 Bibliography ................................... . . . ................. .................. •.... . . .. . .... 11 5

Chapter 4 • Advanced Analytical Theory and Methods: Clustering .. . . .. . .. . ... . .. . . . ... . .. 117

4.1 Overview of Clustering ........ ...... ......... .. ................................................. 118 4.2 K-means ............... ....... ... ....................... .. ........ . ... . .......... . .... . .... .... 118

4.2.1 Use Cases ..... .. ............. . •.....• ... ... .. ..... ........ .......... . . .. ........ ...... ... .. . ...... 119 4.2.2 Overview of the Method . ............ ....... ... . .. ........ ................... ... ... .. . .•. ..... . .. . 120 4.2.3 Determining the Number of Clusters . . . .. .. •. •...................... . .......... ..... .. ... ...... . ... 123 4.2.4 Diagnostics .. ......................... ...•.... ........... ..... ....................... .. .. ....... . 128

CONTENTS

4.2.5 Reasons to Choose and Cautions .. . .. . . . . . . .. . . . . . .. ... . ..... ... .. .. . . •. •. •. . ...•. • .•. ... . ..... ... 730 4.3 Additional Algorithms .............. ... . . . . .. . ...... . ... . ........ .• .. .. . .. ................ .. .... 134 Summary ......... .... ........................ .. . ....................... . . . ..•.. . .................. 135 Exercises ........... ..................... . . ..... . ............................... . .......... .. ..... . 135 Bibliography ............................. ....... ................................ . .................. 136

Chapter 5 • Advanced Analytical Theory and Methods: Association Rules .................. 137

5.1 Overview .... . . ... ........................................ .. . .. . ..... . .. .................. .. .... 138 5.2 A priori Algorithm ........... . ............... . . ....... ... . . .... . . ..... .......... .. ......... ... ... 140 5.3 Evaluation of Candidate Rules ....................... . ... .. . .. ..... •....... . ................ ..... 141 5.4 Applications of Association Rules ............ ... ..... . ..... . . . ... ..... . . .. . . . ...... .............. 143 5.5 An Example: Transactions in a Grocery Store ... . .................... .... . . ... .......... ........... 143

5.5.1 The Groceries Dataset ................... . . .. .............. •........... •... . .......•............... 144 5.5.2 Frequent ltemset Generation . . ........................... .. ......... . . •. •......... •............... 146 5.5.3 Rule Generation and Visualization ...... . ... . ......................... . .•. •.... .•. •........... . .. . 752

5.6 Validation and Testing ........... . ... .... . . ............................................. . ....... 157 5.7 Diagnostics .. .... ..................... . .. . . ..... . ............ . ... . . ... . ...... . ......... .. .... . . . 158 Summary ....... .. ................ . ..... ... . . .. . . ...... .... .... . ........ . . .... ..... .............. . . 158 Exercises ................................ ... . . . ........ . ................. . .... ....... ......... . .... 159 Bibliography ................................ . .. .... ..... ............ ..... . ... ........... ... . ...... . 160

Chapter 6 • Advanced Analytical Theory and Methods: Regression .................. . ..... 161

6.1 Linear Regression .......... . .......... . .. . .. .. ...... . ............ .... . . . ....... ........... ...... 162 6.1.1 UseCases . . . ... . . . .. . ...... ..... ......................... .. . ....... .... .... .. ...... . .......... . .. . /62 6.1.2 Model Description .. ... .. . .. . ..... . ........... . .. . .. .... . . •. ..... . •.•.• . ...... . .•............. . .. . 163 6.1.3 Diagnostics ....................... . .... .. . . . . . . ....... •.•.• .....•. •.•...... .• . •.•.. . .. . .... . . . . . . . 773

6.2 Logistic Regression ............ ........ . ..... ................................ . ......... .. .. . .. .. 178 6.2.1 Use Cases ...... . ....................................... .... ................ .... ................... 179 6.2.2 Model Description ........ .. .... ... •..... . .... ........ .. .. •. ..... ... . .•. •...• .•................... 179 6.2.3 Diagnostics ................. ..... ...... . . .. ............•. •. ........•. ..... .• .•................... 181

6.3 Reasons to Choose and Cautions ....... . . .... .. .... ............ ........... ......... ....... ..... . 188 6.4 Additional Regression Models ............ ... .. ...... . ... . ............. . ... ........ ........... ... 189 Summary ........... .... . ............ . ....... . .........•... . ...... . ...... ... . .. . . ... .. ........... . . 190 Exercises ............ .. .......... .. . .. ................ .. .. .. ............ . . .. .......... . . . .. .. .... . . 190

Chapter 7 • Advanced Analytical Theory and Methods: Classification ...... . .......... . .... 191

7.1 Decision Trees ... .. ............... ...... ............ ............. .......... .............. ... .... 192 7.1.1 Overview of a Decision Tree ...... . .................... .. . ........................ .. .... ..... . ...... 193 7.1.2 The General Algorithm . .............. .............. ... ..•. ... .............. .• .. .. ........ .... . .. . . 197 7.1.3 Decision Tree Algorithms ............. .. . .... .. ......•. . .•.. ... •. •... .... . .... ... . .............. .. 203 7.1.4 Evaluating a Decision Tree ............. . . •... . ... . ...•... .... . ....... . .................... . ... . . . . 204 7.1.5 Decision Trees in R . . . .. ................ ...... .. .. ..... ..... .... .................. . ..... ........ .. 206

7.2 Na'lve Bayes . .... ... ................ . ..... . ...... . .......... . .. . ... . ..... .. ..... ......... . ...... 211 7.2.1 Bayes' Theorem . . .. . ........................ . ..................................................... 212 7.2.2 Nai've Bayes Classifier ................... •... . ... ..... .......•.................................. .. . 214

CONTENTS

7.2.3 Smoothing . ............... .................... . .. . ........ . .. . ...... .. •. .. .......... .. .......... . 277 7.2.4 Diagnostics .. . ........... . ..................... .. .... . .•......... •.•.....•...•........ . . . ......... 217 7.2.5 Nai've Bayes in R ............... . . .. . .....•... .. . ...•.•.........•.•.. .. . .. •. •.•.... ........ . .. .... . 278

7.3 Diagnostics of Classifiers ............ •...... ........... •.......... ...•...• .. •... •. .... ........... 224 7.4 Additional Classification Methods .... • ... • ...... • ............. • .................•... .... ......... 228 Summary ................. ..... ............ • ......•.............. .. ..........................•..... 229 Exercises .................. ... ......... .... .........................•.... . . . .................•..... 230 Bibliography ...... . ..........•......... .... ........... . ... . .............. ... ...•................... 231

Chapter 8 • Advanced Analytical Theory and Methods: Time Series Analysis . . .. ... . ... . .. . 233

8.1 Overview of Time Series Analysis ....... ....... ................ ......................... .... ..... 234 8.1.1 Box-Jenkins Methodology ................... . .. .... ...... . .................... . .. ..... ............ 235

8.2 ARIMA Model. ................ . .. . ....... •..•..... .. ...... . ... •................. • ... . ..•........ 236 8.2.1 Autocorrelation Function (ACF) .. ......... ...................... ... ........ . ......... . .. ..... ..... 236 8.2.2 Autoregressive Models . ...... ... ............ . . . .. •. ... ..... ... . .. ... ... . ......... . ....... .. . . .... 238 8.2.3 Moving Average Models . .. .. . .................................... .................... •..... . .... . 239 8.2.4 ARMA and ARIMA Models ............. . .................................•...........•.....•....... 241 8.2.5 Building and Evaluating an ARIMA Model ............................. . .•.........•. •. . ... •...... 244 8.2.6 Reasons to Choose and Cautions .. ................ . .. . ........ .. . . .. . ....... . .... .•.•. •.. . •. . .... . 252

8.3 Additional Methods ........ ... . ... ....... ... .. ...... ...... .. ....... ....... .. ... . .... . ... . ...... . 253 Summary ........................ ... ... ...... .. ............ • ......... ......... ..• .. .......• ... ..... 254 Exercises .............. . .......... ... ......... . •. .. .............................• .. . . .. • . .• ... ..... 254

Chapter 9 • Advanced Analytical Theory and Methods: Text Analysis ...... . ... . .. .. .. . . ... 255 9.1 Text Analysis Steps .......... . .... ......... ...... ... .................... . ...... . ...... . . .•....... 257 9.2 A Text Analysis Example ..... •.... .... ............................ .. ............ ...... • .... ...... 259 9.3 Collecting Raw Text ........ .. .............. 00 00 00 00 ••••• 00 ••• ••• ••• ••••• 00 ••••• 00 ••••• •• ••• 00 ••• 260 9.4 Representing Text .......................... ... .................. . ...................•.. ...... .. 264 9.5 Term Frequency-Inverse Document Frequency (TFIDF) ...... • .......... • ..... .•. ...... . ......... 269 9.6 Categorizing Documents by Topics .... ................... .. .•..... . . ... • ...... •.. . . .. . . ......... 274 9.7 Determining Sentiments ............... . ...... . ......•...•..•.... .. .. .. •.. •... •.. . . .. ........... 277 9.8 Gaining Insights ................ .. ....................... •..•....... .. ........•... . ..... . ....... 283 Summary ............... . ........... . ......... •.................... • ..... . . . ......... •..... . ....... 290 Exercises ...............•... . ..... . . .. ........ •..•... . ............. • ................. . ..... . ....... 290 Bibliography ............ •. ..•... . ..... . ....... ... . ....... . .. . ................ . ............ . ........ 291

Chapter 10 • Advanced Analytics-Technology and Tools: MapReduce and Hadoop . . . ..... 295

10.1 Analytics for Unstructured Data . 00 .. .... .. 00 ••••• 00. 00 ••• 00 00 .......... 00 ......... 00 •• 00 .. . .... 296 10.1.1 UseCasesoo .. 00.00 00 ••••• 00.00 00 •••••• 00 ••••••• 00 ••• 00 • • 00.00 .. . .................... 00 . .... .. 00. 296 10.1.2 MapReduce . .. .... ......... .. ............... . .......... •......... •.•....... •.•. •....... . ....... 298 70.7.3 Apache Hadoop ......... ... ........... . ......... . . .. ....... .. . . .. . .... ... . .• ...•.... .. . •....... 300

10.2 The Hadoop Ecosystem ....•... . ........... ..... ... . •... .. .............• . •. .. .. ....... . •• ...... 306 70.2.1 Pig . ....... ..... ........ . ......................................... . .. . . .......•... . ..... •.•..... 306 70.2.2 Hive ............... . ............•................ . ... •.•...........•.......•. . .. . .. . ..... . .. . .. 308 70.2.3 HBase ...... .. 00 .. ... . . 00 ••••••••••••••• 00 •••••• 00 . .... . ..... .. ...... 00 .. .. . . . 00 ••• 00 00 ... 00 •••• • 317 10.2.4 Mahout .. 00 • •• • ••••••••••• 00 ............ . . . .. . ... . .... .... . ..... .. .......... .. .. 00 • • • 00 .. . .. . .. • 319

CONTENTS

10.3 NoSOL ...............•........................ • ................. •..................... • ....... 322 Summary .............•...•........................•................. •.....................•....... 323 Exercises .................•........................ • ..................... •...... ................... 324 Bibliography ....... •...... • ................. •...... • .................•......... .... ........ • ..•.... 324

Chapter 11 • Advanced Analytics-Technology and Tools: In-Database Analytics ........ . . . 327

11.1 SOL Essentials ............................................................. .. . . ........ • ..•.... 328 77.1.1 Joins .. . .. . . .. .. . .. ... .. . ......... ... ............. . .. .. . ...... .. .. ... . ....... ... .... . .. ...... . .. . 330 77.1.2 Set Operations ................ . .. . ...................... . ...... ... ........................... . ... 332 11.1.3 Grouping Extensions ......... .. .. .. . . . . .. ........................ ............. .. ................ . 334

11.2 In-Database Text Analysis ............... •... . .............•......•......... . . .. ... .• . . . •..•.... 338 11 .3 Advanced SOL ... .. ......................... •.. • .................•........... . .........•....... 343

71.3.1 Window Functions . . . . ............................... ... .. .... .. . . . ..... . ....................... 343 11.3.2 User-Defined Functions and Aggregates ............................•. •. •............... .. ... .... .347 11.3.3 Ordered Aggregates ............. ..... .... ..... ....... .... .. ..................................... 351 11.3.4 MADiib ...................................... ............•. ....... . . .... . .... •. •................ .352

Summary ..........•.. • ... • .......................................................... .. . . .......... 356 Exercises ......... . .............................. ........ ............................ .. . . .......... 356 Bibliography .......•...... •. .• • .................... • ... .. ........... . •. ..• . ......... .... .. . ........ 357

Chapter 12 • The Endgame, or Putting It All Together ..................................... 359

12.1 Communicating and Operationalizing an Analytics Project. ........ . .....................•....... 360 12.2 Creating the Final Deliverables ......................... ..... . .. .. .. .•.......................... 362

12.2.1 Developing Core Material for Multiple Audiences ........................ •..... .. •.•.............. 364 12.2.2 Project Goals . . . . . .. . . ............ . ............ . ..... . ........ ..... . .. . . ..... . . . ................ 365 12.2.3 Main Findings ....... . ... . . ... . ....................... . .. ... . .. . ... ....• . . . ... . •. •........... . .. .367 12.2.4 Approach ... . .. . . .. . . ............................................................ .... .... ...... 369 12.2.5 Model Description ... . .. . .................................... .. ......... . .... . ...•..... . ..... .... 371 12.2.6 Key Points Supported with Data . .......................... . . . . . ....... . . . ..... .. .. .. . ..... . ..... .372 12.2.7 Model Details .. . . .. ................................................. . ....... •.•....... . ........ .372 12.2.8 Recommendations ........ ... .... ....... .... ........... .......... . .... . . ...... •.•.• .. .... ..... . . 374 12.2.9 Additional Tips on Final Presentation ......... . .. . ............ .. . . . . .. . .. . ..... . •. •.............. .375 12.2.10 Providing Technica15pecificarions and Code ................................... . ................ . 376

12.3 Data Visua lization Basics .......... .... ... .... ....................•.......... . .... . ............. 377 12.3.1 Key Points Supported with Data ............... . ... . . . .................. . ............... ... ...... .378 12.3.2 Evolution of a Graph ................ ..... .... ............. ...... . ...... •.•... •. •.•......... •.... 380 12.3.3 Common Representation Methods .............. .. ............ .. . . . •. •.. . .... •. . ................ 386 12.3.4 How to Clean Up a Graphic ................... •. . . .... . ..... . .......... . . . ..... . ... .......... ... .387 12.3.5 Additional Considerations ..... ................. .... ... . ..... .. . . . . •.•. .. ... . •.• ...... . ...... ... . 392

Summary ............ .. .........................•...... • ... • . ... .........•... •..................... 393 Exercises ........... . . .... . ................. .. .. . . . .... • ................. . . .. . .. • .......... . ....... 394 References and Further Reading ... .. ............ .... ...... ..... ......... . .... . . .................... 394 Bibliography .... . . ... ......... .... . ........................ • ................. .. . .. .. . ... . . ... ...... 394

Index .. . .............. . .. . .. . .. . . .. . . ........... . . . .. . .. . . . ....... . . . ... . . .. . .. .. . .. . . . ... .. . . ............... . 397

Foreword

Technological advances and the associated changes in practical daily life have produced a rapidly expanding "parallel universe" of new content, new data, and new information sources all around us. Regardless of how one defines it, the phenomenon of Big Data is ever more present, ever more pervasive, and ever more important. There is enormous value potential in Big Data: innovative insights, improved understanding of problems, and countless opportunities to predict-and even to shape-the future. Data Science is the principal means to discover and tap that potential. Data Science provides ways to deal with and benefit from Big Data: to see patterns, to discover relationships, and to make sense of stunningly varied images and information.

Not everyone has studied statistical analysis at a deep level. People with advanced degrees in applied math- ematics are not a commodity. Relatively few organizations have committed resources to large collections of data gathered primarily for the purpose of exploratory analysis. And yet, while applying the practices of Data Science to Big Data is a valuable differentiating strategy at present, it will be a standard core competency in the not so distant future.

How does an organization operationalize quickly to take advantage of this trend? We've created this book for that exact purpose.

EMC Education Services has been listening to the industry and organizations, observing the multi-faceted transformation of the technology landscape, and doing direct research in order to create curriculum and con- tent to help individuals and organizations transform themselves. For the domain of Data Science and Big Data Analytics, our educational strategy balances three things: people-especially in the context of data science teams, processes-such as the analytic lifecycle approach presented in this book, and tools and technologies-in this case with the emphasis on proven analytic tools.

So let us help you capitalize on this new "parallel universe" that surrounds us. We invite you to learn about Data Science and Big Data Analytics through this book and hope it significantly accelerates your efforts in the transformational process.

Introduction

Big Data is creating significant new opportunities for organizations to derive new value and create competitive advantage from their most valuable asset: information. For businesses, Big Data helps drive efficiency, quality, and personalized products and services, producing improved levels of customer satisfaction and profit. For scientific efforts, Big Data analytics enable new avenues of investigation with potentially richer results and deeper insights than previously available. In many cases, Big Data analytics integrate structured and unstructured data with real- time feeds and queries, opening new paths to innovation and insight.

This book provides a practitioner's approach to some of the key techniques and tools used in Big Data analytics. Knowledge ofthese methods will help people become active contributors to Big Data analytics projects. The book's content is designed to assist multiple stakeholders: business and data analysts looking to add Big Data analytics skills to their portfolio; database professionals and managers of business intelligence, analytics, or Big Data groups looking to enrich their analytic skills; and college graduates investigating data science as a career field.

The content is structured in twelve chapters. The first chapter introduces the reader to the domain of Big Data, the drivers for advanced analytics, and the role of the data scientist. The second chapter presents an analytic project lifecycle designed for the particular characteristics and challenges of hypothesis-driven analysis with Big Data.

Chapter 3 examines fundamental statistical techniques in the context of the open source R analytic software environment. This chapter also highlights the importance of exploratory data analysis via visualizations and reviews the key notions of hypothesis development and testing.

Chapters 4 through 9 discuss a range of advanced analytical methods, including clustering, classification, regression analysis, time series and text analysis.

Chapters 10 and 11 focus on specific technologies and tools that support advanced analytics with Big Data. In particular, the Map Reduce paradigm and its instantiation in the Hadoop ecosystem, as well as advanced topics in SOL and in-database text analytics form the focus of these chapters.

XVIII ! INTRODUCTION

Chapter 12 provides guidance on operationalizing Big Data analytics projects. This chapter focuses on creat· ing the final deliverables, converting an analytics project to an ongoing asset of an organization's operation, and creating clear, useful visual outputs based on the data.

EMC Academic Alliance University and college faculties are invited to join the Academic Alliance program to access unique "open" curriculum-based education on the following topics:

• Data Science and Big Data Analytics

• Information Storage and Management

• Cloud Infrastructure and Services

• Backup Recovery Systems and Architecture

The program provides faculty with course resources to prepare students for opportunities that exist in today's

evolving IT industry at no cost. For more information, visit http: // education . EMC . com/ academicalliance.

EMC Proven Professional Certification EMC Proven Professional is a leading education and certification program in the IT industry, providing compre-

hensive coverage of information storage technologies, virtualization, cloud computing, data science/Big Data analytics, and more.

Being proven means investing in yourself and formally validating your expertise.

This book prepares you for Data Science Associate (EMCDSA) certification. Visit http : I I educat i on . EMC . com for details.

INTRODUCTION TO BIG DATA ANAL YTICS

Much has been written about Big Data and the need for advanced analytics within industry, academia,

and government. Availability of new data sources and the rise of more complex analytical opportunities

have created a need to rethink existing data architectures to enable analytics that take advantage of Big Data. In addition, significant debate exists about what Big Data is and what kinds of skil ls are required to make best use of it. This chapter explains several key concepts to clarify what is meant by Big Data, why

advanced analyt ics are needed, how Data Science differs from Business Intelligence (BI), and what new

roles are needed for the new Big Data ecosystem.

1.1 Big Data Overview Data is created constantly, and at an ever-increasing rate. Mobile phones, social media, imaging technologies

to determine a medical diagnosis-all these and more create new data, and that must be stored somewhere for some purpose. Devices and sensors automatically generate diagnostic information that needs to be stored and processed in real time. Merely keeping up with this huge influx of data is difficult, but substan-

tially more cha llenging is analyzing vast amounts of it, especially when it does not conform to traditional

notions of data structure, to identify meaningful patterns and extract useful information. These challenges of the data deluge present the opportunity to transform business, government, science, and everyday life.

Several industries have led the way in developing their ability to gather and exploit data:

• Credit card companies monitor every purchase their customers make and can identify fraudulent purchases with a high degree of accuracy using rules derived by processing billions of transactions.

• Mobile phone companies analyze subscribers' calling patterns to determine, for example, whether a caller's frequent contacts are on a rival network. If that rival network is offering an attractive promo- tion that might cause the subscriber to defect, the mobile phone company can proactively offer the subscriber an incentive to remain in her contract.

• For companies such as Linked In and Facebook, data itself is their primary product. The valuations of these companies are heavi ly derived from the data they gather and host, which contains more and more intrinsic va lue as the data grows.

Three attributes stand out as defining Big Data characteristics:

• Huge volume of data: Rather than thousands or millions of rows, Big Data can be billions of rows and millions of columns.

• Complexity of data t ypes and structures: Big Data reflects the variety of new data sources, formats, and structures, including digital traces being left on the web and other digital repositories for subse- quent analysis.

• Speed of new data creation and growth: Big Data can describe high velocity data, with rapid data ingestion and near real time analysis.

Although the volume of Big Data tends to attract the most attention, generally the variety and veloc-

ity of the data provide a more apt definition of Big Data. (Big Data is sometimes described as having 3 Vs: volume, variety, and velocity.) Due to its size or structure, Big Data cannot be efficiently analyzed using only

traditional databases or methods. Big Data problems require new tools and technologies to store, manage, and realize the business benefit. These new tools and technologies enable creation, manipulation, and

1.1 Big Data Overview

management of large datasets and the storage environments that house them. Another definition of Big Data comes from the McKinsey Global report from 2011:

Big Data is data whose scale, distribution, diversity, and/or timeliness require the use of new technical architectures and analytics to enable insights that unlock ne w sources of business value.

McKinsey & Co.; Big Data: The Next Frontier for Innovation, Competition, and Productivity [1]

McKinsey's definition of Big Data impl ies that organizations will need new data architectures and ana-

lytic sandboxes, new tools, new analytical methods, and an integration of multiple skills into the new ro le of the data scientist, which will be discussed in Section 1.3. Figure 1-1 highlights several sources of the Big

Data deluge.

What's Driving Data Deluge?

Mobile Sensors

Smart Grids

Social Media

Geophysical Exploration

FtGURE 1-1 What 's driving the data deluge

Video Surveillance

• Medical Imaging Video

Rendering

Gene Sequencing

The rate of data creation is accelerating, driven by many of the items in Figure 1-1.

Social media and genetic sequencing are among the fastest-growing sources of Big Data and examples of untraditional sources of data being used for analysis.

For example, in 2012 Facebook users posted 700 status updates per second worldwide, which can be leveraged to deduce latent interests or political views of users and show relevant ads. For instance, an update in which a woman changes her relationship status from "single" to "engaged" would trigger ads

on bridal dresses, wedding planning, or name-changing services. Facebook can also construct social graphs to analyze which users are connected to each other as an

interconnected network. In March 2013, Facebook released a new feature called "Graph Search," enabling users and developers to search social graphs for people with similar interests, hobbies, and shared locations.

INTRODUCTION TO BIG DATA ANALYTICS

Another example comes from genomics. Genetic sequencing and human genome mapping provide a detailed understanding of genetic makeup and lineage. The health care industry is looking toward these

advances to help predict which illnesses a person is likely to get in his lifetime and take steps to avoid these maladies or reduce their impact through the use of personalized medicine and treatment. Such tests also

highlight typical responses to different medications and pharmaceutical drugs, heightening risk awareness of specific drug treatments.

While data has grown, the cost to perform this work has fallen dramatically. The cost to sequence one human genome has fallen from $100 million in 2001 to $10,000 in 2011, and the cost continues to drop. Now, websites such as 23andme (Figure 1-2) offer genotyping for less than $100. Although genotyping analyzes

only a fraction of a genome and does not provide as much granularity as genetic sequencing, it does point

to the fact that data and complex analysis is becoming more prevalent and less expensive to deploy.

23 pairs of chromosomes. One unique you.

Bring your ancestry to life. F1ncl out what percent or your DNA comes !rom populations around the world. rang1ng from East As1a Sub-Saharan Alllca Europe, and more. B1eak European ancestry down 1010 d1st1nct regions such as the Bnush Isles. Scnnd1navla Italy and Ashkenazi Jewish. People IVI\h mixed ancestry. Alncan Amencans. Launos. and Nauve Amencans w111 also get a detailed breakdown.

20.5% ( .t A! n

Find relatives across continents or across the street.

Build your family tree and enhance your ex erience.

:38.6% · s, b·S 1h Jn Afr c.an

24.7% Europe.,,

• ' Share your knowledge. Watch it

row.

FIGURE 1-2 Examples of what can be learned through genotyping, from 23andme.com

1.1 Big Dat a Overview

As illustrated by the examples of social media and genetic sequencing, individuals and organizations both derive benefits from analysis of ever-larger and more complex data sets that require increasingly powerful analytical capabilities.

1.1.1 Data Structures Big data can come in multiple forms, including structured and non-structured data such as financial

data, text files, multimedia files, and genetic mappings. Contrary to much of the traditional data analysis performed by organizations, most of the Big Data is unstructured or semi-structured in nature, which

requires different techniques and tools to process and analyze. [2) Distributed computing environments and massively parallel processing (MPP) architectures that enable parallelized data ingest and analysis are

the preferred approach to process such complex data. With this in mind, this section takes a closer look at data structures. Figure 1-3 shows four types of data structures, with 80-90% of future data growth coming from non-

structured data types. [2) Though different, the four are commonly mixed. For example, a classic Relational Database Management System (RDBMS) may store call logs for a software support call center. The RDBMS

may store characteristics of the support calls as typical structured data, with attributes such as time stamps, machine type, problem type, and operating system. In addition, the system will likely have unstructured,

quasi- or semi-structured data, such as free-form call log information taken from an e-mail ticket of the problem, customer chat history, or transcript of a phone call describing the technical problem and the solu- tion or audio file of the phone call conversation. Many insights could be extracted from the unstructured,

quasi- or semi-structured data in the call center data.

'0 Q)

E u 2 iii Q)

0 ~

Big Data Characteristics: Data Structures Data Growth Is Increasingly Unstructured

I Structured

FIGURE 1-3 Big Data Growth is increasingly unstructured

INTRODUCTION TO BIG DATA ANALYTICS

Although analyzing structured data tends to be the most familiar technique, a different technique is required to meet the challenges to analyze semi-structured data (shown as XML), quasi-structured (shown as a clickstream), and unstructured data.

Here are examples of how each of the four main types of data structures may look.

o Structured data: Data containing a defined data type, format, and structure (that is, transaction data, online analytical processing [OLAP] data cubes, traditional RDBMS, CSV files, and even simple spread- sheets). See Figure 1-4.

SUMMER FOOD SERVICE PROGRAM 11 Data as of August 01. 2011)

Fiscal Number of Peak (July) Meals Total Federal Year Sites Participation Served Expenditures 2]

---Thousands-- -MiL- -Million$- 1969 1.2 99 2.2 0.3 1970 1.9 227 8.2 1.8 1971 3.2 569 29.0 8.2 1972 6.5 1,080 73.5 21.9 1973 11.2 1,437 65.4 26.6 1974 10.6 1,403 63.6 33.6 1975 12.0 1,785 84.3 50.3 1976 16.0 2,453 104.8 73.4

TQ3] 22.4 3,455 198.0 88.9 1977 23.7 2,791 170.4 114.4 1978 22.4 2,333 120.3 100.3 1979 23.0 2,126 121.8 108.6 1980 21.6 1,922 108.2 110.1 1981 20.6 1,726 90.3 105.9 1982 14.4 1,397 68.2 87.1 1983 14.9 1,401 71.3 93.4 1984 15.1 1,422 73.8 96.2 1985 16.0 1,462 77.2 111.5 1986 16.1 1,509 77.1 114.7 1987 16.9 1,560 79.9 129.3 1988 17.2 1,577 80.3 133.3 1989 18.5 1.652 86.0 143.8 1990 19? 1 ~Q? 91? 1~11

FIGURE 1-4 Example of structured data

o Semi-structured data: Textual data files with a discernible pattern that enables parsing (such as Extensible Markup Language [XML] data files that are self-describing and defined by an XML schema). See Figure 1-5.

o Quasi-structured data: Textual data with erratic data formats that can be formatted with effort, tools, and time (for instance, web clickstream data that may contain inconsistencies in data values and formats). See Figure 1-6.

o Unstructured data: Data that has no inherent structure, which may include text documents, PDFs, images, and video. See Figure 1-7.

1.1 Big Data Overview

Quasi-structured data is a common phenomenon that bears closer scrutiny. Consider the following

example. A user attends the EMC World conference and subsequently runs a Google search online to find information related to EMC and Data Science. This would produce a URL such as https: I /www . google . c om/ #q=EMC+ data+scienc e and a list of results, such as in the first graphic of Figure 1-5.

- ~ ....- . . •• 0

o:.~t.a c!':a=-set.•"~t.t-e">

<z:.~ca l':cc.p-eq-.:.:.v•"X-:J;.-cc:r.;:a c.:.t:~" cc::te::c.•" :.::·~d.Q"e , c~.=cr:."!•: "> <t.:.e:"!>~~C - :ead.:. ~o Clc~d Co~~e.:.~~, 3~Q' Dace., a::d T:~sced ! ! Sol~t.:.o~s</t.:.t!e>

clc::d cc::,r·..:e.:.::r; . ">

<l.:.::k =e:•"se;·:es!':eee" 1':=-et•" / R. /a;;e;;t c;s/ ccv.rrp""' / jo;n:e· ~ ze: c':." > <l.:.::k =~:•"St.i':es!:eet." !-:.=-et•" / B1/a.s:t::;st c,;u / 1ooorrapo g c / rra ·-. . C!!!! '" > <l.:. ::Jc :-el"""!!t.)-'les!'l.eec" l':=e~•" / 5~ /a.:.;ets / c .,,/ corr:rtgjJ/ .. c!lcO""'. ve:-,.cade:- c:~s"> <l.:.::.k =e:• " st.:,·:esl':ee:t." !':.:et• " 15· / a;;ee,t c:z:Jisgrur:c ... / -e:;n;o;gs· ve:-tco;c• c='a">

<~c::.;::t. :.:,1=e•"t.ex::. / : ·e:;asc::.pt." s:-c• '" //c l a; t o ;n: P' ' p;•"" ccrrt-.~ .. dce:t:t.- ; - ><I sc:l.p:t.> < :~c:.:.;::t. .!l:c•"' / R. /a:.sec:J(<~.;/ cgrr;;:c""/rred•--.1z .. _2 I 6 I 2 .;;,;. "'j;. ~ 3 "'></ ~c:.:.pt.>

FIGURE 1-5 Example of semi-structured data

Tool!un

QUKkt~b~

b:plorerbars

Go to

Stop

R<foosh

Zoom(IOO'Jil

Tcxtsa:e

&>coding

Sty!<

C•rct brOWSing

Source Stc:unt\ frpclt

lnt~ ~loON I 0. tt u re-

Wdlpoge pnv.cy potoey_

P""""'JI>ond

Ful scr~

Ctri•Q

h e

F5

F7

Fll

After doing this search, the user may choose the second link, to read more about the headline "Data Scientist- EM( Education, Training, and Certification." This brings the user to an erne . com site focused on this topic and a new URL, ht t p s : I / e ducation . e rne . com/ guest / campai gn/ data_ science

INTRODUCTION TO BIG DATA ANALYTICS

1

. aspx, that displays the page shown as (2) in Figure 1-6. Arriving at this site, the user may decide to click to learn more about the process of becoming certified in data science. The user chooses a link toward the

top of the page on Certifications, bringing the user to a new URL: ht tps :I I education. erne. com/ guest / certifica tion/ framework/ stf/ data_science . aspx, which is (3) in Figure 1-6.

Visiting these three websites adds three URLs to the log files monitoring the user's computer or network

use. These three URLs are:

https: //www.google . com/#q=EMC+data+s cience https: //education . emc.com/ guest / campaign/ data science . aspx https : //education . emc . com/ guest / certification/ framework / stf / data_ science . aspx

- - ...... - .._.. ............. _ O.Uk*-andi'IO..~T~ · OIC~ o ---·- t..._ ·-- . -- ·-A-- ------·----- .. -,.._ , _____ .... 0.. ldHIWI • DtC (Ot.aiiOI\. l....,... and~ 0 --- -~-~· 1 .. ....... _ .. _....._. __ , ___ -~-·-· · ~----"' .. ~_.,.. ..... - :c ~::...~ and Cenbbcrt 0 t-e•·,-'""""... '•'-""'•• ..,....__ ... --...... ~ .... __ .... .....,.,_.... ... ,...._~·

- ~O•Uik~R........, A0.1t-~~_,...h", • £MC O --------.. ... .- . '"" ..._. ______ , ______ ...., -- ···-.. ... -~--.-- .... https:/ /www.google.com/#q

3

------ ---

,_ __ ----

~-:::.::.::·--===-=-== .. ------·---------·------..---::=--.....::..-..=-.:.-.=-.......

-- ·------·----·---·--·---·~--·-· -----------·--·--., ______ ... _______ _ -·----------·-______ , _______ _

- -------~· --· -----

>l __ _ __ , , _ _ _

... , ------., :::... ::

FiGURE 1-6 Example of EMC Data Science search results

1.1 Big Data Overview

FIGURE 1-7 Example of unstructured data: video about Antarctica expedition [3]

This set of three URLs reflects the websites and actions taken to find Data Science information related

to EMC. Together, this comprises a clicksrream that can be parsed and mined by data scientists to discover

usage patterns and uncover relationships among clicks and areas of interest on a website or group of sites. The four data types described in this chapter are sometimes generalized into two groups: structured

and unstructured data. Big Data describes new kinds of data with which most organizations may not be

used to working. With this in mind, the next section discusses common technology architectures from the standpoint of someone wanting to analyze Big Data.

1.1.2 Analyst Perspective on Data Repositories The introduction of spreadsheets enabled business users to create simple logic on data structured in rows

and columns and create their own analyses of business problems. Database administrator training is not requ ired to create spreadsheets: They can be set up to do many things quickly and independently of information technology (IT) groups. Spreadsheets are easy to share, and end users have control over the logic involved. However, their proliferation can result in "many versions of the truth." In other words, it can be challenging to determine if a particular user has the most relevant version of a spreadsheet, with

the most current data and logic in it. Moreover, if a laptop is lost or a file becomes corrupted, the data and logic within the spreadsheet could be lost. This is an ongoing challenge because spreadsheet programs such as Microsoft Excel still run on many computers worldwide. With the proliferation of data islands (or spread marts), the need to centralize the data is more pressing than ever.

As data needs grew, so did more scalable data warehousing solutions. These technologies enabled

data to be managed centrally, providing benefits of security, failover, and a single repository where users

INTRODUCTION TO BIG DATA ANALYTICS

could rely on getting an "official" source of data for financial reporting or other mission-critical tasks. This

structure also enabled the creation ofOLAP cubes and 81 analytical tools, which provided quick access to a set of dimensions within an RD8MS. More advanced features enabled performance of in-depth analytical

techniques such as regressions and neural networks. Enterprise Data Warehouses (EDWs) are critica l for reporting and 81 tasks and solve many of the problems that proliferating spreadsheets introduce, such as which of multiple versions of a spreadsheet is correct. EDWs-and a good 81 strategy-provide direct data

feeds from sources that are centrally managed, backed up, and secured. Despite the benefits of EDWs and 81, these systems tend to restrict the flexibility needed to perform

robust or exploratory data analysis. With the EDW model, data is managed and controlled by IT groups

and database administrators (D8As), and data analysts must depend on IT for access and changes to the data schemas. This imposes longer lead times for analysts to get data; most of the time is spent waiting for

approvals rather than starting meaningful work. Additionally, many times the EDW rules restrict analysts from building datasets. Consequently, it is common for additional systems to emerge containing critical

data for constructing analytic data sets, managed locally by power users. IT groups generally dislike exis- tence of data sources outside of their control because, unlike an EDW, these data sets are not managed, secured, or backed up. From an analyst perspective, EDW and 81 solve problems related to data accuracy

and availabi lity. However, EDW and 81 introduce new problems related to flexibility and agil ity, which were less pronounced when dealing with spreadsheets.

A solution to this problem is the analytic sandbox, which attempts to resolve the conflict for analysts and

data scientists with EDW and more formally managed corporate data. In this model, the IT group may still

manage the analytic sandboxes, but they will be purposefully designed to enable robust analytics, while being centrally managed and secured. These sandboxes, often referred to as workspaces, are designed to enable teams to explore many datasets in a controlled fashion and are not typically used for enterprise-

level financial reporting and sales dashboards. Many times, analytic sandboxes enable high-performance computing using in-database processing-

the analytics occur within the database itself. The idea is that performance of the analysis will be better if

the analytics are run in the database itself, rather than bringing the data to an analytical tool that resides somewhere else. In-database analytics, discussed further in Chapter 11, "Advanced Analytics- Technology and Tools: In-Database Analytics." creates relationships to multiple data sources within an organization and

saves time spent creating these data feeds on an individual basis. In-database processing for deep analytics

enables faster turnaround time for developing and executing new analytic models, while reducing, though not eliminating, the cost associated with data stored in local, "shadow" file systems. In addition, rather than the typical structured data in the EDW, analytic sandboxes can house a greater variety of data, such as raw data, textual data, and other kinds of unstructured data, without interfering with critical production databases. Table 1-1 summarizes the characteristics of the data repositories mentioned in this section.

TABLE 1-1 Types of Data Repositories, from an Analyst Perspective

Data Repository Characteristics

Spreadsheets and data marts

("spreadmarts")

Spreadsheets and low-volume databases for record keeping

Analyst depends on data extracts.

Data Warehouses

Analytic Sandbox

(works paces)

1.2 State of the Practice in Analytics

Centralized data containers in a purpose-built space

Supports Bl and reporting, but restricts robust analyses

Ana lyst dependent on IT and DBAs for data access and schema changes

Ana lysts must spend significant t ime to get aggregated and disaggre-

gated data extracts from multiple sources.

Data assets gathered from multiple sources and technologies for analysis

Enables flexible, high-performance analysis in a nonproduction environ- ment; can leverage in-database processing

Reduces costs and risks associated with data replication into "shadow" file

systems

"Analyst owned" rather than "DBA owned"

There are several things to consider with Big Data Analytics projects to ensure the approach fits with

the desired goals. Due to the characteristics of Big Data, these projects lend themselves to decision sup-

port for high-value, strategic decision making with high processing complexity. The analytic techniques

used in this context need to be iterative and flexible, due to the high volume of data and its complexity.

Performing rapid and complex analysis requires high throughput network connections and a consideration

for the acceptable amount of latency. For instance, developing a real-t ime product recommender for a

website imposes greater system demands than developing a near· real·time recommender, which may

still provide acceptable performance, have sl ightly greater latency, and may be cheaper to deploy. These

considerations require a different approach to thinking about analytics challenges, which will be explored

further in the next section.

1.2 State of the Practice in Analytics Current business problems provide many opportunities for organizations to become more analytical and

data driven, as shown in Table 1 ·2.

TABLE 1-2 Business Drivers for Advanced Analytics

Business Driver Examples

Optimize business operations

Identify business risk

Predict new business opportunities

Comply with laws or regu latory

requirements

Sales, pricing, profitability, efficiency

Customer churn, fraud, default

Upsell, cross-sell, best new customer prospects

Anti-Money Laundering, Fa ir Lending, Basel II-III, Sarbanes- Oxley(SOX)

INTRODUCTION TO BIG DATA ANALYTICS

Table 1-2 outlines four categories of common business problems that organizations contend with where they have an opportunity to leverage advanced analytics to create competitive advantage. Rather than only performing standard reporting on these areas, organizations can apply advanced analytical techniques to optimize processes and derive more value from these common tasks. The first three examples do not represent new problems. Organizations have been trying to reduce customer churn, increase sales, and cross-sell customers for many years. What is new is the opportunity to fuse advanced analytical techniques with Big Data to produce more impactful analyses for these traditional problems. The last example por- trays emerging regulatory requirements. Many compliance and regulatory laws have been in existence for decades, but additional requirements are added every year, which represent additional complexity and data requirements for organizations. Laws related to anti-money laundering (AML) and fraud prevention require advanced analytical techniques to comply with and manage properly.

1.2.1 81 Versus Data Science The four business drivers shown in Table 1-2 require a variety of analytical techniques to address them prop- erly. Although much is written generally about analytics, it is important to distinguish between Bland Data Science. As shown in Figure 1-8, there are several ways to compare these groups of analytical techniques.

One way to evaluate the type of analysis being performed is to examine the time horizon and the kind of analytical approaches being used. Bl tends to provide reports, dashboards, and queries on business questions for the current period or in the past. Bl systems make it easy to answer questions related to quarter-to-date revenue, progress toward quarterly targets, and understand how much of a given product was sold in a prior quarter or year. These questions tend to be closed-ended and explain current or past behavior, typically by aggregating historical data and grouping it in some way. 81 provides hindsight and some insight and generally answers questions related to "when" and "where" events occurred.

By comparison, Data Science tends to use disaggregated data in a more forward-looking, exploratory way, focusing on analyzing the present and enabling informed decisions about the future. Rather than aggregating historical data to look at how many of a given product sold in the previous quarter, a team may employ Data Science techniques such as time series analysis, further discussed in Chapter 8, "Advanced Analytical Theory and Methods: Time Series Analysis," to forecast future product sales and revenue more accurately than extending a simple trend line. In addition, Data Science tends to be more exploratory in nature and may use scenario optimization to deal with more open-ended questions. This approach provides insight into current activity and foresight into future events, while generally focusing on questions related to "how" and "why" events occur.

Where 81 problems tend to require highly structured data organized in rows and columns for accurate reporting, Data Science projects tend to use many types of data sources, including large or unconventional datasets. Depending on an organization's goals, it may choose to embark on a 81 project if it is doing reporting, creating dashboards, or performing simple visualizations, or it may choose Data Science projects if it needs to do a more sophisticated analysis with disaggregated or varied datasets.

Exploratory

Analytical Approach

Explanatory

I

, .. -- ---, 1 Business 1 1 Intelligence 1 \ , .... _____ ..,

Past

fiGUR E 1 ·8 Comparing 81 with Data Science

1.2.2 Current Analytical Architecture

1 .2 State ofthe Practice In Analytlcs

Predictive Analytics and Data Mining (Data Science)

Typical • Optimization. predictive modo lin£ Techniques forocastlnC. statlatlcal analysis

and • Structured/unstructured data. many Data Types types of sources, very Ioree datasata

Common Questions

Typical Techniques

and Data Types

Time

Common Questions

• What II ... ? • What's tho optlmaltconarlo tor our bualnoss?

• What wtll happen next? What II these trend$ continuo? Why Is this happonlnt?

Business Intelligence

• Standard and ad hoc reportlnc. dashboards. alerts, queries, details on demand

• Structured data. traditional sourcoa. manac:eable datasets

• What happened lut quarter?

• How many units sold?

• Whore Is the problem? In which situations?

Future

As described earlier, Data Science projects need workspaces that are purpose-built for experimenting with

data, with flexible and agile data architectures. Most organizations still have data warehouses that provide

excellent support for traditional reporting and simple data analysis activities but unfortunately have a more

difficult time supporting more robust analyses. This section examines a typical analytical data architecture

that may exist within an organization.

Figure 1-9 shows a typical data architecture and several of the challenges it presents to data scientists

and others trying to do advanced analytics. This section examines the data flow to the Data Scientist and

how this individual tits into the process of getting data to analyze on projects.

INTRODUCTION TO BIG DATA ANALYTICS

FIGURE 1-9 Typical analytic architecture

i..l ,_, It Analysts

Dashboards

Reports

Alerts

1. For data sources to be loaded into the data warehouse, data needs to be well understood, structured, and normalized with the appropriate data type defini t ions. Although th is kind of centralization enables security, backup, and fai lover of highly critical data, it also means that data typically must go through significant preprocessing and checkpoints before it can enter this sort of controlled environment, which does not lend itself to data exploration and iterative analytics.

2. As a result of this level of control on the EDW, additional local systems may emerge in the form of departmental warehouses and local data marts that business users create to accommodate their need for flexible analysis. These local data marts may not have the same constraints for secu- ri ty and structure as the main EDW and allow users to do some level of more in-depth analysis. However, these one-off systems reside in isolation, often are not synchronized or integrated with other data stores, and may not be backed up.

3. Once in the data warehouse, data is read by additional applications across the enterprise for Bl and reporting purposes. These are high-priority operational processes getting critical data feeds from the data warehouses and repositories.

4. At the end of this workflow, analysts get data provisioned for their downstream analytics. Because users generally are not allowed to run custom or intensive analytics on production databases, analysts create data extracts from the EDW to analyze data offline in R or other local analytical tools. Many times these tools are limited to in-memory analytics on desktops analyz- ing samples of data, rather than the entire population of a dataset. Because these analyses are based on data extracts, they reside in a separate location, and the results of the analysis-and any insights on the quality of the data or anomalies-rarely are fed back into the main data repository.

Because new data sources slowly accum ulate in the EDW due to the rigorous validation and

data structuring process, data is slow to move into the EDW, and the data schema is slow to change.

1.2 State of the Practice in Analytics

Departmental data warehouses may have been originally designed for a specific purpose and set of business needs, but over time evolved to house more and more data, some of which may be forced into existing schemas to enable Bland the creation of OLAP cubes for analysis and reporting. Although the EDW achieves the objective of reporting and sometimes the creation of dashboards, EDWs generally limit the ability of analysts to iterate on the data in a separate nonproduction environment where they can conduct in-depth analytics or perform analysis on unstructured data.

The typical data architectures just described are designed for storing and processing mission-critical data, supporting enterprise applications, and enabling corporate reporting activities. Although reports and dashboards are still important for organizations, most traditional data architectures inhibit data exploration and more sophisticated analysis. Moreover, traditional data architectures have several additional implica- tions for data scientists.

o High-value data is hard to reach and leverage, and predictive analytics and data mining activities are last in line for data. Because the EDWs are designed for central data management and reporting, those wanting data for analysis are generally prioritized after operational processes.

o Data moves in batches from EDW to local analytical tools. This workflow means that data scientists are limited to performing in-memory analytics (such as with R, SAS, SPSS, or Excel), which will restrict the size of the data sets they can use. As such, analysis may be subject to constraints of sampling, which can skew model accuracy.

o Data Science projects will remain isolated and ad hoc, rather than centrally managed. The implica- tion of this isolation is that the organization can never harness the power of advanced analytics in a scalable way, and Data Science projects will exist as nonstandard initiatives, which are frequently not aligned with corporate business goals or strategy.

All these symptoms of the traditional data architecture result in a slow "time-to-insight" and lower business impact than could be achieved if the data were more readily accessible and supported by an envi- ronment that promoted advanced analytics. As stated earlier, one solution to this problem is to introduce analytic sandboxes to enable data scientists to perform advanced analytics in a controlled and sanctioned way. Meanwhile, the current Data Warehousing solutions continue offering reporting and Bl services to support management and mission-critical operations.

1.2.3 Drivers of Big Data To better understand the market drivers related to Big Data, it is helpful to first understand some past history of data stores and the kinds of repositories and tools to manage these data stores.

As shown in Figure 1-10, in the 1990s the volume of information was often measured in terabytes. Most organizations analyzed structured data in rows and columns and used relational databases and data warehouses to manage large stores of enterprise information. The following decade saw a proliferation of different kinds of data sources-mainly productivity and publishing tools such as content management repositories and networked attached storage systems-to manage this kind of information, and the data began to increase in size and started to be measured at petabyte scales. In the 2010s, the information that organizations try to manage has broadened to include many other kinds of data. In this era, everyone and everything is leaving a digital footprint. Figure 1-10 shows a summary perspective on sources of Big Data generated by new applications and the scale and growth rate of the data. These applications, which generate data volumes that can be measured in exabyte scale, provide opportunities for new analytics and driving new value for organizations. The data now comes from multiple sources, such as these:

INTRODUCTION TO BIG DATA ANALYTICS

• Medical information, such as genomic sequencing and diagnostic imaging

• Photos and video footage uploaded to the World Wide Web

• Video surveillance, such as the thousands of video cameras spread across a city

• Mobile devices, which provide geospatiallocation data of the users, as well as metadata about text messages, phone calls, and application usage on smart phones

• Smart devices, which provide sensor-based collection of information from smart electric grids, smart buildings, and many other public and industry infrastructures

• Nontraditional IT devices, including the use of radio-frequency identification (RFID) readers, GPS navigation systems, and seismic processing

MEASURED IN MEASURED IN WILL BE MEASURED IN

TERABYTES PET A BYTES EXABYTES lTB • 1.000GB lPB • l .OOOTB lEB l .OOOPB

IIEII You(D

.... ~ .. ·, A n '' \ . ~ I b ~

~ ~ SMS

w: '-----" ORACLE =

1.9905 20005 201.05 (RDBMS & DATA (CONTENT & DIGITAL ASSET (NO-SQL & KEY VALUE)

WAREHOUSE) MANAGEMENT)

FIGURE 1-10 Data evolution and the rise of Big Data sources

The Big Data trend is generating an enormous amount of information from many new sources. This data deluge requires advanced analytics and new market players to take advantage of these opportunities and new market dynamics, which wi ll be discussed in the following section.

1.2.4 Emerging Big Data Ecosystem and a New Approach to Analytics Organizations and data collectors are realizing that the data they can gather from individuals contains intrinsic value and, as a result, a new economy is emerging. As this new digital economy continues to

1.2 State of the Practice in Analytics

evolve, the market sees the introduction of data vendors and data cleaners that use crowdsourcing (such

as Mechanical Turk and Ga laxyZoo) to test the outcomes of machine learning techniques. Other vendors

offer added va lue by repackaging open source tools in a simpler way and bringing the tools to market.

Vendors such as Cloudera, Hortonworks, and Pivotal have provided this value-add for the open source

framework Hadoop.

As the new ecosystem takes shape, there are four main groups of players within this interconnected

web. These are shown in Figure 1-11.

• Data devices [shown in the (1) section of Figure 1-1 1] and the "Sensornet" gat her data from multiple locations and continuously generate new data about th is data. For each gigabyte of new data cre- ated, an additional petabyte of data is created about that data. [2)

• For example, consider someone playing an online video game through a PC, game console, or smartphone. In this case, the video game provider captures data about the skill and levels attained by the player. Intelligent systems monitor and log how and when the user plays the game. As a consequence, the game provider can fine-tune the difficulty of the game, suggest other related games that would most likely interest the user, and offer add itional equipment and enhancements for the character based on the user's age, gender, and interests. Th is information may get stored locally or uploaded to the game provider's cloud to analyze the gaming habits and opportunities for ups ell and cross-sell, and identify archetypical profiles of specific kinds of users.

• Smartphones provide another rich source of data. In addition to messaging and basic phone usage, they store and transmit data about Internet usage, SMS usage, and real-time location. This metadata can be used for analyzing traffic patterns by scanning the density of smart- phones in locations to track the speed of cars or the relative traffic congestion on busy roads. In this way, GPS devices in cars can give drivers real-time updates and offer alternative

routes to avoid traffic delays.

• Retail shopping loyalty cards record not just the amount an individual spends, but the loca- tions of stores that person visits, the kinds of products purchased, the stores where goods are purchased most often, and the combinations of products purchased together. Collecting this data provides insights into shopping and travel habits and the likelihood of successful advertisement targeting for certa in types of retail promotions.

• Data collectors [the blue ovals, identified as (2) within Figure 1-1 1] include sample entities that col lect data from the device and users.

• Data resul ts from a cable TV provider tracking the shows a person watches, which TV channels someone wi ll and will not pay for to watch on demand, and the prices someone is will ing to pay fo r premium TV content

• Retail stores tracking the path a customer takes through their store while pushing a shop- ping cart with an RFID chip so they can gauge which products get the most foot traffic using geospatial data co llected from the RFID chips

• Data aggregators (the dark gray ovals in Figure 1-11, marked as (3)) make sense of the data co llected from the various entities from the "SensorNet" or the "Internet ofThings." These organizations compile data from the devices and usage patterns collected by government agencies, retail stores,

INTRODUCTION TO BIG DATA ANALYTICS

and websites. ln turn, they can choose to transform and package the data as products to sell to list brokers, who may want to generate marketing lists of people who may be good targets for specific ad campaigns.

• Data users and buyers are denoted by (4) in Figure 1-11. These groups directly benefit from the data collected and aggregated by others within the data value chain.

• Retai l banks, acting as a data buyer, may want to know which customers have the highest likelihood to apply for a second mortgage or a home equity line of credit. To provide input for this analysis, retai l banks may purchase data from a data aggregator. This kind of data may include demographic information about people living in specific locations; people who appear to have a specific level of debt, yet still have solid credit scores (or other characteris- tics such as paying bil ls on time and having savings accounts) that can be used to infer credit worthiness; and those who are searching the web for information about paying off debts or doing home remodeling projects. Obtaining data from these various sources and aggrega- tors will enable a more targeted marketing campaign, which would have been more chal- lenging before Big Data due to the lack of information or high-performing technologies.

• Using technologies such as Hadoop to perform natural language processing on unstructured, textual data from social media websites, users can gauge the reaction to events such as presidential campaigns. People may, for example, want to determine public sentiments toward a candidate by analyzing related blogs and online comments. Similarly, data users may want to track and prepare for natural disasters by identifying which areas a hurricane affects fi rst and how it moves, based on which geographic areas are tweeting about it or discussing it via social media.

r:t\ Data \.::J Devices {'[I t Ptto...r r.r..., l UC)(.K VlOLU l !\I ill UO\. AI''

(,.\MI CfitUII CAfW CO\tPl!UR

RfAO(H

~ .~ Iff [) \llOfO MfOICAI

IMo\C'oi"G

Law EniCHCefllefll

Data Users/ Buyers

0 Media

FIGURE 1-11 Emerging Big Data ecosystem

Do live!)' So Mea

'I If,. [Ill AN [

Privato Investigators

/ lawyors

1.3 Key Roles for the New Big Data Ecosystem

As il lustrated by this emerging Big Data ecosystem, the kinds of data and the related market dynamics vary greatly. These data sets can include sensor data, text, structured datasets, and social media. With this in mind, it is worth recall ing that these data sets will not work wel l within traditional EDWs, which were

architected to streamline reporting and dashboards and be centrally managed.lnstead, Big Data problems and projects require different approaches to succeed.

Analysts need to partner with IT and DBAs to get the data they need within an analytic sandbox. A

typical analytical sandbox contains raw data, aggregated data, and data with multiple kinds of structure. The sandbox enables robust exploration of data and requires a savvy user to leverage and take advantage

of data in the sandbox environment.

1.3 Key Roles for the New Big Data Ecosystem As explained in the context of the Big Data ecosystem in Section 1.2.4, new players have emerged to curate, store, produce, clean, and transact data. In addition, the need for applying more advanced analytical tech- niques to increasingly complex business problems has driven the emergence of new roles, new technology

platforms, and new analytical methods. This section explores the new roles that address these needs, and subsequent chapters explore some of the analytical methods and technology platforms.

The Big Data ecosystem demands three categories of roles, as shown in Figure 1-12. These roles were

described in the McKinsey Global study on Big Data, from May 2011 [1].

Three Key Roles of The New Data Ecosystem Role

Deep Analytical Talent

Data Savvy Professionals

Technology and Data Enablers

Data Scientists .. Projected U.S. talent

gap: 1.40,000 to 1.90,000

.. Projected U.S. talent gap: 1..5 million

Note: RcuresaboYe m~ • projected talent CDP In US In 201.8. as ihown In McKinsey May 2011 article "81& Data: l he Nut rront* tot Innovation. Competition. and Product~

FIGURE 1-12 Key roles of the new Big Data ecosystem

The first group- Deep Analytical Talent- is technically savvy, with strong analytical skills. Members pos- sess a combination of skills to handle raw, unstructured data and to apply complex analytical techniques at

INTRODUCTION TO BIG DATA ANALYTICS

massive scales. This group has advanced training in quantitative disciplines, such as mathematics, statistics, and machine learning. To do their jobs, members need access to a robust analytic sandbox or workspace where they can perform large-scale analytical data experiments. Examples of current professions fitting into this group include statisticians, economists, mathematicians, and the new role of the Data Scientist.

The McKinsey study forecasts that by the year 2018, the United States will have a talent gap of 140,000- 190,000 people with deep analytical talent. This does not represent the number of people needed with deep analytical talent; rather, this range represents the difference between what will be available in the workforce compared with what will be needed. In addition, these estimates only reflect forecasted talent shortages in the United States; the number would be much larger on a global basis.

The second group-Data Savvy Professionals-has less technical depth but has a basic knowledge of statistics or machine learning and can define key questions that can be answered using advanced analytics. These people tend to have a base knowledge of working with data, or an appreciation for some of the work being performed by data scientists and others with deep analytical talent. Examples of data savvy profes- sionals include financial analysts, market research analysts, life scientists, operations managers, and business and functional managers.

The McKinsey study forecasts the projected U.S. talent gap for this group to be 1.5 million people by the year 2018. At a high level, this means for every Data Scientist profile needed, the gap will be ten times as large for Data Savvy Professionals. Moving toward becoming a data savvy professional is a critical step in broadening the perspective of managers, directors, and leaders, as this provides an idea of the kinds of questions that can be solved with data.

The third category of people mentioned in the study is Technology and Data Enablers. This group represents people providing technical expertise to support analytical projects, such as provisioning and administrating analytical sandboxes, and managing large-scale data architectures that enable widespread analytics within companies and other organizations. This role requires skills related to computer engineering, programming, and database administration.

These three groups must work together closely to solve complex Big Data challenges. Most organizations are familiar with people in the latter two groups mentioned, but the first group, Deep Analytical Talent, tends to be the newest role for most and the least understood. For simplicity, this discussion focuses on the emerging role of the Data Scientist. It describes the kinds of activities that role performs and provides a more detailed view of the skills needed to fulfill that role.

There are three recurring sets of activities that data scientists perform:

o Reframe business challenges as analytics challenges. Specifically, this is a skill to diagnose busi- ness problems, consider the core of a given problem, and determine which kinds of candidate analyt- ical methods can be applied to solve it. This concept is explored further in Chapter 2, "Data Analytics lifecycle."

o Design, implement, and deploy statistical models and data mining techniques on Big Data. This set of activities is mainly what people think about when they consider the role of the Data Scientist:

1.3 Key Roles for the New Big Data Ecosystem

namely, applying complex or advanced analytical methods to a variety of business problems using data. Chapter 3 through Chapter 11 of this book introduces the reader to many of the most popular analytical techniques and tools in this area.

• Develop insights that lead to actionable recommendations. It is critical to note that applying advanced methods to data problems does not necessarily drive new business va lue. Instead, it is important to learn how to draw insights out of the data and communicate them effectively. Chapter 12, "The Endgame, or Putting It All Together;' has a brief overview of techniques for doing this.

Data scientists are generally thought of as having five main sets of skills and behaviora l characteristics,

as shown in Figure 1-13:

• Quantitative skill: such as mathematics or statistics

• Technical aptitude: namely, software engineering, machine learning, and programming skills

• Skeptical mind-set and critical thinking: It is important that data scientists can examine their work critica lly rather than in a one-sided way.

• Curious and creative: Data scientists are passionate about data and finding creative ways to solve problems and portray information.

• Communicative and collaborative: Data scientists must be able to articulate the business value in a clear way and collaboratively work with other groups, including project sponsors and key stakeholders.

Quantitative

Technical

Skeptical

Curious and Creative

Communlcativr and

CDDaborati~

fiGURE 1 Profile of a Data Scientist

INTRODUCTION TO BIG DATA ANALYTICS

Data scientists are generally comfortable using this blend of skills to acquire, manage, analyze, and visualize data and tell compelling stories about it. The next section includes examples of what Data Science

teams have created to drive new value or innovation with Big Data.

1.4 Examples of Big Data Analytics After describing the emerging Big Data ecosystem and new roles needed to support its growth, this section

provides three examples of Big Data Analytics in different areas: retail, IT infrastructure, and social media. As mentioned earlier, Big Data presents many opportunities to improve sa les and marketing analytics.

An example of this is the U.S. retailer Target. Charles Duhigg's book The Power of Habit [4] discusses how

Target used Big Data and advanced analytical methods to drive new revenue. After analyzing consumer-

purchasing behavior, Target's statisticians determined that the retailer made a great deal of money from

three main life-event situations.

• Marriage, when people tend to buy many new products

• Divorce, when people buy new products and change their spending habits

• Pregnancy, when people have many new things to buy and have an urgency to buy them

Target determined that the most lucrative of these life-events is the thi rd situation: pregnancy. Using data collected from shoppers, Target was able to identify this fact and predict which of its shoppers were

pregnant. In one case, Target knew a female shopper was pregnant even before her family knew [5]. This

kind of knowledge allowed Target to offer specific coupons and incentives to thei r pregnant shoppers. In fact, Target could not only determine if a shopper was pregnant, but in which month of pregnancy a shop- per may be. This enabled Target to manage its inventory, knowing that there would be demand for specific

products and it would likely vary by month over the coming nine- to ten-month cycles. Hadoop [6] represents another example of Big Data innovation on the IT infrastructure. Apache Hadoop

is an open source framework that allows companies to process vast amounts of information in a highly paral-

lelized way. Hadoop represents a specific implementation of the MapReduce paradigm and was designed

by Doug Cutting and Mike Cafarel la in 2005 to use data with varying structures. It is an ideal technical framework for many Big Data projects, which rely on large or unwieldy data sets with unconventional data structures. One of the main benefits of Hadoop is that it employs a distributed file system, meaning it can

use a distributed cluster of servers and commodity hardware to process large amounts of data. Some of the most common examples of Hadoop implementations are in the social med ia space, where Hadoop can manage transactions, give textual updates, and develop social graphs among millions of users. Twitter and Facebook generate massive amounts of unstructured data and use Hadoop and its ecosystem of tools to manage this high volume. Hadoop and its ecosystem are covered in Chapter 10, "Advanced Analytics-

Technology and Tools: MapReduce and Hadoop." Finally, social media represents a tremendous opportunity to leverage social and professional interac-

tions to derive new insights. Linked In exemplifies a company in which data itself is the product. Early on, Linkedln founder Reid Hoffman saw the opportunity to create a social network for working professionals.

Exercises

As of 2014, Linkedln has more than 250 million user accounts and has added many additional features and

data-related products, such as recruiting, job seeker tools, advertising, and lnMaps, which show a social graph of a user's professional network. Figure 1-14 is an example of an In Map visualization that enables

a Linked In user to get a broader view of the interconnectedness of his contacts and understand how he knows most of them.

fiGURE 1-14 Data visualization of a user's social network using lnMaps

Summary Big Data comes from myriad sources, including social media, sensors, the Internet ofThings, video surveil-

lance, and many sources of data that may not have been considered data even a few years ago. As businesses struggle to keep up with changing market requirements, some companies are finding creative ways to apply

Big Data to their growing business needs and increasing ly complex problems. As organizations evolve their processes and see the opportunities that Big Data can provide, they try to move beyond traditional Bl

activities, such as using data to populate reports and dashboards, and move toward Data Science- driven projects that attempt to answer more open-ended and complex questions.

However, exploiting the opportunities that Big Data presents requires new data architectures, includ- ing analytic sandboxes, new ways of working, and people with new skill sets. These drivers are causing organizations to set up analytic sandboxes and build Data Science teams. Although some organizations are

fortunate to have data scientists, most are not, because there is a growing talent gap that makes finding and hiring data scientists in a timely manner difficult. Still, organizations such as those in web retail, health care, genomics, new IT infrastructures, and social media are beginning to take advantage of Big Data and

apply it in creative and novel ways.

Exercises 1. What are the three characteristics of Big Data, and what are the main considerations in processing Big

Data?

2 . What is an analytic sandbox, and why is it important?

3. Explain the differences between Bland Data Science.

4 . Describe the challenges of the current analytical architecture for data scientists.

5. What are the key skill sets and behavioral characteristics of a data scientist?

INTRODUCTION TO BIG DATA ANALYTICS

Bibliography [1] C. B. B. D. Manyika, "Big Data: The Next Frontier for Innovation, Competition, and Productivity,"

McKinsey Global Institute, 2011 . [2] D. R. John Gantz, "The Digital Universe in 2020: Big Data, Bigger Digital Shadows, and Biggest

Growth in the Far East," IDC, 2013. [3] http: I l www. willisresilience . coml emc-datal ab [Online]. [4] C. Duhigg, The Power of Habit: Why We Do What We Do in Life and Business, New York: Random

House, 2012. [5] K. Hil l, "How Target Figured Out a Teen Girl Was Pregnant Before Her Father Did," Forbes, February

2012. [6] http: I l hadoop. apache . org [Online].

DATA ANALYTICS LIFECYCLE

Data science projects differ from most traditional Business Intelligence projects and many data analysis projects in that data science projects are more exploratory in nature. For this reason, it is critical to have a

process to govern them and ensure that the participants are thorough and rigorous in their approach, yet not so rigid that the process impedes exploration.

Many problems that appear huge and daunting at first can be broken down into smaller pieces or

actionable phases that can be more easily addressed. Having a good process ensures a comprehensive and repeatable method for conducting analysis. In addition, it helps focus time and energy early in the process to get a clear grasp of the business problem to be solved.

A common mistake made in data science projects is rushing into data collection and analysis, which

precludes spending sufficient time to plan and scope the amount of work involved, understanding requ ire- ments, or even framing the business problem properly. Consequently, participants may discover mid-stream that the project sponsors are actually trying to achieve an objective that may not match the available data,

or they are attempting to address an interest that differs from what has been explicitly communicated.

When this happens, the project may need to revert to the initial phases of the process for a proper discovery phase, or the project may be canceled.

Creating and documenting a process helps demonstrate rigor, which provides additional credibility

to the project when the data science team shares its findings. A well-defined process also offers a com- mon framework for others to adopt, so the methods and analysis can be repeated in the future or as new members join a team.

2.1 Data Analytics Lifecycle Overview The Data Analytics Lifecycle is designed specifically for Big Data problems and data science projects. The lifecycle has six phases, and project work can occur in several phases at once. For most phases in the life- cycle, the movement can be either forward or backward. This iterative depiction of the lifecycle is intended

to more closely portray a real project, in which aspects of the project move forward and may return to earlier stages as new information is uncovered and team members learn more about various stages of the project. This enables participants to move iteratively through the process and drive toward operational-

izing the project work.

2.1.1 Key Roles for a Successful Analytics Project In recent years, substantial attention has been placed on the emerging role of the data scientist. In October 2012, Harvard Business Review featured an article titled "Data Scientist: The Sexiest Job of the 21st Century" [1], in which experts OJ Patil and Tom Davenport described the new role and how to find and hire data scientists. More and more conferences are held annually focusing on innovation in the areas of Data Science and topics dealing with Big Data. Despite this strong focus on the emerging role of the data scientist specifi-

cally, there are actually seven key roles that need to be fulfilled for a high-functioning data science team to execute analytic projects successfully.

Figure 2-1 depicts the various roles and key stakeholders of an analytics project. Each plays a critical part in a successful analytics project. Although seven roles are listed, fewer or more people can accomplish the work depending on the scope of the project, the organizational structure, and the skills of the participants. For example, on a small, versatile team, these seven roles may be fulfi lled by only 3 people, but a very large project may require 20 or more people. The seven roles follow.

2.1 Data Analytics Lifecycle Overview

...

FIGURE 2-1 Key roles for a successful analytics project

• Business User: Someone who understands the domain area and usually benefits from the results. Th is person can consult and advise the project team on the context of the project, the value of the results, and how the outputs will be operationalized. Usually a business analyst, line manager, or deep subject matter expert in the project domain fulfills this role.

• Project Sponsor: Responsible for the genesis of the project. Provides the impetus and requirements for the project and defines the core business problem. Generally provides the funding and gauges the degree of value from the final outputs of the working team. This person sets the priorities for the project and clarifies the desired outputs.

• Project Manager: Ensures that key milestones and objectives are met on time and at the expected quality.

• Business Intelligence Analyst : Provides business domain expertise based on a deep understanding of the data, key performance indicators (KPis), key metrics, and business intelligence from a reporting perspective. Business Intelligence Analysts generally create dashboards and reports and have knowl- edge of the data feeds and sources.

• Database Administrator (DBA): Provisions and configures the database environment to support the analytics needs of the working team. These responsibilities may include providing access to key databases or tables and ensuring the appropriate security levels are in place related to the data repositories.

• Dat a Engineer: Leverages deep technical skills to assist with tuning SQL queries for data manage- ment and data extraction, and provides support for data ingestion into the analytic sandbox, which

DATA ANALYTICS LIFECYCLE

was discussed in Chapter 1, "Introduction to Big Data Analytics." Whereas the DBA sets up and config- ures the databases to be used, the data engineer executes the actual data extractions and performs substantial data manipulation to facilitate the analytics. The data engineer works closely with the data scientist to help shape data in the right ways for analyses.

o Data Scientist: Provides subject matter expertise for analytical techniques, data modeling, and applying valid analytical techniques to given business problems. Ensures overall analytics objectives are met. Designs and executes analytical methods and approaches with the data available to the project.

Although most of these roles are not new, the last two roles-data engineer and data scientist-have become popular and in high demand [2] as interest in Big Data has grown.

2.1.2 Background and Overview of Data Analytics Lifecycle The Data Analytics Lifecycle defines analytics process best practices spanning discovery to project completion. The lifecycle draws from established methods in the realm of data analytics and decision science. This synthesis was developed after gathering input from data scientists and consulting estab- lished approaches that provided input on pieces of the process. Several of the processes that were consulted include these:

o Scientific method [3], in use for centuries, still provides a solid framework for thinking about and deconstructing problems into their principal parts. One of the most valuable ideas of the scientific method relates to forming hypotheses and finding ways to test ideas.

o CRISP-OM [4] provides useful input on ways to frame analytics problems and is a popular approach for data mining.

o Tom Davenport's DELTA framework [5]: The DELTA framework offers an approach for data analytics projects, including the context of the organization's skills, datasets, and leadership engagement.

o Doug Hubbard's Applied Information Economics (AlE) approach [6]: AlE provides a framework for measuring intangibles and provides guidance on developing decision models, calibrating expert estimates, and deriving the expected value of information.

o "MAD Skills" by Cohen et al. [7] offers input for several of the techniques mentioned in Phases 2-4 that focus on model planning, execution, and key findings.

figure 2-2 presents an overview of the Data Analytics Lifecycle that includes six phases. Teams commonly learn new things in a phase that cause them to go back and refine the work done in prior phases based on new insights and information that have been uncovered. for this reason, figure 2-2 is shown as a cycle. The circular arrows convey iterative movement between phases until the team members have sufficient information to move to the next phase. The callouts include sample questions to ask to help guide whether each of the team members has enough information and has made enough progress to move to the next phase of the process. Note that these phases do not represent formal stage gates; rather, they serve as criteria to help test whether it makes sense to stay in the current phase or move to the next.

Is the model robust enough? Have we

fai led for sure?

······ ::-.. ~~? ........ ·\·

FIGURE 2-2 Overview of Data Analytics Lifecycle

2.1 Data Analytlcs Lifecycle Overview

Do I have enough Information to draft an analytic plan and

share for peer review?

Do I have enough good

quality data to start building the model?

Do I have a good Idea about the type of model to try? Can I refine the

analytic plan?

Here is a brief overview of the main phases of the Data Analytics Lifecycle:

• Phase 1- Discovery: In Phase 1, the team learns the business domain, including relevant history such as whether the organization or business unit has attempted similar projects in the past from which they can learn. The team assesses the resources available to support the project in terms of people, technology, time, and data. Important activities in this phase include framing the business problem as an analytics challenge that can be addressed in subsequent phases and formulating ini- tial hypotheses (IHs) to test and begin learn ing the data.

• Phase 2- Data preparation: Phase 2 requires the presence of an analytic sandbox, in which the team can work with data and perform analytics for the duration of the project. The team needs to execute extract, load, and transform (ELT) or extract, transform and load (ETL) to get data into the sandbox. The ELT and ETL are sometimes abbreviated as ETLT. Data should be t ransformed in the ETLT process so the team can work with it and analyze it. In this phase, the team also needs to famil- iarize itself with the data thoroughly and take steps to condition the data (Section 2.3.4).

DATA ANALYTICS LIFECYCLE

• Phase 3-Model planning: Phase 3 is model planning, where the team determines the methods, techniques, and workflow it intends to follow for the subsequent model building phase. The team explores the data to learn about the relationships between variables and subsequently se lects key variables and the most suitable models.

• Phase 4-Model building: In Phase 4, the team develops data sets for testing, training, and produc- tion purposes. In addition, in this phase the team builds and executes models based on the work done in the model planning phase. The team also considers whether its existing tools will suffice for running the models, or if it will need a more robust environment for executing models and work flows (for example, fast hardware and parallel processing, if applicable).

• Phase 5-Communicate results: In Phase 5, the team, in collaboration with major stakeholders, determines if the results of the project are a success or a failure based on the criteria developed in Phase 1. The team should identify key findings, quantify the business value, and develop a narrative to summarize and convey findings to stakeholders.

• Phase 6-0perationalize: In Phase 6, the team delivers final reports, briefings, code, and technical documents. In addition, the team may run a pilot project to implement the models in a production envi ronment.

Once team members have run models and produced findings, it is critical to frame these results in a

way that is tailored to the audience that engaged the team. Moreover, it is critical to frame the results of the work in a manner that demonstrates clear value. If the team performs a technically accurate analysis but fails to translate the results into a language that resonates with the audience, people will not see the

value, and much of the time and effort on the project will have been wasted. The rest of the chapter is organized as follows. Sections 2.2-2.7 discuss in detail how each of the six

phases works, and Section 2.8 shows a case study of incorporating the Data Analytics Lifecycle in a real-

world data science project.

2.2 Phase 1: Discovery The first phase of the Data Analytics Lifecycle involves discovery (Figure 2-3).1n this phase, the data science

team must learn and investigate the problem, develop context and understanding, and learn about the data sources needed and available for the project. In addition, the team formulates initial hypotheses that can later be tested with data.

2.2.1 Learning the Business Domain Understanding the domain area of the problem is essential. In many cases, data scientists will have deep computational and quantitative knowledge that can be broadly applied across many disciplines. An example

of this role would be someone with an advanced degree in applied mathematics or statistics. These data scientists have deep knowledge of the methods, techniques, and ways for applying heuris-

tics to a variety of business and conceptual problems. Others in this area may have deep knowledge of a domain area, coupled with quantitative expertise. An example of this would be someone with a Ph.D. in life sciences. This person would have deep knowledge of a field of study, such as oceanography, biology, or genetics, with some depth of quantitative knowledge.

At this early stage in the process, the team needs to determine how much business or domain knowledge the data scientist needs to develop models in Phases 3 and 4. The earlier the team can make this assessment

2.2 Phase 1: Discovery

the better, because the decision helps dictate the resources needed for the project team and ensures the

team has the right balance of domain knowledge and technica l expertise.

FIGURE 2-3 Discovery phase

2.2.2 Resources

Do I have enough Information to draft an analytic plan and

share for peer review?

As part of the discovery phase, the team needs to assess the resources available to support the project. In

this context, resources include technology, tools, systems, data, and people.

During this scoping, consider the available tools and technology the team will be using and the types

of systems needed for later phases to operat ionalize the models. In addition, try to evaluate the level of

analytica l sophisticat ion within the organization and gaps that may exist related to tools, technology, and

skills. For instance, for the model being developed to have longevity in an organization, consider what

types of skills and roles will be required that may not exist today. For the project to have long-term success,

DATA ANALYTIC$ LIFECVCLE

what types of skills and roles will be needed for the recipients of the model being developed? Does the requisite level of expertise exist within the organization today, or will it need to be cultivated? Answering these questions will influence the techniques the team selects and the kind of implementation the team chooses to pursue in subsequent phases of the Data Analytics lifecycle.

In addition to the skills and computing resources, it is advisable to take inventory of the types of data available to the team for the project. Consider if the data available is sufficient to support the project's goals. The team will need to determine whether it must collect additional data, purchase it from outside sources, or transform existing data. Often, projects are started looking only at the data available. When the data is less than hoped for, the size and scope of the project is reduced to work within the constraints of the existing data.

An alternative approach is to consider the long-term goals of this kind of project, without being con- strained by the current data. The team can then consider what data is needed to reach the long-term goals and which pieces of this multistep journey can be achieved today with the existing data. Considering longer-term goals along with short-term goals enables teams to pursue more ambitious projects and treat a project as the first step of a more strategic initiative, rather than as a standalone initiative. It is critical to view projects as part of a longer-term journey, especially if executing projects in an organization that is new to Data Science and may not have embarked on the optimum datasets to support robust analyses up to this point.

Ensure the project team has the right mix of domain experts, customers, analytic talent, and project management to be effective. In addition, evaluate how much time is needed and if the team has the right breadth and depth of skills.

After taking inventory of the tools, technology, data, and people, consider if the team has sufficient resources to succeed on this project, or if additional resources are needed. Negotiating for resources at the outset of the project, while seeping the goals, objectives, and feasibility, is generally more useful than later in the process and ensures sufficient time to execute it properly. Project managers and key stakeholders have better success negotiating for the right resources at this stage rather than later once the project is underway.

2.2.3 Framing the Problem Framing the problem well is critical to the success of the project. Framing is the process of stating the analytics problem to be solved. At this point, it is a best practice to write down the problem statement and share it with the key stakeholders. Each team member may hear slightly different things related to the needs and the problem and have somewhat different ideas of possible solutions. For these reasons, it is crucial to state the analytics problem, as well as why and to whom it is important. Essentially, the team needs to clearly articulate the current situation and its main challenges.

As part of this activity, it is important to identify the main objectives of the project, identify what needs to be achieved in business terms, and identify what needs to be done to meet the needs. Additionally, consider the objectives and the success criteria for the project. What is the team attempting to achieve by doing the project, and what will be considered "good enough" as an outcome of the project? This is critical to document and share with the project team and key stakeholders. It is best practice to share the statement of goals and success criteria with the team and confirm alignment with the project sponsor's expectations.

Perhaps equally important is to establish failure criteria. Most people doing projects prefer only to think of the success criteria and what the conditions will look like when the participants are successful. However, this is almost taking a best-case scenario approach, assuming that everything will proceed as planned

2.2 Phase 1: Discovery

and the project team will reach its goals. However, no matter how well planned, it is almost impossible to plan for everything that will emerge in a project. The failure criteria will guide the team in understanding when it is best to stop trying or settle for the results that have been gleaned from the data. Many times people will continue to perform analyses past the point when any meaningful insights can be drawn from the data. Establishing criteria for both success and failure helps the participants avoid unproductive effort and remain aligned with the project sponsors

2.2.4 Identifying Key Stakeholders Another important step is to identify the key stakeholders and their interests in the project. During these discussions, the team can identify the success criteria, key risks, and stakeholders, which should include anyone who will benefit from the project or will be significantly impacted by the project. When interviewing stakeholders, learn about the domain area and any relevant history from similar analytics projects. For example, the team may identify the results each stakeholder wants from the project and the criteria it will use to judge the success of the project.

Keep in mind that the analytics project is being initiated for a reason. It is critical to articulate the pain points as clearly as possible to address them and be aware of areas to pursue or avoid as the team gets further into the analytical process. Depending on the number of stakeholders and participants, the team may consider outlining the type of activity and participation expected from each stakeholder and partici- pant. This will set clear expectations with the participants and avoid delays later when, for example, the team may feel it needs to wait for approval from someone who views himself as an adviser rather than an approver of the work product.

2.2.5 Interviewing the Analytics Sponsor The team should plan to collaborate with the stakeholders to clarify and frame the analytics problem. At the outset, project sponsors may have a predetermined solution that may not necessarily realize the desired outcome. In these cases, the team must use its knowledge and expertise to identify the true underlying problem and appropriate solution.

For instance, suppose in the early phase of a project, the team is told to create a recommender system for the business and that the way to do this is by speaking with three people and integrating the product recommender into a legacy corporate system. Although this may be a valid approach, it is important to test the assumptions and develop a clear understanding of the problem. The data science team typically may have a more objective understanding of the problem set than the stakeholders, who may be suggesting solutions to a given problem. Therefore, the team can probe deeper into the context and domain to clearly define the problem and propose possible paths from the problem to a desired outcome. In essence, the data science team can take a more objective approach, as the stakeholders may have developed biases over time, based on their experience. Also, what may have been true in the past may no longer be a valid working assumption. One possible way to circumvent this issue is for the project sponsor to focus on clearly defining the requirements, while the other members of the data science team focus on the methods needed to achieve the goals.

When interviewing the main stakeholders, the team needs to take time to thoroughly interview the project sponsor, who tends to be the one funding the project or providing the high-level requirements. This person understands the problem and usually has an idea of a potential working solution. It is critical

DATA ANALYTICS LIFE CYCLE

to thoroughly understand the sponsor's perspective to guide the team in getting started on the project.

Here are some tips for interviewing project sponsors:

• Prepare for the interview; draft questions, and review with colleagues.

• Use open-ended questions; avoid asking lead ing questions.

• Probe for details and pose follow-up questions.

• Avoid filling every silence in the conversation; give the other person time to think.

• Let the sponsors express thei r ideas and ask clarifying questions, such as "Why? Is that correct? Is this idea on target? Is there anything else?"

• Use active listening techniques; repeat back what was heard to make sure the team heard it correctly, or reframe what was sa id.

• Try to avoid expressing the team's opinions, which can introduce bias; instead, focus on listening.

• Be mindful of the body language of the interviewers and stakeholders; use eye contact where appro- priate, and be attentive.

• Minimize distractions.

• Document what the team heard, and review it with the sponsors.

Following is a brief list of common questions that are helpful to ask during the discovery phase when

interviewing the project sponsor. The responses wi ll begin to shape the scope of the project and give the

team an idea of the goals and objectives of the project.

• What business problem is the team trying to solve?

• What is the desired outcome of the project?

• What data sources are available?

• What industry issues may impact the analysis?

• What timelines need to be considered?

• Who could provide insight into the project?

• Who has final decision-making authority on the project?

• How wi ll the focus and scope of the problem change if the following dimensions change:

• Time: Analyzing 1 year or 10 years' worth of data?

• People: Assess impact of changes in resources on project timeline.

• Risk: Conservative to aggressive

• Resources: None to unlimited (tools, technology, systems)

• Size and attributes of data: Including internal and external data sources

2.2 Phase 1: Discovery

2.2.6 Developing Initial Hypotheses Developing a set of IHs is a key facet of the discovery phase. This step involves forming ideas that the team can test with data. Generally, it is best to come up with a few primary hypotheses to test and then be creative about developing several more. These IHs form the basis of the analytical tests the team will use in later phases and serve as the foundation for the findings in Phase 5. Hypothesis testing from a statisti- cal perspective is covered in greater detail in Chapter 3, "Review of Basic Data Analytic Methods Using R."

In this way, the team can compare its answers with the outcome of an experiment or test to generate additional possible solutions to problems. As a result, the team will have a much richer set of observations to choose from and more choices for agreeing upon the most impactful conclusions from a project.

Another part of this process involves gathering and assessing hypotheses from stakeholders and domain experts who may have their own perspective on what the problem is, what the solution should be, and how to arrive at a solution. These stakeholders would know the domain area well and can offer suggestions on ideas to test as the team formulates hypotheses during this phase. The team will likely collect many ideas that may illuminate the operating assumptions of the stakeholders. These ideas will also give the team opportunities to expand the project scope into adjacent spaces where it makes sense or design experiments in a meaningful way to address the most important interests of the stakeholders. As part of this exercise, it can be useful to obtain and explore some initial data to inform discussions with stakeholders during the hypothesis-forming stage.

2.2.7 Identifying Potential Data Sources As part of the discovery phase, identify the kinds of data the team will need to solve the problem. Consider the volume, type, and time span of the data needed to test the hypotheses. Ensure that the team can access more than simply aggregated data. In most cases, the team will need the raw data to avoid introducing bias for the downstream analysis. Recalling the characteristics of Big Data from Chapter 1, assess the main characteristics of the data, with regard to its volume, variety, and velocity of change. A thorough diagno- sis of the data situation will influence the kinds of tools and techniques to use in Phases 2-4 of the Data Analytics lifecycle.ln addition, performing data exploration in this phase will help the team determine the amount of data needed, such as the amount of historical data to pull from existing systems and the data structure. Develop an idea of the scope of the data needed, and validate that idea with the domain experts on the project.

The team should perform five main activities during this step of the discovery phase:

o Identify data sources: Make a list of candidate data sources the team may need to test the initial hypotheses outlined in this phase. Make an inventory of the datasets currently available and those that can be purchased or otherwise acquired for the tests the team wants to perform.

o Capture aggregate data sources: This is for previewing the data and providing high-level under- standing. It enables the team to gain a quick overview of the data and perform further exploration on specific areas. It also points the team to possible areas of interest within the data.

o Review the raw data: Obtain preliminary data from initial data feeds. Begin understanding the interdependencies among the data attributes, and become familiar with the content of the data, its quality, and its limitations.

DATA ANALYTICS LIFECYCLE

• Evaluate the data structures and tools needed: The data type and structure dictate which tools the team can use to analyze the data. This evaluation gets the team thinking about which technologies may be good candidates for the project and how to start getting access to these tools.

• Scope the sort of data infrastructure needed for this type of problem: In addition to the tools needed, the data influences the kind of infrastructure that 's required, such as disk storage and net- work capacity.

Unlike many traditional stage-gate processes, in which the team can advance only when specific criteria

are met, the Data Ana lytics Lifecycle is intended to accommodate more ambiguity. This more closely reflects how data science projects work in real-life situations. For each phase of the process, it is recommended

to pass certain checkpoints as a way of gauging whether the team is ready to move to the next phase of

the Data Analytics Lifecycle. The team can move to the next phase when it has enough information to draft an analytics plan and

share it for peer review. Although a peer review of the plan may not actually be required by the project,

creating the plan is a good test of the team's grasp of the business problem and the team's approach to addressing it. Creating the analytic plan also requires a clear understanding of the domain area, the problem to be solved, and scoping of the data sources to be used. Developing success criteria early in the

project clarifies the problem definition and helps the team when it comes time to make choices about

the analytical methods being used in later phases.

2.3 Phase 2: Data Preparation The second phase of the Data Analytics Lifecycle involves data preparation, which includes the steps to explore, preprocess, and condition data prior to model ing and analysis. In this phase, the team needs to create a robust environment in which it can explore the data that is separate from a production environment.

Usually, this is done by preparing an analytics sandbox. To get the data into the sandbox, the team needs to

perform ETLT, by a combination of extracting, transforming, and loading data into the sandbox. Once the data is in the sandbox, the team needs to learn about the data and become familiar with it. Understanding

the data in detail is critical to the success of the project. The team also must decide how to condition and transform data to get it into a format to facilitate subsequent analysis. The team may perform data visua liza-

tions to help team members understand the data, including its trends, outliers, and relationships among data variables. Each of these steps of the data preparation phase is discussed throughout this section.

Data preparation tends to be the most labor-intensive step in the analytics lifecycle.ln fact, it is common for teams to spend at least SOo/o of a data science project's time in this critical phase. if the team cannot obtain enough data of sufficient quality, it may be unable to perform the subsequent steps in the lifecycle process.

Figure 2-4 shows an overview of the Data Analytics Lifecycle for Phase 2. The data preparation phase is generally the most iterative and the one that teams tend to underestimate most often. This is because most teams and leaders are anxious to begin analyzing the data, testing hypotheses, and getting answers to some of the questions posed in Phase 1. Many tend to jump into Phase 3 or Phase 4 to begin rapid ly developing models and algorithms without spending the time to prepare the data for modeling. Consequently, teams

come to realize the data they are working with does not allow them to execute the models they want, and they end up back in Phase 2 anyway.

Frc;uRE 2 Data preparation phase

2.3.1 Preparing the Analytic Sandbox

2.3 Phase 2: Data Preparation

Do I have enough good

quality data to start building the model?

The first subphase of data preparation requires the team to obtain an analytic sandbox (also commonly referred to as a workspace), in which the team ca n explore the data without interfering with live produc-

tion databases. Consider an example in which the team needs to work with a company's financial data. The team should access a copy of the financial data from the analytic sandbox rather than interacting with the product ion version of the organization's main database, because that will be tight ly controlled and

needed for financial reporting. When developing the analytic sandbox, it is a best practice to collect all kinds of data there, as team

members need access to high volumes and varieties of data for a Big Data analytics project. This can include

DATA ANALYTICS LIFECYCLE

everything from summary-level aggregated data, structured data, raw data feeds, and unstructured text data from call logs or web logs, depending on the kind of analysis the team plans to undertake.

This expansive approach for attracting data of all kind differs considerably from the approach advocated by many information technology (IT) organizations. Many IT groups provide access to only a particular sub- segment of the data for a specific purpose. Often, the mindset of the IT group is to provide the minimum amount of data required to allow the team to achieve its objectives. Conversely, the data science team wants access to everything. From its perspective, more data is better, as oftentimes data science projects are a mixture of purpose-driven analyses and experimental approaches to test a variety of ideas. In this context, it can be challenging for a data science team if it has to request access to each and every dataset and attribute one at a time. Because of these differing views on data access and use, it is critical for the data science team to collaborate with IT, make clear what it is trying to accomplish, and align goals.

During these discussions, the data science team needs to give IT a justification to develop an analyt- ics sandbox, which is separate from the traditional IT-governed data warehouses within an organization. Successfully and amicably balancing the needs of both the data science team and IT requires a positive working relationship between multiple groups and data owners. The payoff is great. The analytic sandbox enables organizations to undertake more ambitious data science projects and move beyond doing tradi- tional data analysis and Business Intelligence to perform more robust and advanced predictive analytics.

Expect the sandbox to be large.lt may contain raw data, aggregated data, and other data types that are less commonly used in organizations. Sandbox size can vary greatly depending on the project. A good rule is to plan for the sandbox to be at least 5-10 times the size of the original data sets, partly because copies of the data may be created that serve as specific tables or data stores for specific kinds of analysis in the project.

Although the concept of an analytics sandbox is relatively new, companies are making progress in this area and are finding ways to offer sandboxes and workspaces where teams can access data sets and work in a way that is acceptable to both the data science teams and the IT groups.

2.3.2 Performing ETLT As the team looks to begin data transformations, make sure the analytics sandbox has ample bandwidth and reliable network connections to the underlying data sources to enable uninterrupted read and write. In ETL, users perform extract, transform, load processes to extract data from a datastore, perform data transformations, and load the data back into the datastore. However, the analytic sandbox approach differs slightly; it advocates extract, load, and then transform.ln this case, the data is extracted in its raw form and loaded into the datastore, where analysts can choose to transform the data into a new state or leave it in its original, raw condition. The reason for this approach is that there is significant value in preserving the raw data and including it in the sandbox before any transformations take place.

For instance, consider an analysis for fraud detection on credit card usage. Many times, outliers in this data population can represent higher-risk transactions that may be indicative of fraudulent credit card activity. Using ETL, these outliers may be inadvertently filtered out or transformed and cleaned before being loaded into the datastore.ln this case, the very data that would be needed to evaluate instances of fraudu- lent activity would be inadvertently cleansed, preventing the kind of analysis that a team would want to do.

Following the ELT approach gives the team access to clean data to analyze after the data has been loaded into the database and gives access to the data in its original form for finding hidden nuances in the data. This approach is part of the reason that the analytic sandbox can quickly grow large. The team may want clean data and aggregated data and may need to keep a copy of the original data to compare against or

2.3 Phase 2: Data Preparation

look for hidden patterns that may have existed in the data before the cleaning stage. This process can be summarized as ETLT to reflect the fact that a team may choose to perform ETL in one case and ELT in another.

Depending on the size and number of the data sources, the team may need to consider how to paral- lelize the movement of the datasets into the sandbox. For this purpose, moving large amounts of data is sometimes referred to as Big ETL. The data movement can be parallelized by technologies such as Hadoop or MapReduce, which will be explained in greater detail in Chapter 10, "Advanced Analytics-Technology and Tools: MapReduce and Hadoop." At this point, keep in mind that these technologies can be used to perform parallel data ingest and introduce a huge number of files or datasets in parallel in a very short period of time. Hadoop can be useful for data loading as well as for data analysis in subsequent phases.

Prior to moving the data into the analytic sandbox, determine the transformations that need to be performed on the data. Part of this phase involves assessing data quality and structuring the data sets properly so they can be used for robust analysis in subsequent phases. In addition, it is important to con- sider which data the team will have access to and which new data attributes will need to be derived in the data to enable analysis.

As part of the ETLT step, it is advisable to make an inventory of the data and compare the data currently available with datasets the team needs. Performing this sort of gap analysis provides a framework for understanding which datasets the team can take advantage of today and where the team needs to initiate projects for data collection or access to new datasets currently unavailable. A component of this sub phase involves extracting data from the available sources and determining data connections for raw data, online transaction processing (OLTP) databases, online analytical processing (OLAP) cubes, or other data feeds.

Application programming interface (API) is an increasingly popular way to access a data source [8]. Many websites and social network applications now provide APis that offer access to data to support a project or supplement the datasets with which a team is working. For example, connecting to the Twitter API can enable a team to download millions of tweets to perform a project for sentiment analysis on a product, a company, or an idea. Much of the Twitter data is publicly available and can augment other data sets used on the project.

2.3.3 Learning About the Data A critical aspect of a data science project is to become familiar with the data itself. Spending time to learn the nuances of the datasets provides context to understand what constitutes a reasonable value and expected output versus what is a surprising finding. In addition, it is important to catalog the data sources that the team has access to and identify additional data sources that the team can leverage but perhaps does not have access to today. Some of the activities in this step may overlap with the initial investigation of the datasets that occur in the discovery phase. Doing this activity accomplishes several goals.

o Clarifies the data that the data science team has access to at the start of the project

o Highlights gaps by identifying datasets within an organization that the team may find useful but may not be accessible to the team today. As a consequence, this activity can trigger a project to begin building relationships with the data owners and finding ways to share data in appropriate ways. In addition, this activity may provide an impetus to begin collecting new data that benefits the organi- zation or a specific long-term project.

o Identifies datasets outside the organization that may be useful to obtain, through open APis, data sharing, or purchasing data to supplement already existing datasets

DATA ANALYTICS LIFECYCLE

Table 2-1 demonstrates one way to organize this type of data inventory.

TABLE: 1 Sample Dataset Inventory

Data Available Data to Obtain and Data Available, but Data to from Third

Dataset Accessible not Accessible Collect Party Sources

Products shipped e

Product Financials •

Product Ca ll Center • Data

Live Product Feedback Surveys

Product Sentiment from Social Media

2.3.4 Data Conditioning

• •

Data conditioning refers to the process of cleaning data, normalizing datasets, and performing trans- formations on the data. A critical step with in the Data Ana lytics Lifecycle, data conditioning can involve

many complex steps to join or merge data sets or otherwise get datasets into a state that enables analysis in further phases. Data conditioning is often viewed as a preprocessing step for the data analysis because

it involves many operations on the dataset before developing models to process or analyze the data. This implies that the data-conditioning step is performed only by IT, the data owners, a DBA, or a data engineer. However, it is also important to involve the data scientist in this step because many decisions are made in

the data conditioning phase that affect subsequent analysis. Part of this phase involves deciding which aspects of particular datasets will be useful to analyze in later steps. Because teams begin forming ideas

in this phase about which data to keep and which data to transform or discard, it is important to involve multiple team members in these decisions. Leaving such decisions to a single person may cause teams to return to this phase to retrieve data that may have been discarded.

As with the previous example of deciding which data to keep as it relates to fraud detection on credit card usage, it is critical to be thoughtful about which data the team chooses to keep and which data will be discarded. This can have far-reaching consequences that will cause the team to retrace previous steps if the team discards too much of the data at too early a point in this process. Typically, data science teams would rather keep more data than too little data for the analysis. Additional questions and considerations

for the data conditioning step include these.

• What are the data sources? What are the target fields (for example, columns of the tables)?

• How clean is the data?

2.3 Phase 2: Data Preparation

o How consistent are the contents and files? Determine to what degree the data contains missing or inconsistent values and ifthe data contains values deviating from normal.

o Assess the consistency of the data types. For instance, if the team expects certain data to be numeric, confirm it is numeric or if it is a mixture of alphanumeric strings and text.

o Review the content of data columns or other inputs, and check to ensure they make sense. For instance, if the project involves analyzing income levels, preview the data to confirm that the income values are positive or if it is acceptable to have zeros or negative values.

o Look for any evidence of systematic error. Examples include data feeds from sensors or other data sources breaking without anyone noticing, which causes invalid, incorrect, or missing data values. In addition, review the data to gauge if the definition ofthe data is the same over all measurements. In some cases, a data column is repurposed, or the column stops being populated, without this change being annotated or without others being notified.

2.3.5 Survey and Visualize After the team has collected and obtained at least some of the datasets needed for the subsequent analysis, a useful step is to leverage data visualization tools to gain an overview of the data. Seeing high-level patterns in the data enables one to understand characteristics about the data very quickly. One example is using data visualization to examine data quality, such as whether the data contains many unexpected values or other indicators of dirty data. (Dirty data will be discussed further in Chapter 3.) Another example is skewness, such as if the majority of the data is heavily shifted toward one value or end of a continuum.

Shneiderman [9] is well known for his mantra for visual data analysis of "overview first, zoom and filter, then details-on-demand." This is a pragmatic approach to visual data analysis. It enables the user to find areas of interest, zoom and filter to find more detailed information about a particular area of the data, and then find the detailed data behind a particular area. This approach provides a high-level view of the data and a great deal of information about a given dataset in a relatively short period of time.

When pursuing this approach with a data visualization tool or statistical package, the following guide- lines and considerations are recommended.

o Review data to ensure that calculations remained consistent within columns or across tables for a given data field. For instance, did customer lifetime value change at some point in the middle of data collection? Or if working with financials, did the interest calculation change from simple to com- pound at the end of the year?

o Does the data distribution stay consistent over all the data? If not, what kinds of actions should be taken to address this problem?

o Assess the granularity of the data, the range of values, and the level of aggregation of the data.

o Does the data represent the population of interest? For marketing data, if the project is focused on targeting customers of child-rearing age, does the data represent that, or is it full of senior citizens and teenagers?

o For time-related variables, are the measurements daily, weekly, monthly? Is that good enough? Is time measured in seconds everywhere? Or is it in milliseconds in some places? Determine the level of granularity of the data needed for the analysis, and assess whether the current level of timestamps on the data meets that need.

DATA ANALYTICS LIFECYCLE

• Is the data standardized/normalized? Are the scales consistent? If not, how consistent or irregular is the data?

• For geospatial datasets, are state or country abbreviations consistent across the data? Are personal names normalized? English units? Metric units?

These are typical considerations that should be part of the thought process as the team evaluates the data sets that are obtained for the project. Becoming deeply knowledgeable about the data will be critica l when it comes time to construct and run models later in the process.

2.3.6 Common Tools for the Data Preparation Phase Several tools are commonly used for this phase:

• Hadoop [10] can perform massively parallel ingest and custom analysis for web traffic parsing, GPS location analytics, genomic analysis, and combining of massive unstructured data feeds from mul- tiple sources.

• Alpine Miner [11] provides a graphical user interface (GUI) for creating analytic work flows, including data manipulations and a series of analytic events such as staged data-mining techniques (for exam- ple, first select the top 100 customers, and then run descriptive statistics and clustering) on Postgres SQL and other Big Data sources.

• Open Refine (formerly ca lled Google Refine) [12] is "a free, open source, powerful tool for working with messy data." It is a popular GUI-based tool for performing data transformations, and it's one of the most robust free tools currently available.

• Simi lar to Open Refine, Data Wrangler [13] is an interactive tool for data cleaning and transformation. Wrangler was developed at Stanford University and can be used to perform many transformations on a given dataset. In addition, data transformation outputs can be put into Java or Python. The advan- tage of this feature is that a subset of the data can be manipulated in Wrangler via its GUI, and then the same operations can be written out as Java or Python code to be executed against the full, larger dataset offline in a local analytic sandbox.

For Phase 2, the team needs assistance from IT, DBAs, or whoever controls the Enterprise Data Warehouse (EDW) for data sources the data science team would like to use.

2.4 Phase 3: Model Planning In Phase 3, the data science team identifies candidate models to apply to the data for clustering,

classifying, or finding relationships in the data depending on the goal of the project, as shown in Figure 2-5. It is during this phase that the team refers to the hypotheses developed in Phase 1, when they first became acquainted with the data and understanding the business problems or domain area. These hypotheses help the team frame the analytics to execute in Phase 4 and select the right methods to achieve its objectives.

Some of the activities to consider in this phase include the following:

• Assess the structure of the datasets. The structure of the data sets is one factor that dictates the tools and analytical techniques for the next phase. Depending on whether the team plans to analyze tex- tual data or transactional data, for example, different tools and approaches are required.

• Ensure that the analytical techniques enable the team to meet the business objectives and accept or reject the working hypotheses.

2.4 Phase 3: Model Planning

• Determine if the situation warrants a single model or a series of techniques as part of a larger analytic workflow. A few example models include association rules (Chapter 5, "Advanced Ana lytical Theory and Methods: Association Rules") and logistic regression (Chapter 6, "Advanced Analytical Theory and Methods: Regression"). Other tools, such as Alpine Miner, enable users to set up a series of steps and analyses and can serve as a front·end user interface (UI) for manipulating Big Data sources in PostgreSQL.

FIGURE 2·5 Model planning phase

Do I have a good Idea about the type of model to try? Can I refine the

analytic plan?

In addition to the considerations just listed, it is useful to research and understand how other analysts generally approach a specific kind of problem. Given the kind of data and resources that are available, eva lu- ate whether similar, existing approaches will work or if the team will need to create something new. Many times teams can get ideas from analogous problems that other people have solved in different industry

verticals or domain areas. Table 2-2 summarizes the results of an exercise of this type, involving several domain areas and the types of models previously used in a classification type of problem after conducting

research on churn models in multiple industry verti ca ls. Performing this sort of diligence gives the team

DATAANALYTICS LIFECYCLE

ideas of how others have solved similar problems and presents the team with a list of candidate models to

try as part of the model planning phase.

TABLE 2-2 Research on Model Planning in industry Verticals

Market Sector Analytic Techniques/Methods Used

Consumer Packaged Goods

Retail Banking

Reta il Business

Wireless Telecom

Multiple linear regression, automatic relevance determination (ARD). and decision tree

Multiple regression

Logistic regression, ARD, decision tree

Neural network, decision tree, hierarchical neurofuzzy systems, rule evolver, logistic regression

2.4.1 Data Exploration and Variable Selection Although some data exploration takes place in the data preparation phase, those activities focus mainly on

data hygiene and on assessing the quality of the data itself. In Phase 3, the objective of the data exploration

is to understand the relationships among the variables to inform selection of the variables and methods

and to understand the problem domain. As with earlier phases of the Data Analytics Lifecycle, it is impor-

tant to spend t ime and focus attention on this preparatory work to make the subsequent phases of model

selection and execution easier and more efficient. A common way to conduct this step involves using tools

to perform data visualizations. Approaching the data exploration in this way aids the team in previewing

the data and assessing relationships between variables at a high level.

In many cases, stakeholders and subject matter experts have instincts and hunches about what the data

science team should be considering and analyzing. Likely, this group had some hypothesis that led to the

genesis of the project. Often, stakeholders have a good grasp of the problem and domain, although they

may not be aware of the subtleties within the data or the model needed to accept or reject a hypothesis.

Other times, stakeholders may be correct, bu t for the wrong reasons (for instance, they may be correct

about a correlation that exists but infer an incorrect reason for the correlation). Meanwhile, data scientists

have to approach problems with an unbiased mind-set and be ready to question all assumptions. As the team begins to question the incoming assumptions and test initial ideas of the projec t sponsors

and stakeholders, it needs to consider the inputs and data that will be needed, and then it must examine

whether these inputs are actually correlated with the outcomes that the team plans to predict or analyze.

Some methods and types of models will handle correlated variables better than others. Depending on what

the team is attempting to solve, it may need to consider an alternate method, reduce the number of data

inputs, or transform the inputs to allow the team to use the best method for a given business problem.

Some of these techniques will be explored further in Chapter 3 and Chapter 6.

The key to this approach is to aim for capturing the most essential predictors and variables rather than

considering every possible variable that people think may influence the outcome. Approaching the prob-

lem in this manner requires iterations and testing to identify the most essential variables for the intended

analyses. The team should plan to test a range of variables to include in the model and then focus on the most important and influential variables.

2.4 Phase 3: Model Planning

If the team plans to run regression analyses, identify the candidate predictors and outcome variables of the model. Plan to create variables that determine outcomes but demonstrate a strong relationship to the outcome rather than to the other input variables. This includes remaining vigilant for problems such as serial correlation, multicollinearity, and other typical data modeling challenges that interfere with the validity of these models. Sometimes these issues can be avoided simply by looking at ways to reframe a given problem. In addition, sometimes determining correlation is all that is needed ("black box prediction"), and in other cases, the objective of the project is to understand the causal relationship better. In the latter case, the team wants the model to have explanatory power and needs to forecast or stress test the model under a variety of situations and with different datasets.

2.4.2 Model Selection In the model selection subphase, the team's main goal is to choose an analytical technique, or a short list of candidate techniques, based on the end goal of the project. For the context of this book, a model is discussed in general terms. In this case, a model simply refers to an abstraction from reality. One observes events happening in a real-world situation or with live data and attempts to construct models that emulate this behavior with a set of rules and conditions. In the case of machine learning and data mining, these rules and conditions are grouped into several general sets of techniques, such as classification, association rules, and clustering. When reviewing this list of types of potential models, the team can winnow down the list to several viable models to try to address a given problem. More details on matching the right models to common types of business problems are provided in Chapter 3 and Chapter 4, "Advanced Analytical Theory and Methods: Clustering."

An additional consideration in this area for dealing with Big Data involves determining if the team will be using techniques that are best suited for structured data, unstructured data, or a hybrid approach. For instance, the team can leverage MapReduce to analyze unstructured data, as highlighted in Chapter 10. Lastly, the team should take care to identify and document the modeling assumptions it is making as it chooses and constructs preliminary models.

Typically, teams create the initial models using a statistical software package such as R, SAS, or Matlab. Although these tools are designed for data mining and machine learning algorithms, they may have limi- tations when applying the models to very large datasets, as is common with Big Data. As such, the team may consider redesigning these algorithms to run in the database itself during the pilot phase mentioned in Phase 6.

The team can move to the model building phase once it has a good idea about the type of model to try and the team has gained enough knowledge to refine the analytics plan. Advancing from this phase requires a general methodology for the analytical model, a solid understanding of the variables and techniques to use, and a description or diagram of the analytic workflow.

2.4.3 Common Tools for the Model Planning Phase Many tools are available to assist in this phase. Here are several of the more common ones:

o R [14] has a complete set of modeling capabilities and provides a good environment for building interpretive models with high-quality code.ln addition, it has the ability to interface with databases via an ODBC connection and execute statistical tests and analyses against Big Data via an open source connection. These two factors makeR well suited to performing statistical tests and analyt- ics on Big Data. As of this writing, R contains nearly 5,000 packages for data analysis and graphical representation. New packages are posted frequently, and many companies are providing value-add

DATA ANALVTICS LIFECVCLE

services for R (such as training, instruction, and best practices), as well as packaging it in ways to make it easier to use and more robust. This phenomenon is similar to what happened with Linux in the late 1980s and early 1990s, when companies appeared to package and make Linux easier for companies to consume and deploy. UseR with fi le extracts for offl ine analysis and optimal performance, and use RODBC connections for dynamic queries and faster development.

• SQL Analysis services [15] can perform in-database analytics of common data mining functions, involved aggregations, and basic predictive models.

• SAS/ACCESS [16] provides integration between SAS and the analytics sandbox via multiple data connectors such as OBDC, JOB(, and OLE DB. SAS itself is genera lly used on file extract s, but with SAS/ACCESS, users can connect to relational databases (such as Orac le or Teradata) and data ware- house appliances (such as Green plum or Aster), files, and enterprise applications (such as SAP and Salesforce.com).

2.5 Phase 4: Model Building In Phase 4, the data science team needs to develop data sets for training, testing, and production purposes.

These data sets enable the data scientist to develop the analytical model and train it ("t raining data"), while holding aside some of the data ("hold-out data" or "test data") for testing the model. (These topics are

addressed in more detail in Chapter 3.) During th is process, it is critical to ensure that the training and test datasets are sufficiently robust for the model and analytical techniques. A simple way to t hink of these

datasets is to view the training dataset for conducting the initial experiments and the test sets for va lidating an approach once the initia l experiments and models have been run.

In the model building phase, shown in Figure 2-6, an analytical model is developed and fit on the train-

ing data and evaluated (scored) against the test data. The phases of model planning and model building can overlap quite a bit, and in practice one can iterate back and forth between the two phases for a while before settling on a final model.

Although the modeling techniques and logic required to develop models can be highly complex, the

actual duration of th is phase can be short compared to the time spent preparing the data and defining the approaches. In general, plan to spend more time preparing and learning the data (Phases 1-2) and crafting a presentation of the findings (Phase 5). Phases 3 and 4 tend to move more quickly, although they are more

complex from a conceptual standpoint. As part of this phase, the data science team needs to execute the models defined in Phase 3. During this phase, users run models from analytical software packages, such as R or SAS, on file extracts

and small data sets for testing purposes. On a small scale, assess the va lidity of the model and its results. For instance, determine if the model accounts for most of the data and has robust predictive power. At this point, refine the models to optimize the results, such as by modifying variable inputs or reducing correlated variables where appropriate. In Phase 3, the team may have had some knowledge of correlated variables

or problematic data attributes, which will be confirmed or denied once the models are actually executed. When immersed in the details of constructing models and transforming data, many small decisions are often made about the data and the approach for the modeling. These details can be easily forgotten once the project is completed. Therefore, it is vital to record the resu lts and logic of the model during this phase. In addi tion, one must take care to record any operating assumptions that were made in the modeling process

regarding the data or the context.

Is the model robust enough? Have we

failed for sure?

FIGURE 2· 6 Model building phase

2.5 Phase 4: Model Building

Creating robust models that are suitable to a specific situation requ ires thoughtful consideration to ensure the models being developed ultimately meet the objectives outlined in Phase 1. Questions to con- sider include these:

• Does the model appear valid and accurate on the test data?

• Does the model output/behavior make sense to the domain experts? That is, does it appear as if the model is giving answers that make sense in this contex t?

• Do the parameter values of the fitted model make sense in the context of the domain?

• Is the model sufficiently accurate to meet the goal?

• Does the model avoid intolerable mistakes? Depending on context, false positives may be more seri- ous or less serious than false negatives, for instance. (False positives and false negatives are discussed further in Chapter 3 and Chapter 7, "Advanced Analytical Theory and Methods: Classification.")

DATA ANALYTICS LIFECYCLE

• Are more data or more inputs needed? Do any of the inputs need to be transformed or eliminated?

• Will the kind of model chosen support the runtime requirements?

• Is a different form of the model required to address the business problem? If so, go back to the model planning phase and revise the modeling approach.

Once the data science team can evaluate either if the model is sufficiently robust to solve the problem

or if the team has failed, it can move to the next phase in the Data Analytics Lifecycle.

2.5.1 Common Tools for the Model Building Phase There are many tools avai lable to assist in this phase, focused primarily on statistical analysis or data mining software. Common tools in this space include, but are not limited to, the following:

• Commercial Tools:

• SAS Enterprise Miner (17) allows users to run predictive and descriptive models based on large volumes of data from across the enterprise. It interoperates with other large data stores, has many partnerships, and is built for enterprise-level computing and analytics.

• SPSS Modeler [18) (provided by IBM and now called IBM SPSS Modeler) offers methods to explore and analyze data through a GUI.

• Matlab [19) provides a high-level language for performing a variety of data analytics, algo- rithms, and data exploration.

• Alpine Miner [1 1) provides a GUI front end for users to develop analytic workfiows and interact with Big Data tools and platforms on the back end.

• STATISTICA [20) and Mathematica [21) are also popular and well-regarded data mining and analytics tools.

• Free or Open Source tools:

• Rand PL/R [14) R was described earlier in the model planning phase, and PL!R is a procedural language for PostgreSQL with R. Using this approach means that R commands can be exe- cuted in database. This technique provides higher performance and is more scalable than running R in memory.

• Octave [22), a free software programming language for computational modeling, has some of the functionality of Matlab. Because it is freely available, Octave is used in major universities when teaching machine learning.

• WEKA [23) is a free data mining software package with an analytic workbench. The functions created in WEKA can be executed within Java code.

• Python is a programming language that provides toolkits for machine learning and analysis, such as scikit-learn, numpy, scipy, pandas, and related data visualization using matplotlib.

• SQL in-database implementations, such as MADlib [241. provide an alterative to in-memory desktop analytical tools. MADiib provides an open-source machine learning library of algo- rithms that can be executed in-database, for PostgreSQL or Greenplum.

2.6 Phase 5: Communicate Results

2.6 Phase 5: Communicate Results After executing the model, the team needs to compare the outcomes of the modeling to the criteria estab-

lished for success and failure. In Phase 5, shown in Figure 2-7, the team considers how best to articulate

the findings and outcomes to the various team members and stakeholders, taking into account caveats,

assumptions, and any limitations of the results. Because the presentation is of ten circulated within an

orga nization, it is critical to articulate the results properly and position the findings in a way that is appro-

priate for the audience.

FIGURE 2-7 Communicate results phase

. .. :.:··· .. :~· ,.. .· .......... ~··

As part of Phase 5, the team needs to determine if it succeeded or failed in its objectives. Many times

people do not wa nt to admit to failing, but in this instance failure should not be considered as a true

failure, but rather as a failure of the data to accept or reject a given hypothesis adequately. This concept

can be counterintuitive for those w ho have been told their whole careers not to fail. However, the key is

DATA ANALYTICS LIFECYCLE

to remember that the team must be rigorous enough with the data to determine whether it wil l prove or disprove the hypotheses outlined in Phase 1 (discovery). Sometimes teams have only done a superficial

analysis, which is not robust enough to accept or reject a hypothesis. Other times, teams perform very robust

analysis and are searching for ways to show results, even when results may not be there. It is important to strike a balance between these two extremes when it comes to analyzing data and being pragmatic in

terms of showing real-world results. When conducting this assessment, determine if the results are statistically significant and va lid. If they

are, identify the aspects of the results that stand out and may provide sa lient findings when it comes time to communicate them. If the results are not valid, think about adjustments that can be made to refine and

iterate on the model to make it va lid. During this step, assess the results and identify which data points

may have been surprising and which were in line with the hypotheses that were developed in Phase 1. Comparing the actual resu lts to the ideas formulated early on produces additional ideas and insights that would have been missed if the team had not taken time to formulate initial hypotheses early in the process.

By this time, the team should have determined which model or models address the analytical challenge in the most appropriate way. In addition, the team should have ideas of some of the findings as a result of the

project. The best practice in this phase is to record all the findings and then select the three most significant ones that can be shared with the stakeholders. In addition, the team needs to reflect on the implications

of these findings and measure the business value. Depending on what emerged as a result of the model, the team may need to spend time quantifying the business impact of the results to help prepare for the presentation and demonstrate the value of the findings. Doug Hubbard's work [6) offers insights on how

to assess intangibles in business and quantify the value of seemingly unmeasurable th ings. Now that the team has run the model, completed a thorough discovery phase, and learned a great deal

about the datasets, reflect on the project and consider what obstacles were in the project and what can be improved in the future. Make recommendations for future work or improvements to existing processes, and

consider what each of the team members and stakeholders needs to fulfi ll her responsibil ities. For instance, sponsors must champion the project. Stakeholders must understand how the model affects their processes. (For example, if the team has created a model to predict customer churn, the Marketing team must under-

stand how to use the churn model predictions in planning their interventions.) Production engineers need to operationalize the work that has been done. In addition, this is the phase to underscore the business benefits of the work and begin making the case to implement the logic into a live production environment.

As a result of this phase, the team will have documented the key findings and major insights derived

from the analysis. The deliverable of this phase will be the most visible portion of the process to the outside stakeholders and sponsors, so take care to clearly articulate the results, methodology, and business value of the findings. More details will be provided about data visualization tools and references in Chapter 12, "The Endgame, or Putting It All Together."

2.7 Phase 6: Operationalize In the final phase, the team communicates the benefits of the project more broadly and sets up a pilot

project to deploy the work in a controlled way before broadening the work to a full enterprise or ecosystem of users. In Phase 4, the team scored the model in the analytics sandbox. Phase 6, shown in Figure 2-8, represents the first time that most analytics teams approach deploying the new ana lytical methods or

models in a production environment. Rather than deploying these models immediately on a wide-scale

2.7 Phase 6: Operationalize

basis, the risk can be managed more effectively and the team can learn by undertaking a small scope, pilot

deployment before a wide-scale rollout. This approach enables the team to learn about the performance and related constraints of the model in a production environment on a small scale and make adjustments before a full deployment. During the pilot project, the team may need to consider executing the algorithm

in the database rather than with in-memory tools such as R because the run time is significantly faster and more efficient than running in-memory, especially on larger datasets.

FIGURE 2-8 Model operationalize phase

While scoping the effort involved in conducting a pilot project, consider running the model in a production environment for a discrete set of products or a single line of business, which tests the model

in a live setting. This allows the team to learn from the deployment and make any needed adjustments before launching the model across the enterprise. Be aware that this phase can bring in a new set of team members- usually the engineers responsible for the production environment who have a new set of issues and concerns beyond those of the core project team. This technical group needs to ensure that

DATA ANALYTIC$ LIFECYCLE

running the model fits smoothly into the production environment and that the model can be integrated

into related business processes. Part of the operationalizing phase includes creating a mechanism for performing ongoing monitoring

of model accuracy and, if accuracy degrades, finding ways to retrain the model. If feasible, design alerts for when the model is operating "out-of-bounds." This includes situations when the inputs are beyond the

range that the model was trained on, which may cause the outputs of the model to be inaccurate or invalid. If this begins to happen regularly, the model needs to be retrained on new data.

Often, analytical projects yield new insights about a business, a problem, or an idea that people may

have taken at face value or thought was impossible to explore. Four main deliverables can be created to

meet the needs of most stakeholders. This approach for developing the four deliverables is discussed in greater detail in Chapter 12.

Figure 2-9 portrays the key outputs for each of the main stakeholders of an analytics project and what

they usually expect at the conclusion of a project.

• Business User typically tries to determine the benefits and implications of the findings to the business.

• Project Sponsor typica lly asks questions related to the business impact of the project, the risks and return on investment (ROI), and the way the project can be evangelized within the organization (and beyond).

• Project Manager needs to determine if the project was completed on time and within budget and how well the goals were met.

• Business Intelligence Analyst needs to know if the reports and dashboards he manages will be impacted and need to change.

• Data Engineer and Database Administrator (DBA) typical ly need to share their code from the ana- lytics project and create a technical document on how to implement it.

• Data Scientist needs to share the code and explain the model to her peers, managers, and other stakeholders.

Although these seven roles represent many interests within a project, these interests usually overlap, and most of them can be met with four main deliverables.

• Presentation for project sponsors: This contains high-level takeaways for executive level stakehold- ers, with a few key messages to aid their decision-making process. Focus on clean, easy visuals for the presenter to explain and for the viewer to grasp.

• Presentation for analysts, which describes business process changes and reporting changes. Fellow data scientists will want the details and are comfortable with technical graphs (such as Receiver Operating Characteristic [ROC) curves, density plots, and histograms shown in Chapter 3 and Chapter 7).

• Code for technical people.

• Technical specifications of implementing the code.

As a general rule, the more executive the audience, the more succinct the presentation needs to be. Most executive sponsors attend many briefings in the course of a day or a week. Ensure that the presenta- tion gets to the point quickly and frames the results in terms of value to the sponsor's organization. For instance, if the team is working with a bank to analyze cases of credit card fraud, highlight the frequency of fraud, the number of cases in the past month or year, and the cost or revenue impact to the bank

2.8 Case Study: Global Innovation Network and Analysis (GINA)

(or focus on the reverse-how much more revenue the bank could gain if it addresses the fraud problem).

This demonstrates the business impact better than deep dives on the methodology. The presentation

needs to include supporting information about analytical methodology and data sources, but generally only as supporting detail or to ensure the audience has confidence in the approach that was taken to analyze the data.

-Key Outputs from a Successful Analytic Project Code Presentation for Analysts

== Technlt411 Specs 11:011 Present1t1on for Project Sponsors

FIGURE 2-9 Key outputs from a successful ana lyrics project

When presenting to other audiences with more quantitative backgrounds, focus more time on the methodology and findings. In these instances, the team can be more expansive in describing the out-

comes, methodology, and analytical experiment with a peer group. This audience will be more interested in the techniques, especially if the team developed a new way of processing or analyzing data that can be reused in the future or appl ied to similar problems. In addition, use imagery or data visualization when possible. Although it may take more time to develop imagery, people tend to remember mental pictures to demonstrate a point more than long lists of bullets [25]. Data visualization and presentations are discussed

further in Chapter 12.

2.8 Case Study: Global Innovation Network and Analysis (GINA) EMC's Global Innovation Network and Analytics (GINA) team is a group of senior technologists located in centers of excellence (COEs) around the world. This team's charter is to engage employees across global COEs to drive innovation, research, and university partnerships. In 2012, a newly hired director wanted to

DATA ANALYTICS LIFECYCLE

improve these activities and provide a mechanism to track and analyze the related information. In addition, this team wanted to create more robust mechanisms for capturing the results of its informal conversations with other thought leaders within EMC, in academia, or in other organizations, which could later be mined

for insights. The GINA team thought its approach would provide a means to share ideas globally and increase

knowledge sharing among GINA members who may be separated geographically. It planned to create a data repository containing both structured and unstructured data to accomplish three main goals.

o Store formal and informal data.

o Track research from global technologists.

o Mine the data for patterns and insights to improve the team's operations and strategy.

The GINA case study provides an example of how a team applied the Data Analytics Ufecycle to analyze innovation data at EMC.Innovation is typically a difficult concept to measure, and this team wanted to look for ways to use advanced analytical methods to identify key innovators within the company.

2.8.1 Phase 1: Discovery In the GINA project's discovery phase, the team began identifying data sources. Although GINA was a group of technologists skilled in many different aspects of engineering, it had some data and ideas about what it wanted to explore but lacked a formal team that could perform these analytics. After consulting with various experts including Tom Davenport, a noted expert in analytics at Babson College, and Peter Gloor, an expert in collective intelligence and creator of CoiN (Collaborative Innovation Networks) at MIT, the team decided to crowdsource the work by seeking volunteers within EMC.

Here is a list of how the various roles on the working team were fulfilled.

o Business User, Project Sponsor, Project Manager: Vice President from Office of the CTO

o Business Intelligence Analyst: Representatives from IT

o Data Engineer and Database Administrator (DBA): Representatives from IT

o Data Scientist: Distinguished Engineer, who also developed the social graphs shown in the GINA case study

The project sponsor's approach was to leverage social media and blogging [26] to accelerate the col- lection of innovation and research data worldwide and to motivate teams of "volunteer" data scientists at worldwide locations. Given that he lacked a formal team, he needed to be resourceful about finding people who were both capable and willing to volunteer their time to work on interesting problems. Data scientists tend to be passionate about data, and the project sponsor was able to tap into this passion of highly talented people to accomplish challenging work in a creative way.

The data for the project fell into two main categories. The first category represented five years of idea submissions from EMC's internal innovation contests, known as the Innovation Road map (formerly called the Innovation Showcase). The Innovation Road map is a formal, organic innovation process whereby employees from around the globe submit ideas that are then vetted and judged. The best ideas are selected for further incubation. As a result, the data is a mix of structured data, such as idea counts, submission dates, inventor names, and unstructured content, such as the textual descriptions of the ideas themselves.

2.8 Case Study: Global Innovation Network and Analysis (GINA)

The second category of data encompassed minutes and notes representing innovation and research activity from around the world. This also represented a mix of structured and unstructured data. The structured data included attributes such as dates, names, and geographic locations. The unstructured documents contained the "who, what, when, and where" information that represents rich data about knowledge growth and transfer within the company. This type of information is often stored in business silos that have little to no visibility across disparate research teams.

The 10 main IHs that the GINA team developed were as follows:

o IH1: Innovation activity in different geographic regions can be mapped to corporate strategic directions.

o IH2: The length oftime it takes to deliver ideas decreases when global knowledge transfer occurs as part of the idea delivery process.

o IH3: Innovators who participate in global knowledge transfer deliver ideas more quickly than those who do not.

o IH4: An idea submission can be analyzed and evaluated for the likelihood of receiving funding.

o IHS: Knowledge discovery and growth for a particular topic can be measured and compared across geographic regions.

o IH6: Knowledge transfer activity can identify research-specific boundary spanners in disparate regions.

o IH7: Strategic corporate themes can be mapped to geographic regions.

o IHS: Frequent knowledge expansion and transfer events reduce the time it takes to generate a corpo- rate asset from an idea.

o IH9: Lineage maps can reveal when knowledge expansion and transfer did not (or has not) resulted in a corporate asset.

o IH1 0: Emerging research topics can be classified and mapped to specific ideators, innovators, bound- ary spanners, and assets.

The GINA (IHs) can be grouped into two categories:

o Descriptive analytics of what is currently happening to spark further creativity, collaboration, and asset generation

o Predictive analytics to advise executive management of where it should be investing in the future

2.8.2 Phase 2: Data Preparation The team partnered with its IT department to set up a new analytics sandbox to store and experiment on the data. During the data exploration exercise, the data scientists and data engineers began to notice that certain data needed conditioning and normalization. In addition, the team realized that several missing data sets were critical to testing some of the analytic hypotheses.

As the team explored the data, it quickly realized that if it did not have data of sufficient quality or could not get good quality data, it would not be able to perform the subsequent steps in the lifecycle process. As a result, it was important to determine what level of data quality and cleanliness was sufficient for the

DATA ANALYTICS LIFECYCLE

project being undertaken. In the case of the GINA, the team discovered that many of the names of the researchers and people interacting with the universities were misspelled or had leading and trailing spaces in the datastore. Seemingly small problems such as these in the data had to be addressed in this phase to enable better analysis and data aggregation in subsequent phases.

2.8.3 Phase 3: Model Planning In the GINA project, for much of the dataset, it seemed feasible to use social network analysis techniques to look at the networks of innovators within EMC.In other cases, it was difficult to come up with appropriate ways to test hypotheses due to the lack of data. In one case (IH9), the team made a decision to initiate a longitudinal study to begin tracking data points over time regarding people developing new intellectual property. This data collection would enable the team to test the following two ideas in the future:

o IHS: Frequent knowledge expansion and transfer events reduce the amount oftime it takes to generate a corporate asset from an idea.

o IH9: Lineage maps can reveal when knowledge expansion and transfer did not (or has not} result(ed) in a corporate asset.

For the longitudinal study being proposed, the team needed to establish goal criteria for the study. Specifically, it needed to determine the end goal of a successful idea that had traversed the entire journey. The parameters related to the scope of the study included the following considerations:

o Identify the right milestones to achieve this goal.

o Trace how people move ideas from each milestone toward the goal.

o Once this is done, trace ideas that die, and trace others that reach the goal. Compare the journeys of ideas that make it and those that do not.

o Compare the times and the outcomes using a few different methods (depending on how the data is collected and assembled). These could be as simple as t-tests or perhaps involve different types of classification algorithms.

2.8.4 Phase 4: Model Building In Phase 4, the GINA team employed several analytical methods. This included work by the data scientist using Natural Language Processing (NLP} techniques on the textual descriptions of the Innovation Road map ideas. In addition, he conducted social network analysis using Rand RStudio, and then he developed social graphs and visualizations of the network of communications related to innovation using R's ggplot2 package. Examples of this work are shown in Figures 2-10 and 2-11.

2.8 Case Study: Global Innovation Network and Analysis (GINA)

• • , t-ft11lf f

·-·· '-..lr f .. fi"-CIW1o FIGURE 2-10 Social graph [27] visualization of idea submitters and finalists

• • • 0

0 0 0 0 o o o 0 0 0

0 oo O o

0 ()

o ocflr_ og Betweenness Ranks 0 ..() 0 1. 578 o cr~ 2. 5 11 0 0() 0 3. 341 0 4. 171 0 <i"' 0 5. 138 0 0 vv

00 0 0 o·o

FIGURE 2-11 Social graph visualization of top innovation influencers

DATA ANALYTICS LIFECYCLE

Figure 2-10 shows social graphs that portray the relationships between idea submitters within GINA. Each color represents an innovator from a different country. The large dots with red circles around them represent hubs. A hub represents a person with high connectivity and a high "betweenness" score. The cluster in Figure 2-11 contains geographic variety, which is critical to prove the hypothesis about geo- graphic boundary spanners. One person in this graph has an unusually high score when compared to the rest of the nodes in the graph. The data scientist identified this person and ran a query against his name within the analytic sandbox. These actions yielded the following information about this research scientist (from the social graph), which illustrated how influential he was within his business unit and across many other areas of the company worldwide:

o In 2011, he attended the ACM SIGMOD conference, which is a top-tier conference on large-scale data management problems and databases.

o He visited employees in France who are part of the business unit for EMC's content management teams within Documentum (now part of the Information Intelligence Group, or II G).

o He presented his thoughts on the SIGMOD conference at a virtual brown bag session attended by three employees in Russia, one employee in Cairo, one employee in Ireland, one employee in India, three employees in the United States, and one employee in Israel.

o In 2012, he attended the SDM 2012 conference in California.

o On the same trip he visited innovators and researchers at EMC federated companies, Pivotal and VMware.

o Later on that trip he stood before an internal council of technology leaders and introduced two of his researchers to dozens of corporate innovators and researchers.

This finding suggests that at least part of the initial hypothesis is correct; the data can identify innovators who span different geographies and business units. The team used Tableau software for data visualization and exploration and used the Pivotal Green plum database as the main data repository and analytics engine.

2.8.5 Phase 5: Communicate Results In Phase 5, the team found several ways to cull results of the analysis and identify the most impactful and relevant findings. This project was considered successful in identifying boundary spanners and hidden innovators. As a result, the CTO office launched longitudinal studies to begin data collection efforts and track innovation results over longer periods of time. The GINA project promoted knowledge sharing related to innovation and researchers spanning multiple areas within the company and outside of it. GINA also enabled EMC to cultivate additional intellectual property that led to additional research topics and provided opportunities to forge relationships with universities for joint academic research in the fields of Data Science and Big Data. In addition, the project was accomplished with a limited budget, leveraging a volunteer force of highly skilled and distinguished engineers and data scientists.

One of the key findings from the project is that there was a disproportionately high density of innova- tors in Cork, Ireland. Each year, EMC hosts an innovation contest, open to employees to submit innovation ideas that would drive new value for the company. When looking at the data in 2011, 15% of the finalists and 15% of the winners were from Ireland. These are unusually high numbers, given the relative size of the Cork COE compared to other larger centers in other parts of the world. After further research, it was learned that the COE in Cork, Ireland had received focused training in innovation from an external consultant, which

2.8 Case Study: Global Innovation Network and Analysis (GINA)

was proving effective. The Cork COE came up with more innovation ideas, and better ones, than it had in

the past, and it was making larger contributions to innovation at EMC. It would have been difficu lt, if not

impossible, to identify this cluster of innovators through traditional methods or even anecdotal, word-of-

mouth feedback. Applying social network analysis enabled the team to find a pocket of people within EMC

who were making disproportionately strong contributions. These findings were shared internally through

presentations and conferences and promoted through social media and blogs.

2.8.6 Phase 6: Ope rationalize Running analytics against a sandbox fi lled with notes, minutes, and presentations from innovation activities

yielded great insights into EMC's innovation cu lture. Key find ings from the project include these:

• The CTO office and GINA need more data in the future, including a marketing initiative to convince people to inform the global community on their innovation/research activities.

• Some of the data is sensitive, and the team needs to consider security and privacy related to the data, such as who can run the models and see the results.

• In addition to running models, a parallel initiative needs to be created to improve basic Business Intelligence activities, such as dashboards, reporting, and queries on research activities worldwide.

• A mechanism is needed to continually reevaluate the model after deployment. Assessing the ben- efits is one of the main goals of this stage, as is defining a process to retrain the model as needed.

In addition to the actions and find ings listed, the team demonstrated how analytics can drive new

insights in projects that are traditionally difficult to measure and quantify. This project informed investment

decisions in university research projects by the CTO office and identified hidden, high-value innovators.

In addition, the CTO office developed too ls to help submitters improve ideas using topic modeling as part

of new recommender systems to help idea submitters find similar ideas and refine thei r proposals for new

intellectual property. Table 2-3 outlines an analytics plan for the GINA case study example. Although this project shows only

three findings, there were many more. For instance, perhaps the biggest overarching result from this project

is that it demonstrated, in a concrete way, that analytics can drive new insights in projects that deal with

topics that may seem difficult to measure, such as innovation.

TABLE 2-3 Analytic Plan from the EMC GINA Project

Components of Analytic Plan GINA Case Study

Discovery Business Problem Framed

Initial Hypotheses

Data

Tracking global knowledge growth, ensuring effective knowledge transfer, and quickly converting it into corporate assets. Executing on these three elements should accelerate innovation.

An increase in geographic knowledge transfer improves the speed of idea delivery.

Five years of innovation idea submissions and history; six months of textual notes from global innovation and research activities

(continues)

DATA ANALYTIC$ LIFECYCLE

TABLE 2-3 Analytic Plan from the EMC GINA Project (Continued)

Components of Analytic Plan GINA Case Study

Model Planning

Analytic Technique

Result and Key Findings

Social network analysis, socia l graphs, clustering, and regression

analysis

1. Identified hidden, high-value innovators and found ways to share their knowledge

2. Informed investment decisions in university research projects

3. Created tools to help submitters improve ideas with idea

recommender systems

Innovation is an idea that every company wants to promote, but it can be difficult to measure innovation

or identify ways to increase innovation. Th is project explored this issue from the standpoint of evaluating

informal socia l networks to identify boundary spanners and influential people within innovation sub-

networks. In essence, this project took a seemingly nebulous problem and applied advanced analytica l

methods to tease out answers using an objective, fact-based approach.

Another outcome from the project included the need to supplement analytics with a separate data-

store for Business Intell igence reporting, accessib le to search innovation/ research initiatives. Aside from

supporting decision making, th is will provide a mechanism to be informed on discussions and research

happening worldwide among team members in disparate locations. Finally, it highlighted the value that

can be gleaned through data and subsequent analysis. Therefore, the need was identified to start formal

marketing programs to convince people to submit (or inform) the global community on their innovation/

research activities. The knowledge sharing was critical. Without it, GINA would not have been able to

perform the analysis and identify the hidden innovators w ithin the company.

Summary This chapter described the Data Analytics Lifecycle, which is an approach to managing and executing

analytical projects. This approach describes the process in six phases.

1. Discovery

2. Data preparation

3. Model planning

4. Model building

5. Commun icate results

6 . Operationalize

Through these steps, data science teams can identify problems and perform rigorous investigati on of

the datasets needed for in-depth analysis. As stated in the chapter, although much is w ritten about the

analytical methods, the bulk of t he t ime spent on these kinds of projects is spent in preparation-namely,

Bibliography

in Phases 1 and 2 (discovery and data preparation). In addition, this chapter discussed the seven roles

needed for a data science team.lt is critical that organizations recognize that Data Science is a team effort,

and a balance of skills is needed to be successful in tackling Big Data projects and other complex projects

involving data analytics.

Exercises 1 . In which phase would the team expect to invest most of the project time? Why? Where would the

team expect to spend the least time?

2 . What are the benefits of doing a pilot program before a full -scale rollout of a new analytical method-

ology? Discuss this in the context of the mini case study.

3. What kinds of tools would be used in the following phases, and for which kinds of use scenarios?

a. Phase 2: Data preparation

b. Phase 4: Model building

Bibliography [1] T. H. Davenport and D. J. Patil, "Data Scientist: The Sexiest Job of the 21st Century," Harvard

Business Review, October 2012. [2) J. Manyika, M. Chiu, B. Brown, J. Bughin, R. Dobbs, C. Roxburgh, and A. H. Byers, "Big Data: The Next

Frontier for Innovation, Competition, and Productivity," McKinsey Global Institute, 2011. [3] "Scientific Method" [Online]. Available: http : //en. wikipedia . org/wiki/

Scientific method. [4) "CRISP-OM" [Online]. Available: http : //en . wikipedia . org/wiki/

Cross_Industry_Standard_Process_for_Data_Mining. [5) T. H. Davenport, J. G. Harris, and R. Morison, Analytics at Work: Smarter Decisions, Better Results,

2010, Harvard Business Review Press. [6] D. W. Hubbard, How to Measure Anything: Finding the Value of Intangibles in Business, 2010,

Hoboken, NJ: John Wiley & Sons. [7) J. Cohen, B. Dolan, M. Dunlap, J. M. Hellerstein and C. Welton, MAD Skills: New Analysis Practices

for Big Data, Watertown, MA 2009. [8] "List of APis" [Online]. Available: http : //www. programmableweb . com/apis. [9] B. Shneiderman [Online]. Available: http : //www . ifp . illinois . edu/nabhcs/

abstracts/shneiderman.html. [10) "Hadoop" [Online]. Available: http : //hadoop . apache . org. [11] "Alpine Miner" [Online]. Available: http : // alpinenow . com. [12] "OpenRefine" [Online]. Available: http : // open refine . org. [13] "Data Wrangler" [Online). Avai lable: http : //vis . stanford . edu/wrangler / . [14] "CRAN" [Online). Available: http: // cran . us . r-project . org. [15] "SQL" [Online]. Available: h ttp: //en . wikipedia . org/wiki/SQL. [16) "SAS/ACCESS" [Onl ine]. Available: http : //www . sas . com/en_ us/software/

data-management/access . htm.

DATA ANALYTICS LIFECYCLE

[17] "SAS Enterprise Miner" [Online]. Available: http: I /www. sas. com/ en_us/ software/ analytics/enterprise-miner.html.

[18] "SPSS Modeler" [Online]. Available: http: I /www- 03. ibm. com/ software/products/ en/category/business-analytics.

[19] "Matlab" [Online]. Available: http: I /www. mathworks. com/products/matlab/. [20] "Statistica" [Online]. Available: https: I /www. statsoft. com. [21] "Mathematica" [Online]. Available: http: I /www. wolfram. com/mathematical. [22] "Octave" [Online]. Available: https: I /www. gnu. erg/software/octave/. [23] "WEKA" [Online]. Available: http: I /www. cs. waikato. ac. nz/ml/weka/. [24] "MADiib" [Online]. Available: http: I /madl ib. net. [25] K. L. Higbee, Your Memory-How It Works and How to Improve It, New York: Marlowe &

Company, 1996. [26] S. Todd, "Data Science and Big Data Curriculum" [Online]. Available: http: I I steve todd

.typepad.com/my_weblog/data-science-and-big-data-curriculum/. [27] T. H Davenport and D. J. Patil, "Data Scientist: The Sexiest Job of the 21st Century," Harvard

Business Review, October 2012.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

The previous chapter presented the six phases of the Data Analytics Lifecycle.

• Phase 1: Discovery

• Phase 2: Data Preparation

• Phase 3: Model Planning

• Phase 4: Model Building

• Phase 5: Communicate Results

• Phase 6: Operationalize

The first three phases involve various aspects of data exploration. In general, the success of a data

analysis project requires a deep understanding of the data. It also requires a toolbox for mining and pre-

senting the data. These activities include the study of the data in terms of basic statistical measures and creation of graphs and plots to visualize and identify relationships and patterns. Several free or commercial tools are available for exploring, conditioning, modeling, and presenting data. Because of its popularity and

versatility, the open-source programming language R is used to illustrate many of the presented analytical

tasks and models in this book. This chapter introduces the basic functionality of the R programming language and environment. The

first section gives an overview of how to useR to acquire, parse, and filter the data as well as how to obtain

some basic descriptive statistics on a dataset. The second section examines using R to perform exploratory data analysis tasks using visua lization. The final section focuses on statistical inference, such as hypothesis testing and analysis of variance in R.

3.1 Introduction toR R is a programming language and software framework for statistical analysis and graphics. Available for use under the GNU General Public License [1], R software and installation instructions can be obtained via the Comprehensive R Archive and Network [2]. This section provides an overview of the basic functionality of R.

In later chapters, this foundation in R is utilized to demonstrate many of the presented analytical techniques. Before delving into specific operations and functions of R later in this chapter, it is important to under-

stand the now of a basic R script to address an analytical problem. The following R code illustrates a typical

analytical situation in which a dataset is imported, the contents of the dataset are examined, and some modeling building tasks are executed. Although the reader may not yet be familiar with the R syntax, the code can be followed by reading the embedded comments, denoted by #. In the following scenario, the annual sales in U.S. dollars for 10,000 retail customers have been provided in the form of a comma- separated-value (CSV) fi le. The read . csv () function is used to import the CSV file. This dataset is stored to the R variable sales using the assignment operator <- .

H imp< rt a CSV file of theo tot'l.- annual sa es for each customcl· sales <- read .csv( "c:/data/yearly_sales.csv")

# €'>:amine Lhe imported dataset head(sales)

summary (sales)

# plot num_of_orders vs. sales plot(sales$num_of_orders,sales$sales_total,

main .. "Number of Orders vs. Sales")

# perform a statistical analysis (fit a linear regression model) results <- lm(sales$sales_total - sales$num_of_orders) summary(results)

# perform some diagnostics on the fitted model # plot histogram of the residuals hist(results$residuals, breaks .. 800)

3.1 Introduction toR

In this example, the data file is imported using the read. csv () function. Once the file has been imported, it is useful to examine the contents to ensure that the data was loaded properly as well as to become familiar with the data. In the example, the head ( ) function, by default, displays the first six records of sales.

# examine the imported dataset head(sales)

cust id sales total num of orders gender - - - - 100001 800.64

2 100002 217.53 100003 74.58 2 t·l

4 100004 ·198. 60 t•l

5 100005 723.11 4 F 6 100006 69.43 2 F

The summary () function provides some descriptive statistics, such as the mean and median, for each data column. Additionally, the minimum and maximum values as well as the 1st and 3rd quartiles are provided. Because the gender column contains two possible characters, an "F" (female) or "M" (male), the summary () function provides the count of each character's occurrence.

summary(sales)

cust id i"lin. :100001 1st Qu . : 1 o 2 5o 1 l>ledian :105001 !>lean :105001 3rd Qu. :107500 l\lax. : 110 0 0 0

sales total !'-lin. 30.02 1 s t Qu . : 8 0 . 2 9 r'ledian : 151.65 t•lean 24 9. 46 3 rd Qu. : 2 9 5 . 50 t•lax. :7606.09

num of orde1·s gender !'-lin. 1.000 F:5035 1st Qu.: 2.000 !·l: 4965 t>ledian : 2.000 !>lean 2.428 3rd Qu.: 3.000 1•1ax. :22.000

Plotting a dataset's contents can provide information about the relationships between the vari- ous columns. In this example, the plot () function generates a scatterplot of the number of orders (sales$num_of_orders) againsttheannual sales (sales$sales_total). The$ is used to refer- ence a specific column in the dataset sales. The resulting plot is shown in Figure 3-1.

# plot num_of_orders vs. sales plot(sales$num_of_orders,sales$sales_total,

main .. "Number of Orders vs. Sales")

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

Number of Orders vs. Total Sales

0

iii 0 0 0 :§ 0 0 I <0

C/)

Q> 0 iii 0 § 0 0 C/) 0 0 II> 0

I I i i i 8 8 0 0 0 ~ C/) 0 0 Q> 0 • 8 iii N I I C/) • 0 5 10 15 20

sales$num_ of_ orders

FtGURE 3-1 Graphically examining the data

Each point corresponds to the number of orders and the total sales for each customer. The plot indicates

that the annual sales are proportional to the number of orders placed. Although the observed relationship

between these two variables is not purely linear, the analyst decided to apply linear regression using the lm () function as a first step in the model ing process.

resul t s <- lm(sal es$sal es_total - sales$num_of_or ders) r esults

ca.l: lm formu.a sa.c Ssales ~ota. sales$num_of_orders

Coefti 1en· In· er ep• sa:essnum o f orders

The resulting intercept and slope values are -154.1 and 166.2, respectively, for the fitted linear equation. However, results stores considerably more information that can be examined with the summary () function. Details on the contents of results are examined by applying the at t ributes () function.

Because regression analysis is presented in more detail later in the book, the reader should not overly focus on interpreting the following output.

summary(results)

Call : lm formu:a sa!esSsales_total - salcs$num_of_orders

Re!'a ilnls:

Min IQ Med1an 3C 1·1ax -666 . 5 12S . S - 26 . 7 86 . 6 4103 . 4

Coef ficient:s: Est1mate Std . Errol r value Prl> t

Intercept -15~.128 sal~s$num f orders 166 . 22l

.; . 12"' - 37 . 33 1 . 462 112 . 66

<2e-16

<2e- ~6

3.1 Introduction to R

Sior:1t . codes : 0 ' ... . 0.00! •·· · c . o: •• • 5 I • I . 1 I 1

Res1aua. star:da~d e~ro~ : ~! .: on 999° deg~ees of :reeo~m ~ultlple R·squar d : 0 . ~617 , Aa:usted P-sq~a~ed : . 561

The summary () function is an example of a generic function. A generic function is a group of func- tions sharing the same name but behaving differently depending on the number and the type of arguments they receive. Utilized previously, plot () is another example of a generic function; the plot is determined

by the passed variables. Generic functions are used throughout this chapter and the book. In the final portion of the example, the following R code uses the generic function hist () to generate a histogram (Figure 3-2) of the residuals stored in results. The function ca ll illustrates that optional parameter values can be passed. In this case, the number of breaks is specified to observe the large residuals.

~ pert H. some d13gnosLics or. the htted m .. de. # plot hist >gnm f the residu, ls his t (r esults $res idual s, breaks= 800)

Histogram of resultsSresiduals

0 I()

>-u c 0 .. 0 :J <:T ~ 0 u. I()

0

0 1000 2000 3000

resuttsSres1duals

FIGURE 3-2 Evidence of large residuals

4000

This simple example illustrates a few of the basic model planning and building tasks that may occur in Phases 3 and 4 of the Data Analytics Lifecycle. Throughout this chapter, it is useful to envision how the presented R functionality will be used in a more comprehensive analysis.

3.1.1 R Graphical User Interfaces R software uses a command-line interface (CLI) that is similar to the BASH shell in Linux or the interactive versions of scripting languages such as Python. UNIX and Linux users can enter command Rat the terminal prompt to use the CU. For Windows installations, R comes with RGui.exe, which provides a basic graphica l user interface (GUI). However, to improve the ease of writing, executing, and debugging R code, several additional GUis have been written for R. Popular GUis include the R commander [3]. Rattle [4], and RStudio [5). This section presents a brief overview of RStudio, which was used to build the R examples in th is book. Figure 3-3 provides a screenshot of the previous R code example executed in RStudio.

REVIEW O F BASIC DATA ANALYTIC M ETHODS USING R

._CNtl. .. .. t 1 ules .. r t -.d.uv " ... tw..o u ln

' 1 • -...1 • n • • "' 6llu,-...,.1.,_uh,1.u.,·

!~uln •

- - ....._.. -....y

.. tJ - ..... O....ft• f .:1-

.-------, ulu 10000 OM. ol " " whbhs

Scripts rn~o~hs ... .. , ... ... ... ... .•. ... ... ...

plot u1ts~of-orcl9ors,u1es ules_tot•l, utn-·~ ~ cwo...s '"· s..ln

. ' ruulu t"ltSIIIU

•. '

to' 1 ' Jo flt I T 1• uln ,u lu_utul ulu~,..._ot_orct«'s

11 luu

- .... ,..,.,... ""'- ; :- •toMtt· 0 { a. .....

j Workspace

'" lU Ul

•Ill r t f " ~ I hht ruuhs1t"tst~•h. br u11 • 100 r Histogram or results$reslduals ·-'" ••• iu~-~.~ ... ~------:=::::::::::::::::~

"s-uy(resulu)

c•H: l•(f or-..1& - ulululu_uul .. saln~of_orcMf's)

... , .... ls : tUn tQ lllt'dhn 1Q ~b

· 6M. 1 - US, \ •U .7 t6.6 .&10), <1

lsttuu Ud. Crrw 1 " ' ',.,. k(,.Jtl) omuupt) . ,,,,u, •.ut -Jr.n ~ •. ,, •·• ul•s~oLoro.-' u6. Ul 1. 41 61 uJ.M <-lt-16 •••

sttnU. codts : o '• •• ' o. oot •••• 0.01 ••• o.os •, • 0.1 • • 1

l:utdlu•1 sund¥d uror: 110.1 on tnt CS•vr"' or fr~ tty\ttph I:•S.,¥-.1: 0 , $617, .lodJw~t f'd l•squ.vl'd: 0 . )6)7 f" •Uathttc : t . ltl••Ool on I wrd 9Ht Of", P•VA1U41: ot l . h•16

,. #pf'rfor• ~- diA~ltn Of' Uw ttlud _,.., Jo ?lot hhtOQrM ot tt,. re~lduh ~ Mn(ruwh~k'n lcN.th, .,.,,,, · tOO)

FIGURE 3-3 RStudio GUI

.:1

Console

j

The four highlighted window panes follow.

~

~ j

~

~

• Scripts: Serves as an area to write and saveR code

1000

• Workspace: Lists the datasets and variables in the R environment

Plots

2000 3000

• Plot s: Displays the plots generated by the R code and provides a straightforward mechanism to export the plots

• Console: Provides a history of the executed R code and the output

Additionally, the console pane can be used to obtain help information on R. Figure 3-4 illustrates that by entering ? lm at the console prompt, the help details of the lm ( ) function are provided on the right. Alternatively, help ( lm) could have been entered at the console prompt.

Functions such as edit () and fix () allow the user to update the contents of an R variable. Alternatively, such changes can be implemented with RStudio by selecting the appropriate variable from the workspace pane.

R allows one to save the workspace environment, including variables and loaded libraries, into an . Rdata file using the save . image () function. An existing . Rdata file can be loaded using the load . image () function. Tools such as RStudio prompt the user for whether the developer wants to save the workspace connects prior to exiting the GUI.

The reader is encouraged to install Rand a preferred GUI to try out the R examples provided in the book and utilize the help functionality to access more details about the discussed topics.

., .. t tt • • ........... , 41 1ft f Ot l.a.l:?' ~~ t" u lu N

r e...cl.csv 411\1 , • .,.1yJ•1n.u\

" ... ... . .. hud ulu s~salu . ,. ,. ..

. ._. .

"' .. , plot ultJ l......_.,....ot'MrS ,Uh.tSnles.toul. .. ,,..-~of arden'''~· ~·u· , .. >01 ... >07 , .. , .. 110

• f • .I H-It t II t>t .II It~ r--r;~l~ ~\) ru.ulu 1• uluSulu,.ICKil ulus~of .. crd~ ru~ln

Ul "r•·f dl \1 nt,,d~l U7 •ph•t hi t< t t~ '"' ••I lU hht ru11hs Srutduah, bru~s • 1001 u• ---

,;.·,;·iah .... ~ •• ;;;.;::.:---------=========----' un: lo(f or-.la .. ultsSul•s .. tO'CAI .. uohsJtuil,..of_or~s )

luto.uh: Min IQ .. fltiM )Q '""'

~tM. , · US. S • lt.7 M , t 4110), 41

CCHff lc.l..r:ts: Uttaau St d. lrror t "' ' '"' "'(•I t I>

(fnurcept) -1~.UI <I.Ut - J1.JJ c2t-l6 ••· u1e~ lnwa..ot_orws 1641.211 1."62 UI.M -.l t - 16 ...

stvnu. cCIIOH.: o ···-· 0.001 •••• 0.01 ••• o.o\ ·.• o. t • • 1

• ntdvll nln<t¥0 tf'ror: 210.1 on t9N detJ't.S of frt~ tt~~lt tple •-•qwwtd: 0. MJ7. AdJW1ttO •·squAred: o. ~617 r -su thttc : l.2t2 ... o.& on 1 1t10 tttl cw , .,._., ,..,.: c 2.21-16

) • .,..,.,0,.. ·- ctl~tt(\ 01'1 tr.. flt\f'G ..,., • • plot ,.,,uq• of ttw rnldv• h .. "'ht(r~whs~~sl..,.h, lilr'Uh • toO) ... ,. • I -

FIGURE 3-4 Accessing help in Rstudio

-- , -

3.1.2 Data Import and Export

3.1 Introduction toR

J U .:J-

ulu

.. ...... o.ttl01 • i -;:,

ru~o~lu

J ,.. .... ,~ """ "' ...... .z..

ll f"'*"t 1--Ut M-" '"

Fitting Linear Models

.:J o .. c:ttptSon ~-u&t411 kllftl•f"'Idek I CM ... vt .. IIC:WfYWft9'*1- UIQ!It1UIIIIIII~II-I .nd 1Nfyt4vlt-•(~ • ·~~ . _.,_...clfbab'UMn)

uqrcrw:a!• , 41 c..•, , ..... ,,,, .,.l111ht•, ft• .• etlc.tl, _,bOd • • q" · · .o., .. T~. • .. ~. y .. r;u..,r, ql" • ru:z. •~h:.ct • TWI, cMtruu • II"J:.I. , o thu, . .. )

Argument1

',

f QI&l}&

J ..... lf'lot.,Kt~tl&•••t· t• liii.•(OfiDMII'IIfunbece«cldlotNIWIII ttymtdcestiiCI¥IbOnol I ::::::.~.:. ~:-:=',::7'-=:::.7::~·~101CIU I ...... )t ...... tlw""'*''"tlltfNdee fnalbn:l.ncl&:.• tt.~ ... tll ... hm u ... tr_::~, ft;....,ll l tYJIIUI1CIIt.,....,....,.kwaiiiii'O~•uhcl

II'I~'IIIKtorl~l ....... fl .......... lO beuMO~UMtc,.,poctst II'I__......U.tl....,_,teMI<MCI•t!lotiftaltJI'X-tsl SPIOII4 c.r--..:.or•-...aor 1--'UL ....,C~IM1Il ...... d•l4~..qll vt:~t•~• ~ng , .. r .... . -,,, ...,.,...,.,.,.,,., ... ...,., .. YMO S..lban.tan .=.J

In the annual retail sales example, the dataset was imported into R using the read . csv () function as

in the following code.

sales <- read . csv("c : /data/yearly_sales . csv" )

R uses a forward slash {!) as the separator character in the directory and file paths. This convention

makes script Iiies somewhat more portable at the expense of some initial confusion on the part of Windows

users, who may be accustomed to using a backslash (\) as a separator. To simpl ify the import of multiple Iiies

with long path names, the setwd () function can be used to set the working directory for the subsequent

import and export operations, as shown in the following R code.

setwd ( "c: / data/ ") sales < - read.csv ("yearly_sales . csv" )

Other import functions include read. table ( l and read . de lim () ,which are intended to import

other common file types such as TXT. These functions can also be used to import the yearly _ sales

. csv file, as the following code illustrates.

sales_table <- read .table ( "yearly_sales . csv " , header=TRUE, sep="," ) sales_delim <- read .delim ("yearly_sales . csv", sep=",")

The main difference between these import functions is the default values. For example, the read

. de lim () function expects the column separator to be a tab("\ t"). ln the event that the numerical data

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

in a data file uses a comma for the decimal, R also provides two additional functions-read . csv2 () and

read . del im2 ()-to import such data. Table 3-1 includes the expected defaults for headers, column

separators, and decimal point notations.

TABLE 3-1 Import Function Defaults

Function Headers Separator Decimal Point

r ead. t able () FALSE

r ead. csv () TRUE

r ead. csv2 ( ) TRUE "·" . read . d e lim () TRUE "\t "

r ead. delirn2 () TRUE "\t " .. . The analogous R functions such as write . table () ,write . csv () ,and write . csv 2 () enable

exporting of R datasets to an external fi le. For example, the following R code adds an additional column

to the sales dataset and exports the modified dataset to an external file.

t; ?\dd 1 ,... ... l,;.f'1Il t .. • h.;;. _'b:!l JUt :i ~ ~ j

sales$per_order < - sal es$sales_total/sales$num_of_orders

# exp 1 L d1ta 1s ''ll' 1.-.. <r u 1 "' L!1< llL t n• t '1'.' name,,

write . t able(sales ," sal es_modified .txt ", sep= "\t ", row. names=FALSE

Sometimes it is necessary to read data from a database management system (DBMS). R packages such

as DBI [6) and RODBC [7] are available for this purpose. These packages provide database interfaces

for communication between Rand DBMSs such as MySQL, Oracle, SQL Server, PostgreSQL, and Pivotal

Greenplum. The following R code demonstrates how to instal l the RODBC package with the i ns t al l

. packages () function. The 1 ibr ary () function loads the package into the R workspace. Finally, a

connector (conn ) is initialized for connecting to a Pivotal Greenplum database tra i n i ng2 via open database connectivity (ODBC) with user user. The training2 database must be defined either in the I etc/ODBC . ini configuration file or using the Administrative Tools under the Windows Control Panel.

install . packages ( "RODBC" ) library(RODBC) conn <- odbcConnect ("t r aining2", uid="user" , pwd= "passwor d " )

The connector needs to be present to submit a SQL query to an ODBC database by using the

sq l Query () function from the RODBC package. The following R code retrieves specific columns from the housi ng table in which household income (h inc ) is greater than $1,000,000.

housing_data <- s qlQuery(conn, "select serialno , s t ate, persons, r ooms from housing where hinc > 1000000")

head(housing_data )

4552088

4 45"- 88

5 8699:!93 6

5

5

5

9

9

5

3.1 Introduction to R

Although plots can be saved using the RStudio GUI, plots can also be saved using R code by specifying

the appropriate graphic devices. Using the j peg () function, the following R code creates a new JPEG

file, adds a histogram plot to the file, and then closes the fi le. Such techniques are useful w hen automating

standard reports. Other functions, such as png () , bmp () , pdf () ,and postscript () ,are available in R to save plots in the desired format.

jpeg ( fil e= "c : /data/sales_hist . j peg" )

h ist(sales$num_of_ orders ) creaLe a ne'" jpeg file

# export histogt·;un to jpeg d ev. o ff () ~ shut off the graphic device

More information on data imports and exports can be found at http : I I cran . r-proj e ct . orgl doc I ma nuals I r- rel easei R- da ta . html, such as how to import data sets from statistical software packages including Minitab, SAS, and SPSS.

3.1.3 Attribute and Data Types In the earlier example, the sales variable contained a record for each customer. Several characteristics, such as total annual sa les, number of orders, and gender, were provided for each customer. In general,

these characteristics or attributes provide the qualitative and quantitative measures for each item or subject

of interest. Attributes can be categorized into four types: nominal, ordinal, interval, and ratio (NOIR) [8).

Table 3-2 distinguishes these four attribute types and shows the operations they support. Nominal and

ordinal attributes are considered categorical attributes, whereas interval and ratio attributes are considered

numeric attributes.

TABLE 3-2 NOIR Attribute Types

Categorical (Qualitative) Numeric (Quantitative)

Nominal Ordinal Interval Rat io

Definition The va lues represent Attributes The difference Both the difference

labels that distin- imply a between two and the ratio of

guish one from sequence. values is two values are

another. meaningful. meaningful.

Examples ZIP codes, national- Quality of Temperature in Age, temperature

ity, street names, diamonds, Celsius or in Kelvin, counts, gender, employee ID academic Fahrenheit, ca l- length, weight numbers, TRUE or grades, mag- endar dates,

FALSE nitude of lati tudes earthquakes

Operations =, >' =, ~, = , ;t., =,~,

<, s , >, 2: <, s , >, c:, <, s , >, ~,

+, - + , - ,

x, .:-

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

Data of one attribute type may be converted to another. For example, the qual it yof diamonds {Fair, Good, Very Good, Premium, Ideal} is considered ordinal but can be converted to nominal {Good, Excellent} with a defined mapping. Similarly, a ratio attribute like Age can be converted into an ordinal attribute such as {Infant, Adolescent, Adult, Senior}. Understanding the attribute types in a given dataset is important to ensure that the appropriate descriptive statistics and analytic methods are applied and properly inter- preted. For example, the mean and standard deviation of U.S. postal ZIP codes are not very meaningful or appropriate. Proper handling of categorical variables will be addressed in subsequent chapters. Also, it is useful to consider these attribute types during the following discussion on R data types.

Numeric, Character, and Logical Data Types

Like other programming languages, R supports the use of numeric, character, and logical (Boolean) values. Examples of such variables are given in the following R code.

i <- 1

sport <- "football" flag <- TRUE

# create a numeric variable # create a character variable # create a logical variable

R provides several functions, such as class () and type of (),to examine the characteristics of a given variable. The class () function represents the abstract class of an object. The typeof () func- tion determines the way an object is stored in memory. Although i appears to be an integer, i is internally stored using double precision. To improve the readability of the code segments in this section, the inline R comments are used to explain the code or to provide the returned values.

class(i) # returns "numeric" typeof(i) # returns "double"

class(sport) # returns "character" typeof(sport) # returns "character"

class(flag) .. returns "logical" tt typeof (flag) # returns "logical"

Additional R functions exist that can test the variables and coerce a variable into a specific type. The following R code illustrates how to test if i is an integer using the is . integer ( } function and to coerce i into a new integer variable, j, using the as. integer () function. Similar functions can be applied for double, character, and logical types.

is.integer(i) j <- as.integer(i) is.integer(j)

# returns FALSE # coerces contents of i into an integer # returns TRUE

The application of the length () function reveals that the created variables each have a length of 1. One might have expected the returned length of sport to have been 8 for each of the characters in the string 11 football". However, these three variables are actually one element, vectors.

length{i) length(flag) length(sport)

# returns 1 # returns 1 # returns 1 (not 8 for "football")

3.1 Introduction to R

Vectors

Vectors are a basic building block for data in R. As seen previously, simple R variables are actually vectors. A vector can only consist of values in the same class. The tests for vectors can be conducted using the is. vector () function.

is.vector(i) is.vector(flag) is.vector(sport)

!t returns TRUE # returns TRUE ±t returns TRUE

R provides functionality that enables the easy creation and manipulation of vectors. The following R code illustrates how a vector can be created using the combine function, c () or the colon operator, :, to build a vector from the sequence of integers from 1 to 5. Furthermore, the code shows how the values of an existing vector can be easily modified or accessed. The code, related to the z vector, indicates how logical comparisons can be built to extract certain elements of a given vector.

u <- c("red", "yellow", "blue") " create a vector "red" "yello•d" "blue" u u[l] v <- 1:5 v

sum(v) w <- v * 2 w

w[3]

±; t·eturns "red" "yellow'' "blue" returns "red" 1st element in u)

# create a vector 1 2 3 4 5 # returns 1 2 3 4 5 It returns 15 It create a vector 2 4 6 8 10

# returns 2 4 6 8 10 returns 6 (the 3rd element of w)

z <- v + w z

# sums two vectors element by element # returns 6 9 12 15

z > 8 z [z > 8]

# returns FALSE FALSE TRUE TRUE TRUE # returns 9 12 15

z[z > 8 I z < 5] returns 9 12 15 ("!"denotes "or")

Sometimes it is necessary to initialize a vector of a specific length and then populate the content of the vector later. The vector ( } function, by default, creates a logical vector. A vector of a different type can be specified by using the mode parameter. The vector c, an integer vector of length 0, may be useful when the number of elements is not initially known and the new elements will later be added to the end ofthe vector as the values become available.

a <- vector(length=3) # create a logical vector of length 3 a # returns FALSE FALSE FALSE b <- vector(mode::"numeric 11 , 3) #create a numeric vector of length 3 typeof(b) # returns "double" b[2] <- 3.1 #assign 3.1 to the 2nd element b # returns 0.0 3.1 0.0 c <- vector(mode= 11 integer", 0) # create an integer vectot· of length o c # returns integer(O) length(c) # returns o

Although vectors may appear to be analogous to arrays of one dimension, they are technically dimen- sionless, as seen in the following R code. The concept of arrays and matrices is addressed in the following discussion.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

1·eturns 3 length(b) dim(b) ~ 1·etun1s NULL (an undefined value)

Arrays and Matrices

The array () function can be used to restructure a vector as an array. For example, the following R code builds a three-dimensional array to hold the quarterly sales for three regions over a two-year period and then assign the sales amount of $158,000 to the second region for the first quarter of the first year.

H the dimensions are 3 regions , 4 quarters, and 2 years quarterly_sales < - array(O, dim=c(3,4,2)) quarterly_sales[2,1,11 <- 158000 quarterly_sales

1

[. 1, [.:! 1 :. , 1 [,·s!

[1' 1 0 0 0 [:!,1 !58000 c 0 0 [ 3. 1 0 0 0 0

2

[. 11 (.21 [. 31 [. 41

[ 1' 1 0 0 0 0

[2 ' 1 0 0 0 0

[3 ' 1 0 0 0 0

A two-dimensional array is known as a matrix. The following code initializes a matrix to hold the quar- terly sales for the three regions. The parameters nrov1 and ncol define the number of rows and columns, respectively, for the sal es_ma trix.

sales_matrix <- matrix(O, nrow = 3, neal 4) sales_matrix

[ 1, 1 [2,1 [ 1' 1

[.11 ;,:!) 1.31 [. .; 1 0

0

0

0

0

0

0

0 n

R provides the standard matrix operations such as addition, subtraction, and multiplication, as well as the transpose function t () and the inverse matrix function ma t r ix . inver s e () included in the matrixcalc package. The following R code builds a 3 x 3 matrix, M, and multiplies it by its inverse to obtain the identity matrix.

library(matrixcalc) M <- matrix(c(1,3,3,5,0,4,3 , 3,3) ,nrow 3,ncol 3) build a 3x3 matrix

3.1 Introduction toR

M %*% matrix . inverse (M} ~ multiply 1·! by inverse (:01 }

[. 1] [. 2] [ ' 3]

[ 1' J 0 0

[2' J 0 1 0

[3' J 0 0 1

Data Frames

Simi lar to the concept of matrices, data frames provide a structure for storing and accessing several variables

of possibly different data types. In fact, as the i s . data . fra me () function indicates, a data frame was created by the r ead . csv () function at the beginning of the chapter.

r.import a CSV :ile of the total annual sales :or each customer sales < - read .csv ("c : / data/ yearly_s a l es .c sv" ) i s .dat a . f r ame (sales ) ~ t·eturns TRUE

As seen earlier, the variables stored in the data frame can be easily accessed using the $ notation. The

following R code illustrates that in this example, each variable is a vector with the exception of gende r , which was, by a read . csv () default, imported as a factor. Discussed in detail later in this section, a factor denotes a categorical variable, typically with a few finite levels such as "F" and "M" in the case of gender.

l ength(sal es$num_of _or ders) returns 10000 (number of customers)

i s . vector(sales$cust id) returns TRUE - is .vector(sales$sales_total) returns TRUE i s .vector(sales$num_of_orders ) returns TRUE is .vector (sales$gender) returns FALSE

is . factor(sa les$gender ) ~ returns TRUE

Because of their flexibility to handle many data types, data frames are the preferred input format for

many ofthe modeling functions available in R. The following use of the s t r () function provides the structure of the sales data frame. This function identifi es the integer and numeric (double) data types, the factor variables and levels, as well as the first few values for each variable.

str (sal es) # display structure of the data frame object

'data.ft·ame': 10000 obs . of 4 vanables : $ CUSt id int 100001 100002 100003 100004 100005 100006 . .. $ sales total num 800 . 6 217.5 74.6 498 . 6 723 . 1 $ num of orders : int 3 3 2 3 4 2 2 2 2 2 . .. - $ gender Factor w/ 2 le,·els UfU I "f'-1" : 1 l 2 2 1 1 2 2 1 2 .. .

In the simplest sense, data frames are lists of variables of the same length. A subset of the data frame

can be retrieved through subsetting operators. R's subsetting operators are powerful in that they allow

one to express complex operations in a succinct fashion and easily retrieve a subset of the dataset.

'! extract the fourth column of the sales data frame sal es [, 4] H extract the gender column of the sales data frame

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

sales$gender # retrieve the first two rows of the data frame

sales[l:2,] # retrieve the first, third, and fourth columns

sales[,c(l,3,4)] l! retrieve both the cust_id and the sales_total columns

sales[,c("cust_id", "sales_total")] # retrieve all the records whose gender is female

sales[sales$gender=="F",]

The following R code shows that the class of the sales variable is a data frame. However, the type of the sales variable is a list. A list is a collection of objects that can be of various types, including other lists.

class(sales) "data. frame" typeof(sales) "list"

Lists Lists can contain any type of objects, including other lists. Using the vector v and the matrix M created in earlier examples, the following R code creates assortment, a list of different object types.

# build an assorted list of a string, a numeric, a list, a vector,

# and a matrix

housing<- list("own", "rent") assortment <- list("football", 7.5, housing, v, M) assortment

[ [1)]

[1) "football"

[ (2])

[1) 7. 5

[ (3])

[ [ 3)) [ [ 1))

[1) "own"

[ [3)) [ [2)]

[1) "rent"

[ [4)]

[1] 1 2 3 4 5

[ [5)]

[11 J

[21 J

[3 1 J

[I 1] [ 1 2] [ 1 3 J

1

3

3

5

0

4

3.1 Introduction toR

In displaying the contents of assortment, the use of the double brackets, [ [] ] , is of particular importance. As the following R code illustrates, the use of the single set of brackets only accesses an item in the list, not its content.

# examine the fifth object, loll in the list class(assortment[S]) .. returns "2.ist" tt length(assortment[S]) .. returns 1 tt class(assortment[[S]]) # returns "matrix" length(assortment[[S]]) # returns 9 {for the 3x3 matrix)

As presented earlier in the data frame discussion, the s tr ( ) function offers details about the structure of a list.

str(assortment) List of 5

$ : chr "football" $ : num 705 $ :List of 2

0 0 $ : chr "own " 0 0$ : chr "rent"

$ int [ 1: 5] 1 2 3 4 5 $ : num [ 1: 3 1 1 : 3] 1 3 3 5 0 4 3 3 3

Factors

Factors were briefly introduced during the discussion of the gender variable in the data frame sales. In this case, gender could assume one of two levels: ForM. Factors can be ordered or not ordered. In the case of gender, the levels are not ordered.

class(sales$gender) is.ordered(sales$gender)

# returns "factor" # returns FALSE

Included with the ggplot2 package, the diamonds data frame contains three ordered factors. Examining the cut factor, there are five levels in order of improving cut: Fair, Good, Very Good, Premium, and Ideal. Thus, sales$gender contains nominal data, and diamonds$cut contains ordinal data.

head(sales$gender)

F F l-1 1'-1 F F

Levels: F l\1

library(ggplot2) data(diamonds)

# display first six values and the levels

# load the data frame into the R workspace

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

str(diamonds) 'data.frame': 53940 obs. of 10 variables:

$ carat

$ cut

$ color

$ clarity:

$ depth

$ table

$ price

$ X

$ y

$ z

num 0.23 0.21 0.23 0.29 0.31 0.24 0.24 0.26 0.22 ...

Ord.factor w/ 5 levels "Fair"c"Good"c .. : 5 4 2 4 2 3 ...

Ord.factor w/ 7 levels "D"c"E"c"F"c"G"c .. : 2 2 2 6 7 7

Ord.factor w/ 8 levels "I1"c"SI2"c"SI1"< .. : 2 3 5 4 2

num 61.5 59.8 56.9 62.4 63.3 62.8 62.3 61.9 65.1 59.4

num 55 61 65 58 58 57 57 55 61 61 ...

int 326 326 327 334 335 336 336 337 337 338

num 3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...

num 3.98 3.84 4.07 4.23 4.35 3.96 3.98 4.11 3.78 4.05

num 2.43 2.31 2.31 2.63 2.75 2.48 2.47 2.53 2.49 2.39

head(diamonds$cut) # display first six values and the levels Ideal Premium Good Premium Good Very Good

Levels: Fair c Good c Very Good < Premium < Ideal

Suppose it is decided to categorize sales$sales_ totals into three groups-small, medium, and big-according to the amount of the sales with the following code. These groupings are the basis for the new ordinal factor, spender, with levels {small, medium, big}.

# build an empty character vector of the same length as sales sales_group <- vector (mode=''character",

length=length(sales$sales_total))

# group the customers according to the sales amount

sales_group[sales$sales_total<100] <- "small" sales_group[sales$sales_total>=100 & sales$sales_total<500] <- "medium" sales_group[sales$sales_total>=500] <- "big"

# create and add the ordered factor to the sales data frame spender<- factor(sales_group,levels=c("small", "medium", "big"),

ordered = TRUE) sales <- cbind(sales,spender)

str(sales$spender) Ord.factor w/ 3 levels "small"c"medium"c .. : 3 2 1 2 3 1 1 1 2 1 ...

head(sales$spender) big medium small medium big small

Levels: small < medium c big

The cbind () function is used to combine variables column-wise. The rbind () function is used to combine datasets row-wise. The use of factors is important in several R statistical modeling functions, such as analysis of variance, aov ( ) , presented later in this chapter, and the use of contingency tables, discussed next.

3.11ntrodudion toR

Contingency Tables

In R, table refers to a class of objects used to store the observed counts across the factors for a given dataset. Such a table is commonly referred to as a contingency table and is the basis for performing a statistical test on the independence of the factors used to build the table. The following R code builds a contingency table based on the sales$gender and sales$ spender factors.

# build a contingency table based on the gender and spender factors sales_table <- table{sales$gender,sales$spender)

sales_table small medium big

F 1726 2746 563

M 1656 2723 586

class(sales_table) typeof(sales_table) dim{sales_table)

# performs a chi-squared test

summary(sales_table) Number of cases in table: 10000 Number of factors: 2

returns "table"

returns "integer" # returns 2 3

Test for independence of all factors: Chisq = 1.516, df = 2, p-value = 0.4686

Based on the observed counts in the table, the summary {) function performs a chi-squared test on the independence of the two factors. Because the reported p-value is greater than 0.05, the assumed independence of the two factors is not rejected. Hypothesis testing and p-values are covered in more detail later in this chapter. Next, applying descriptive statistics in R is examined.

3.1.4 Descriptive Statistics It has already been shown that the summary () function provides several descriptive statistics, such as the mean and median, about a variable such as the sales data frame. The results now include the counts for the three levels of the spender variable based on the earlier examples involving factors.

summary(sales) cust

·- id sales - total nurn --- of orders gende1· spender

!,lin. :100001 r~lin. 30.02 !\lin. 1.000 F:5035 small :3382

1st Qu. :102501 1st Qu.: 80.29 1st Qu.: 2.000 1<1:4965 medium:5469

!\led ian :105001 r<ledian : 151.65 1\ledian : 2.000 big : 114 9

!\lean :105001 r-lean 249.46 r'lean 2.428

3rd Qu. : 107500 3rd Qu.: 295.50 3rd Qu.: 3.000 !\lax. :110000 r~Iax. : 7 6 0 6 . 0 9 1~1ax. :22.000

The following code provides some common R functions that include descriptive statistics. In parenthe- ses, the comments describe the functions.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

:. ca.ls, assig::

x <- sales$sales_total y <- sales$num_of_orders

cor(x,yl :: returns 0.75080!5 correlatlor.)

cov(x,yl II returns 345.~111 (covarianc<?)

IQR(x) ff :retu::n~ :ns.:n (int.erquartile range) mean(x) ~ returns 249.4';'i7 mean) ,. median(x) returns 151.65 (me:lianl

range (x ) " te:urns 30.0::: 7 06 . 09 min rna:-:) sd(x) ., returns '-l9.0508 ::;:... :1. :ie·:.

var(x) retur::s ~C17r.l.~ ··ari:'l!!~"",...

The IQR () function provides the difference between the third and the first quarti les. The other func-

tions are fairly self-explanatory by their names. The reader is encouraged to review the available help files

for acceptable inputs and possible options.

The function apply () is useful when the same function is to be applied to several variables in a data frame. For example, the following R code calculates the standard deviation for the first three variables in

sales. In the code, setting MARGIN=2 specifies that the sd () function is applied over the columns.

Other functions, such as lappl y () and sappl y (), apply a function to a list or vector. Readers can refer

to the R help files to learn how to use these functions.

apply (sales[,c (l : 3) ], MARGIN=2, FUN=Sd)

Additional descriptive statistics can be applied wi th user-defined funct ions. The following R code

defines a function, my_ range () , to compute the difference between the maximum and minimum va lues returned by the range () function. In general, user-defined functions are usefu l for any task or operation

that needs to be frequently repeated. More information on user-defined functions is available by entering

help ( 11 function 11 ) in the console.

# build a functi~n tv plvviJ~ the difterence bet~een ~ -he maxrmum and thE .:m • •. 1< my_range <- function (v) {range (v ) (2] - range (v) [1)} my_range (x )

3.2 Exploratory Data Analysis So far, this chapter has addressed importing and exporting data in R, basic data types and operations, and

generating descriptive statistics. Functions such as summary () can help analysts easily get an idea of the magnitude and range of the data, but other aspects such as linear relationships and distributions are

more difficult to see from descriptive statistics. For example, the following code shows a summary view of

a data frame data with two columns x and y. The output shows the range of x and y, but it's not clear

what the relationship may be between these two variables.

summary (data ) · ..

M1n. : 1.90481 ~·1n .

1st Qu . : -0.66321 !s• 0u Nedian : 0 . 0"'167 N•d.111 Nean 0.0-52~ 3rd Qu .: 0 . 65414 r t ,,u

3.2 Exploratory Data Analysis

y

A useful way to detect patterns and anomalies in the data is through the exploratory data analysis with

visualization. Visualization gives a succinct, holistic view of the data that may be difficult to grasp from the

numbers and summaries alone. Variables x and y of the data frame data can instead be visual ized in a scatterplot (Figure 3-5). which easily depicts the relationship between two variab les. An important facet

of the initial data exploration, visualization assesses data cleanliness and suggests potentia lly important

relationships in the data prior to the model planning and building phases.

Scatterplot of X and Y

-1·

2 0 X

FIGURE 3-5 A scatterplot can easily show if x andy share a relation

The code to generate data as well as Figure 3-5 is shown next.

x <- rno rm (SO) y <- x + rnorm(SO , mean=O , sd=O . S)

data<- as .data . f rame(cbind(x , y ) )

2

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

summary (data )

library (ggplo t 2) ggpl ot (data, aes (x=x , y=y)) +

geom_point (size=2) + ggtitle ("Scatterplo t o f X and Y" ) + theme (axis.text=element_t ext(s i ze= l 2) ,

axis. title el ement_text (si ze=l4 ) , plot.title = e l ement_t ext(si ze=20 , face ="bold" ))

Explora tory data analysis [9] is a data analysis approach to reveal the important characteristics of a dataset, mainly through visualization. This section discusses how to use some basic visualization techniques and the plotting feature in R to perform exploratory data analysis.

3.2.1 Visualization Before Analysis To illustrate the importance of visualizing data, consider Anscombe's quartet. Anscom be's quartet consists of four datasets, as shown in Figure 3-6. It was constructed by statistician Francis Anscom be [10] in 1973

to demonstrate the importance of graphs in statistical analyses.

# 1 # 2 # 3 # 4

X y X y X y X y

4 4.26 4 3 10 4 5.39 8 5 25

5 5.68 5 4 74 5 5.73 8 5.56

6 7.24 6 6 13 6 6.08 8 5.76

7 4.82 7 7.26 7 6.42 8 6.58

8 6.95 8 8.14 6.77 8 6.89

9 8.81 9 8.77 9 7. 11 8 7.04

10 8.04 10 9.14 10 7.46 8 7.7 1

11 8.33 11 9.26 11 7.81 8 7.91

12 10.84 12 9.13 12 8. 15 8 8.47

13 7.58 13 8.74 13 12.74 8 8.84

14 9.96 14 8.10 14 8.84 19 12.50

fiGURE 3-6 Anscom be's quartet

The four data sets in Anscom be's quartet have nearly identical statistical properties, as shown in Table 3-3.

TABLE 3-3 Statistical Properties of Anscombe's Quartet

Statistical Property Value

Meanof x 9

Variance of y 11

Mean ofY 7.50 (to 2 decimal points)

3.2 Exploratory Data Analysis

Variance of Y 4.12 or4.13 (to 2 decimal points)

Correla tions between x andy 0.816

Linear regression line y = 3.00 + O.SOx (to 2 decimal points)

Based on the nearly identical statistical properties across each dataset, one might conclude that these four datasets are quite similar. However, the scatterplots in Figure 3-7 tell a different story. Each dataset is

plotted as a scatterplot, and the fitted lines are the result of applying linear regression models. The estimated regression line fits Dataset 1 reasonably well. Dataset 2 is definitely nonlinear. Dataset 3 exhibits a linear trend, with one apparent outlier at x = 13. For Dataset 4, the regression line fits the dataset quite well. However, with only points at two x values, it is not possible to determine that the linearity assumption is proper.

12

• •

12

:t 5

I

I

~I •

3

• • • •

10

15

X

FIGURE 3-7 Anscom be's quartet visualized as scatterplots

• • ~:

5

• • •

10

2

~ • •

4

15

The R code for generating Figure 3-7 is shown next. It requires the R package ggplot2 [11]. which can

be installed simply by running the command install . p ackages ( "ggp lot2" ) . The anscombe

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

dataset for the plot is included in the standard R distribution. Enter data ( ) for a list of datasets included in the R base distribution. Enter data ( Da tase tName) to make a dataset available in the current workspace.

In the code that follows, variable levels is created using the gl (} function, which generates factors offour levels (1, 2, 3, and 4), each repeating 11 times. Variable myda ta is created using the with (data, expression) function, which evaluates an expression in an environment con- structed from da ta.ln this example, the data is the anscombe dataset, which includes eight attributes: xl, x2, x3, x4, yl, y2, y3, and y4. The expression part in the code creates a data frame from the anscombe dataset, and it only includes three attributes: x, y, and the group each data point belongs to (mygroup).

install.packages(''ggplot2") # not required if package has been installed

data (anscombe) anscombe

x1 x2 x3 x4

1 10 10 10 8

2 8 8 8 8

13 13 13

4 9 9

5 11 11 11

6 14 14 14 8

7 6 6 6 8

8 4 4 4 19

9 12 12 12 8

10 7 7 7 8

11 5 5 5 8

nrow(anscombe) [1] 11

It load the anscombe dataset into the current \'iOrkspace

y1 y2 y3 y4 8. O·l 9.14 7.-16 6.58

6.95 8.14 6.77 5.76

7.58 8.74 12.74 7.71

8.81 8.77 7.11 8.84

8.33 9.26 7.81 8.·±7

9. 9G 8.10 8.34 7.04

7.24 6.13 6. •J8 5.25

·l. 26 3.10 5. 3 9 12.50

10. 8•1 9.13 8.15 5.56

4.82 7.26 6.-12 7.91

5.68 4.74 5.73 6.89

It number of rows

# generates levels to indicate which group each data point belongs to levels<- gl(4, nrow(anscombe)) levels [1] 1 1 1 1 1 1 1 1 l l l 2 .; 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3

[ 34] 4 4 4 4 4 •l ·l 4 4 4 4

Levels: 1 2 3 4

# Group anscombe into a data frame mydata <- with(anscombe, data.frame(x=c(xl,x2,x3,x4), y=c(yl,y2,y3,y4),

mygroup=levels))

mydata X y mygroup

10 8.04

2 8 6.95

13 7.58

4 9 8.81

... 1 1 ... 4 4, B 'i.S6

-l3 8 7 0 l 4 44 B 6 . 89 4

A Ma~f -~atterp "tF ~siny th ruplot~ package library (ggplot2 ) therne_set (therne_bw ()) - s L rlot color :~erne

ggplot (rnydata, aes (x, y )) + geom_point (size=4 ) +

j\11 ' 1 7

geom_srnooth (rnethod="lrn ", fill=NA, fullrange=TRUE) + facet_wrap (-rnygroup)

3.2.2 Dirty Data

3.2 Exploratory Data Analysis

This section addresses how dirty data can be detected in the data exploration phase with visual izations. In general, analysts should look for anomalies, verify the data with domain knowledge, and decide the most

appropriate approach to clean the data. Consider a scenario in which a bank is conducting data analyses of its account holders to gauge customer

retention. Figure 3-8 shows the age distribution of the account holders.

0 0 -...

>.

~ ~ u

~ ~ c QJ :J 0" QJ

u: 8 -J ~

0 -'

Age

FIGURE 3-8 Age distribution of bank account holders

If the age data is in a vector called age, the graph can be created with the following R script:

hist(age, br eaks=lOO , main= "Age Distributi on of Account Holders ", xlab="Age", ylab="Frequency", col="gray" )

The figure shows that the median age of the account holders is around 40. A few accounts with account holder age less than 10 are unusual but plausible. These could be custodial accounts or college savings accounts set up by the parents of young children. These accounts should be retained for future analyses.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

However, the left side of the graph shows a huge spike of customers who are zero years old or have negative ages. This is likely to be evidence of missing data. One possible explanation is that the null age values could have been replaced by 0 or negative values during the data input. Such an occurrence may be caused by entering age in a text box that only allows numbers and does not accept empty values. Or it might be caused by transferring data among several systems that have different definitions for null values (such as NULL, NA, 0, -1, or-2). Therefore, data cleansing needs to be performed over the accounts with abnormal age values. Analysts should take a closer look at the records to decide if the missing data should be eliminated or if an appropriate age value can be determined using other available information for each of the accounts.

In R, the is . na (} function provides tests for missing values. The following example creates a vector x where the fourth value is not available (NA). The is . na ( } function returns TRUE at each NA value and FALSE otherwise.

X<- c(l, 2, 3, NA, 4) is.na(x) [1) FALSE FALSE FALSE TRUE FALSE

Some arithmetic functions, such as mean ( } , applied to data containing missing values can yield an NA result. To prevent this, set the na. rm parameter to TRUE to remove the missing value during the function's execution.

mean(x) [1) NA

mean(x, na.rm=TRUE) [1) 2. 5

The na. exclude (} function returns the object with incomplete cases removed.

DF <- data.frame(x = c(l, 2, 3), y = c(lO, 20, NA)) DF

X y

1 1 10

2 2 20

3 3 NA

DFl <- na.exclude(DF) DFl

X y

1 1 10

2 2 20

Account holders older than 100 may be due to bad data caused by typos. Another possibility is that these accounts may have been passed down to the heirs of the original account holders without being updated. In this case, one needs to further examine the data and conduct data cleansing if necessary. The dirty data could be simply removed or filtered out with an age threshold for future analyses. If removing records is not an option, the analysts can look for patterns within the data and develop a set of heuristics to attack the problem of dirty data. For example, wrong age values could be replaced with approximation based on the nearest neighbor-the record that is the most similar to the record in question based on analyzing the differences in all the other variables besides age.

3.2 Exploratory Data Analysis

Figure 3-9 presents another example of dirty data. The distribution shown here corresponds to the age of mortgages in a bank's home loan portfolio. The mortgage age is calculated by subtracting the orig ina- tion date of the loan from the current date. The vertical axis corresponds to the number of mortgages at each mortgage age.

Portfolio Distribution, Years Since Origination 0 0

"' ~ 0 0

~ 0

>-u c 0 (X)

Qj 0 ::J 0 cY <D ~ u. 0

0 ..,. 0 0

"' 0

I

0 2 6 8 10

Mortgage Age

FIGURE 3-9 Distribution of mortgage in years since origination from a bank's home loan portfolio

If the data is in a vector called mortgage, Figure 3-9 can be produced by the following R script.

hist (mortgage, breaks=lO, xlab='Mortgage Age ", col="gray•, main="Portfolio Distribution, Years Since Origination" )

Figure 3-9 shows that the loans are no more than 10 years old, and these 10-year-old loans have a

disproportionate frequency compared to the rest of the population. One possible explanation is that the 10-year-old loans do not only include loans originated 10 years ago, but also those originated earlier than that. In other words, the 10 in the x-axis actually means"<! 10. This sometimes happens when data is ported from one system to another or because the data provider decided, for some reason, not to distinguish loans that are more than 10 years old. Analysts need to study the data further and decide the most appropriate

way to perform data cleansing. Data analysts should perform sanity checks against domain knowledge and decide if the dirty data

needs to be eliminated. Consider the task to find out the probability of mortgage loan default. If the past observations suggest that most defaults occur before about the 4th year and 10-year-old mortgages

rarely default, it may be safe to eliminate the dirty data and assume that the defaulted loans are less than 10 years old. For other analyses, it may become necessary to track down the source and find out the true origination dates.

Dirty data can occur due to acts of omission.ln the sales data used at the beginning of this chapter, it was seen that the minimum number of orders was 1 and the minimum annual sales amount was $30.02.

Thus, there is a strong possibility that the provided dataset did not include the sales data on all customers, just the customers who purchased something during the past year.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

3.2.3 Visualizing a Single Variable Using visual representations of data is a hallmark of exploratory data analyses: letting the data speak to

its audience rather than imposing an interpretation on the data a priori. Sections 3.2.3 and 3.2.4 examine ways of displaying data to help explain the underlying distributions of a single variable or the relationships

of two or more variables.

R has many functions avai lable to examine a single variable. Some of these func tions are listed in

Table 3-4.

TABLE 3-4 Example Functions for Visualizing a Single Variable

Function Purpose

pl o t (data)

barplot (data )

dotchart (data )

hist (data)

plot(density (data))

s tem (data)

rug (data)

Dotchart and Barplot

Scatterplot where x is the index andy is the value; suitable for low-volume data

Barplot with vertical or horizontal bars

Cleveland dot plot [12)

Histogram

Density p lot (a continuous histogram)

Stem-and-leaf plot

Add a rug representation (1-d plot) of the data to an existing plot

Dotchart and barplot portray continuous values with labels from a discrete variable. A dotchart can be

created in R with the function dot cha rt (x , labe l= ... ) , where x is a numeric vector and l abel is a vector of categorical labels for x. A barplot can be created with the barplot (he igh t ) function, where heigh t represents a vector or matrix. Figure 3-10 shows (a) a dotchart and (b) a barplot based

on the mtcars dataset, which includes the fuel consumption and 10 aspects of automobile design and performance of 32 automobiles. This dataset comes with the standard R distribution.

The plots in Figure 3-10 can be produced with the following R code.

data (mtcars ) dotchart (mtcars$mpg,labels=row .names (mtcars ) ,cex=.7,

main= "Mi les Per Gallon (MPG ) of Car Models", xlab= "MPG" )

barplot (tabl e (mtcars$cyl ) , main="Distribu:ion of Car Cyl inder Counts", xlab= "Number of Cylinders" )

Histogram and Density Plot

Figure 3-ll(a) includes a histogram of household income. The histogram shows a clear concentration of

low household incomes on the left and the long tail of the higher incomes on the right.

Volvo U2f Uastreb Bota Ferran [)n) Ford Panttra L Lotus Europa Pot3che 91•-2 F'"1X1·9 Ponbac Frebrd ComaroZ28 AJ.ICJavtlw1 Dodge Chalenger Toyota Corona Toyota Carob Hondt CNC F,.1 128 Chrysltr ~nal L11cok1 Cont11tnt.l C.d .. c Fleotwoo4 o Utrc •54Slt Utrc 4SOSL Utrc.c.SQSE. Utrc2!0( Were 280 Wtre230 llerc 2•00 Ousttr 360 Vttant Homtt SportabOU1 Homtl' Drrve Datsun 710

Uazdo R.X' Wag Uazda RXI

10

l.llles Per Gallon (t.IPG) of Cor Models

0

0

0

0

0

0

0

0

0

15 20 2S 30

UPG

(a)

3.2 Explorat ory Dat a Analysis

Distribution of Car Cylinder counts

~

0 ~

0 ~

co

"' ....

0 D 6 8

Ntmler ol Cylinders

(b)

FIGURE 3-10 (a) Dotchart on the miles per gallon of cars and (b) Barplot on the distribution of car cylinder

counts

Histogram of Income Distribution of Income (log10 scale)

0 " .... 0 N

"' 0

"' 0

i'; 0 ?;- 00

c: "' 0 .. v; :> c: CT 0

., "' ., "' 0 0 u:

0 "' N 0 ~

N 0

0 0 0

Oe•OO 1e+05 2e+05 3e+05 4e•05 5e•05 4 0 4 5 50 55

Income N = 4000 Band\Yidlh = 0 02069

FIGURE 3·11 (a) Histogram and (b) Density plot of household income

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

Figure 3-11 (b) shows a density plot of the logarithm of household income values, which emphasizes the distribution. The income distribution is concentrated in the center portion of the graph. The code to generate the two plots in Figure 3-11 is provided next. The rug ( } function creates a one-dimensional density plot on the bottom of the graph to emphasize the distribution of the observation.

# randomly generate 4000 observations from the log normal distribution income<- rlnorm(4000, meanlog = 4, sdlog = 0.7) summary (income)

Min. 1st Qu. t.Jedian t>!ean 3rd Qu. f.!ax.

4.301 33.720 54.970 70.320 88.800 659.800

income <- lOOO*income summary (income)

Min. 1st Qu. f.!edian f.!ean 3rd Qu. 1\!ax.

4301 33720 54970 70320 88800 659800

# plot the histogram hist(income, breaks=SOO, xlab="Income", main="Histogram of Income") # density plot plot(density(loglO(income), adjust=O.S),

main="Distribution of Income (loglO scale)") # add rug to the density plot rug(loglO(income))

In the data preparation phase of the Data Analytics Lifecycle, the data range and distribution can be obtained. If the data is skewed, viewing the logarithm of the data (if it's all positive) can help detect struc- tures that might otherwise be overlooked in a graph with a regular, nonlogarithmic scale.

When preparing the data, one should look for signs of dirty data, as explained in the previous section. Examining if the data is unimodal or multi modal will give an idea of how many distinct populations with different behavior patterns might be mixed into the overall population. Many modeling techniques assume that the data follows a normal distribution. Therefore, it is important to know if the available dataset can match that assumption before applying any of those modeling techniques.

Consider a density plot of diamond prices (in USD). Figure 3-12(a) contains two density plots for pre- mium and ideal cuts of diamonds. The group of premium cuts is shown in red, and the group of ideal cuts is shown in blue. The range of diamond prices is wide-in this case ranging from around $300 to almost $20,000. Extreme values are typical of monetary data such as income, customer value, tax liabilities, and bank account sizes.

Figure 3-12(b) shows more detail of the diamond prices than Figure 3-12(a) by taking the logarithm. The two humps in the premium cut represent two distinct groups of diamond prices: One group centers around log10 price= 2.9 (where the price is about $794), and the other centers around log10 price= 3.7 (where the price is about $5,012). The ideal cut contains three humps, centering around 2.9, 3.3, and 3.7 respectively.

The R script to generate the plots in Figure 3-12 is shown next. The diamonds dataset comes with the ggplot2 package.

library("ggplot2") data(diamonds) # load the diamonds dataset from ggplot2

# Only keep the premium and ideal cuts of diamonds

.. ' 3t '

~ o; ; '. "

It '

niceDiamonds < - diamonds [diamonds$cut=="Pr emi um" I diamonds$cut== " Idea l •, I

summary(niceDiamonds$cut )

0 0

Pr m1u 137<ll

!:! a .. . lSSl

# plot density plot of diamond prices ggplot( niceDiamonds, ae s(x=price , fill =cut) ) +

geom_density(alpha = .3, col or=NA)

# plot density plot of the loglO of diamond prices ggpl ot (niceDiamonds , aes (x=logl O(price) , f il l =cut ) ) +

geom_density (alpha = . 3, color=NA)

3.2 Exploratory Data Analysis

As an alternative to ggplot2, the lattice package provides a function ca lled densityplot () for making simple density plot s .

~ ;; c .. "

0 0

1~300 price

(a) togtO(prtce)

(b)

cut Premium

Jcsu•

FIGURE 3-12 Density plots of (a) d iamond prices and (b) the logarithm of diamond p rices

3.2.4 Examining Multiple Variables A scatterp lot (shown previously in Figure 3-1 and Figure 3-5) is a simple and w idely used visualization

for finding the relationship among multiple variables. A sca tterplot can represent data with up to five

variables using x-axis, y-axis, size, color, and shape. But usually only two to four variables are portrayed

in a scatterplot to minimize confusion. When examining a scatterplot, one needs to pay close attention

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

to the possible relationship between the variables. If the functional relationship between the variables is

somewhat pronounced, the data may roughly lie along a straight line, a parabola, or an exponential curve. If variable y is related exponentially to x, then the plot of x versus log (y) is approximately linea r. If the plot looks more like a cluster without a pattern, the corresponding variables may have a weak relationship.

The scatterplot in Figure 3-13 portrays the relationship of two variables: x and y . The red line shown on the graph is the fitted line from the linear regression. Linear regression wi ll be revisited in Chapter 6,

"Advanced Analytical Theory and Methods: Regression." Figure 3-13 shows that the regression line does not fit the data well. This is a case in which linear regression cannot model the relationship between the

variables. Alternative methods such as the l oess () function can be used to fit a nonlinear line to the data. The blue curve shown on the graph represents the LOESS curve, which fits the data better than linear regression.

0 0 N

0 .,.,

0 0

0 .,.,

0

0

0

2 4

FIGURE 3-13 Examining two variables with regression

0

0 o o 0 0 0 0

0

0

6 8 10

The R code to produce Figure 3-13 is as follows. The runi f ( 7 5, 0 , 1 0) generates 75 numbers between 0 to 10 with random deviates, and the numbers conform to the uniform distribution. The

r norm ( 7 5 , o , 2 o) generates 75 numbers that conform to the normal distribu tion, with the mean equal to 0 and the standard deviation equal to 20. The poi n ts () function is a generic function that draws a

sequence of points at the specified coordinates. Parameter type=" 1" tells the function to draw a solid line. The col parameter sets the color of the line, where 2 represents the red color and 4 represents the blue co lor.

7 numbers ben:een

x c- runif(75 , 0 , 10)

x c- sort(x)

~nd 10 ~f unifor~ distribution

y c - 200 + xA 3 - 10 * x A2 + x + rnorm(75, 0 , 20)

lr c- lm(y - x)

poly c- loess(y - x)

::a_l_ .eqL .;~l ..

L E5~

4

6

8

fit < - predict (pol y) fit a nonlinear lice

plot (x, y )

# draw the fitted li~e for the l i near regression points (x, lr$coeffic i ents [l ] + lr$coeffici ents [2 ] • x ,

type= "1 ", col = 2)

points (x, fit, type = "1" , col = 4 )

Dotchart and Barplot

3.2 Exploratory Data Analysis

Dotchart and barplot from the previous section can visualize multiple variables. Both of them use color as an additional dimension for visualizing the data.

For the same mtcars dataset, Figure 3-14 shows a dotchart that groups vehicle cyl inders at they-axis

and uses colors to distinguish different cylinders. The vehicles are sorted according to their MPG values. The code to generate Figure 3-14 is shown next.

Miles Per Gallon (MPG) of Car Models Grouped by Cylinder

Toyota Corolla 0

Fl8t 128 0 Lotus Eu ropa 0 Honda Civic 0 F1at X1-9 0 Porscl1e 914- 2 0 t.terc2400 0 Mere 230 0 Datsun 710 0 Toyota Corona 0 Volvo 142E 0

Hornet 4 Drive 0 Mazda RX4 Wag 0 Mazda RX4 0 Ferrari Dine 0 I.! ere 280 0 Valiant 0 I.! ere 280C 0

Pontiac Fire bird 0 Hornet Sportabout 0 Mere 450SL 0 Mere 450SE 0 Ford Pantera L 0 Dodge Challenger 0 AMC Javeun 0 Mere 450SLC 0 1.1aserati Bora 0 Chrysler Imperial 0 Duster 360 0 Camaro Z28 0 Lincoln Continental 0 Cadillac Fleetwood 0

I I I I

10 15 20 25 30

Miles Per Gallon

FIGURE 3-14 Dotplot to visualize multip le variables

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

;: sor- bJ' mpg cars <- mtcars[or der {mtcars$mpg ) , )

h grouping variabl e must be a factol cars$cyl < - f actor {cars$cyl )

cars$col or[car s$cyl==4) <- "red" cars$color[cars$cyl==6) < - "blue • car s$color[cars$cyl==8) < - "darkgreen •

dotchart {cars$mpg, labels=row.names{cars) , cex- . 7, groups= cars$cyl, main=" Mi les Per Gallon {MPG ) of Car Mode l s \ nGr ouped by Cylinder• , xl ab="Miles Per Gal l on•, co l or=cars$color, gcolor="bl ac k")

The barplot in Figure 3-15 visualizes the distribution of car cylinder counts and number of gears. The x-axis represents the number of cylinders, and the color represents the number of gears. The code to

generate Figure 3-15 is shown next.

~

~

CD

~ :J 0 u

<D

"" N

0

4

Distribution of Car Cylinder Counts and Gears

Number of Gears • 3 !;! 4 D 5

6

Number of Cylinders

FIGURE 3-15 Barplot to visualize multiple variables

count s <- t able {mtcars$gear , mtcars$cyl ) barpl ot (counts, main= "Di s tributi on of Car Cylinder Counts and Gears • ,

x l ab="Number of Cylinders • , ylab="Counts •, col=c ( " #OOO OFFFF" , "#0080FFFF", "#OOFFFFFF") , legend = rownames (counts ) , beside- TRUE, args. l egend = list (x= "top", title= "Number of Gears" ))

8

3.2 Exploratory Data Analysis

Box-and-Whisker Plot

Box-and-whisker plots show the distribution of a continuous variable for each value o f a discrete variable.

The box-and-whisker plot in Figure 3-16 visualizes mean household incomes as a function of region in

the United States. The first digit of the U.S. postal ("ZIP") code corresponds to a geographical region

in the United States. In Figure 3-16, each data point corresponds to the mean household income from a

particular zip code. The horizontal axis represents the first digit of a zip code, ranging from 0 to 9, where

0 corresponds to the northeast reg ion ofthe United States (such as Maine, Vermont, and Massachusetts),

and 9 corresponds to the southwest region (such as Ca lifornia and Hawaii). The vertical axis represents

the logarithm of mean household incomes. The logarithm is taken to bet ter v isualize the distr ibution

of the mean household incomes.

.., E 0 u c ;:; 0 .c '" "' ::J 0 J:

so-

iii ~ 5- • '" :::!! 0 Cl 2

Mean Household Income by Zip Code

' ' ' 2 5 6

Zlp1

FIGURE 3-16 A box-and-whisker plot of mean household income and geographical region

' 8 9

In this figure, the scatterplot is displayed beneath the box-and-whisker plot, with some jittering for the

overlap points so that each line of points widens into a strip. The "box" of the box-and-whisker shows the

range that contains the central 50% of the data, and the line inside the box is the location of the median

value. The upper and lower hinges of the boxes correspond to the first and third quartiles of the data. The

upper whisker extends from the hinge to the highest value that is within 1.5 * IQR of the hinge. The lower whisker extends from the hinge to the lowest value within 1.5 * IQR of the hinge. IQR is the inter-quartile range, as discussed in Section 3.1.4. The points outside the wh iskers can be considered possible outliers.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

j 8 c C! '0

</) 0

0 0

! :;) 8 0 </)

I <i I c IB ::!i 0 0. 0 C! .2

" 0 0

The graph shows how household income varies by reg ion. The highest median incomes are in region

0 and region 9. Region 0 is slightly higher, but the boxes for the two regions overlap enough that the dif- ference between the two regions probably is not significant. The lowest household incomes tend to be in

region 7, which includes states such as Louisiana, Arkansas, and Oklahoma. Assuming a data frame called DFcontains two columns (MeanHousehol din come and Zipl), the

following R script uses the ggplot2 1ibrary [11 ] to plot a graph that is simi lar to Figure 3-16.

library (ggplot2 ) plot the jittered scat-erplot w/ boxplot

H color -code points with z1p codes h th~ outlier . s.ze pr~vents the boxplot from p:c-•inq •h~ uutlier ggplot (data=DF, aes (x=as . factor (Zipl ) , y=loglO(MeanHouseholdincome) )) +

geom_point(aes(color=factor (Zipl )) , alpha=0 .2, positi on="j itter") + geom_boxpl ot(outlier .size=O, alpha=O . l ) + guides(colour=FALSE) + ggtitle ("Mean Hous ehold Income by Zip Code")

Alternatively, one can create a simple box-and-whisker plot with the boxplot () function provided

by the R base package.

Hexbinplot for Large Data sets

This chapter has shown that scat terplot as a popular visualization can visualize data containing one or more variables. But one should be careful about using it on high-volume data. lf there is too much data, the

structure of the data may become difficult to see in a scatterplot. Consider a case to compare the logarithm of household income against the years of education, as shown in Figure 3-17. The cluster in the scatterplot on the left (a) suggests a somewhat linear relationship of the two variables. However, one cannot rea lly see

the structure of how the data is distributed inside the cluster. This is a Big Data type of problem. Millions or billions of data points would require different approaches for exploration, visualization, and analysis.

g] Counts 71&8 6328

I ··- SS22 4771

0 407S 0 " 34 8 ~ 1&15 0 f u .J

316

0 1640 1418 a

~ 1051

0 739

r 432 .... 279 132 39

0 1 10 ..

5 10 15 ~'•W~.Eduauon

MeanEduca1ion

(a) (b)

FIGURE 3-17 (a) Scatterplot and (b) Hexbinplot of household income against years of education

3.2 Exploratory Data Analysis

Although color and transparency can be used in a scatterplot to address this issue, a hexbinplot is sometimes a better alternative. A hexbinplot combines the ideas of scatterplot and histogram. Similar to a scatterplot, a hexbinplot visualizes data in the x-axis andy-axis. Data is placed into hex bins, and the third dimension uses shading to represent the concentration of data in each hexbin.

In Figure 3-17(b), the same data is plotted using a hexbinplot. The hexbinplot shows that the data is more densely clustered in a streak that runs through the center of the cluster, roughly along the regression line. The biggest concentration is around 12 years of education, extending to about 15 years.

In Figure 3-17, note the outlier data at MeanEducation=O. These data points may correspond to some missing data that needs further cleansing.

Assuming the two variables MeanHouseholdincome and MeanEduca tion are from a data frame named zeta, the scatterplot of Figure 3-17(a) is plotted by the following R code.

# plot the data points plot(loglO(MeanHouseholdincome) - MeanEducation, data=zcta) # add a straight fitted line of the linear regression abline(lm(loglO(MeanHouseholdincome) - MeanEducation, data=zcta), col='red')

Using the zeta data frame, the hexbinplot of Figure 3-17(b) is plotted by the following R code. Running the code requires the use of the hexbin package, which can be installed by running ins tall .packages ( "hexbin").

library(hexbin) # "g" adds the grid, "r" adds the regression line # sqrt transform on the count gives more dynamic range to the shading # inv provides the inverse transformation function of trans hexbinplot(loglO(MeanHouseholdincome) - MeanEducation,

data=zcta, trans= sqrt, inv = function(x) x ... 2, type=c( 11 g 11 , 11 r 11 ))

Scatterplot Matrix

A scatterplot matrix shows many scatterplots in a compact, side-by-side fashion. The scatterplot matrix, therefore, can visually represent multiple attributes of a dataset to explore their relationships, magnify differences, and disclose hidden patterns.

Fisher's iris dataset [13] includes the measurements in centimeters ofthe sepal length, sepal width, petal length, and petal width for 50 flowers from three species of iris. The three species are setosa, versicolor, and virginica. The iris dataset comes with the standard R distribution.

In Figure 3-18, all the variables of Fisher's iris dataset (sepal length, sepal width, petal length, and petal width) are compared in a scatterplot matrix. The three different colors represent three species of iris flowers. The scatterplot matrix in Figure 3-18 allows its viewers to compare the differences across the iris species for any pairs of attributes.

REVIEW O F BA SIC DATA ANA LYTIC M ETHODS USING R

Q .., 0

"'

"' Q

Sepal. length

.. ;~·: .. • • " . • ··~til!~-= ,. . . . . . .,

~ .. ·.t.* •.

H 55 65 7 5

Fisher's Iris Dataset

20 25 30 35 •o

••• I

~-t' ...... .. ;.;.:.·· • • •• •

Sepal. Width

• • • - ~·

• =:t • • .

... .. ~· .....

Petal. length

12 3<567

• setosa D verstcolor • virgimca FIGURE 3·18 Scatterplot matrix of Fisher's {13] iris dataset

0510152025

..... ..... f·

w.4"t~ ,. .• . "' .... "' .. "' 0&<4 "'

14 11

'" 10>1 '19 "' ~ .. 11t

I ll

f.· .. . ~-· ... . . . _ic

)9 I

Petal. Width

Consider the scatterplot from the first row and third column of Figure 3-18, where sepal length is com-

pared against petal length. The horizontal axis is the petal length, and the vertical axis is the sepal length. The scatterplot shows that versicolor and virginica share similar sepal and petal lengths, although the latter has longer petals. The petal lengths of all setosa are about the same, and the petal lengths are remarkably

shorter than the other two species. The scatterplot shows that for versicolor and virgin ica, sepal length grows linearly with the petal length.

The R code for generating the scatterplot matrix is provided next.

I; define the colors colors<- C( 11 red 11 J 11 green 11 , 11 blue•')

~ draw the plot ma:rix pairs(iris[l : 4], main= "Fisher ' s Iris Dataset•,

pch = 21, bg = colors[unclass (iris$Species)]

= ~Qr qrdp~ica: pa~a~ :e~· - cl~!' p!ot - 1~9 :c :te ~1gure ~~a1o~ par (xpd = TRUE)

" ada l<"go::d legend (0.2, 0 .02, horiz = TRUE, as.vector (unique (iris$Species )) ,

fil l = colors, bty = "n" )

3.2 Exploratory Data Analysis

The vector colors defines the color scheme for the plot. It could be changed to something like colors<- c("gray50", "white" , "black" } to makethescatterplotsgrayscale.

Analyzing a Variable over Time

Visua lizing a variable over time is the same as visualizing any pair of variables, but in this case the goal is to identify time-specific patterns.

Figure 3-19 plots the monthly total numbers of international airline passengers (in thousands) from

January 1940 to December 1960. Enter plot (AirPassengers} in the R console to obtain a similar graph. The plot shows that, for each year, a large peak occurs mid-year around July and August, and a small

peak happens around the end of the year, possibly due to the holidays. Such a phenomenon is referred to as a seasonality effect.

0 0 CD

0 0 II'>

"' Q; 0 0>

c 0 ., .... "' "' "' 0 Q, 0 < (")

0 0 N

0

~

1950 1952 1954 1956 1958 1960

Tune

FIGURE 3-19 Airline passenger counts from 1949 to 1960

Additionally, the overall trend is that the number of air passengers steadily increased from 1949 to

1960. Chapter 8, "Advanced Analytica l Theory and Methods: Time Series Analysis," discusses the analysis of such data sets in greater detail.

3.2.5 Data Exploration Versus Presentation Using visualization for data exploration is different from presenting results to stakeholders. Not every type of plot is suitable for all audiences. Most of the plots presented earlier try to detail the data as clearly as pos- sible for data scientists to identify structures and relationships. These graphs are more technical in nature

and are better suited to technical audiences such as data scientists. Nontechnical stakeholders, however, generally prefer simple, clear graphics that focus on the message rather than the data.

Figure 3-20 shows the density plot on the distribution of account va lues from a bank. The data has been converted to the log10 scale. The plot includes a rug on the bottom to show the distribution of the variable. This graph is more suitable for data scientists and business analysts because it provides information that

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

can be relevant to the downstream analysis. The graph shows that the transformed account values follow an approximate normal distribution, in the range from $100 to $10,000,000. The median account value is approximately $30,000 (1 o4s), with the majority of the accounts between $1,000 (1 03) and $1,000,000 (1 06).

Distribution of Account Values (log10 scale)

CD ci

II)

ci

oq: 0

~ ("') ·a;

c c::) cu 0

N c::)

..... c::)

0 c::)

2 3 4 5

N = 5000 Bandwidth= 0.05759

FIGURE 3-20 Density plots are better to show to data scientists

6 7

Density plots are fairly technical, and they contain so much information that they would be difficult to explain to less technical stakeholders. For example, it would be challenging to explain why the account values are in the log10 scale, and such information is not relevant to stakeholders. The same message can be conveyed by partitioning the data into log-like bins and presenting it as a histogram. As can be seen in Figure 3-21, the bulk of the accounts are in the S 1,000-1,000,000 range, with the peak concentration in the $10-SOK range, extending to $500K. This portrayal gives the stakeholders a better sense of the customer base than the density plot shown in Figure 3-20.

Note that the bin sizes should be carefully chosen to avoid distortion of the data.ln this example, the bins in Figure 3-21 are chosen based on observations from the density plot in Figure 3-20. Without the density plot, the peak concentration might be just due to the somewhat arbitrary appearing choices for the bin sizes.

This simple example addresses the different needs of two groups of audience: analysts and stakehold- ers. Chapter 12, "The Endgame, or Putting It All Together," further discusses the best practices of delivering presentations to these two groups.

Following is the R code to generate the plots in Figure 3-20 and Figure 3-21.

# Generate random log normal income data income= rlnorm(SOOO, meanlog=log(40000), sdlog=log(S))

# Part I: Create the density plot plot(density(loglO(income), adjust=O.S),

main= 11 Distribution of Account Values (loglO scale)") # Add rug to the density plot

3.3 Statistical Methods for Evaluation

r ug (logl O(income))

l• :l... "1 ! .... < bl:-;.5''

breaks = c(O, 1000, 5000, 10000, 50000, 100000, SeS, le6, 2e7 ) "'! 1.:: .... ... ••' ,

bins = cut(income, breaks, include .lowest=T, labels c ( "< lK", "1 - SK", "5- lOK" , "10 - SOK",

"50-lOOK" , "100 -SOOK" , "SOCK-1M", "> 1M") ) ~ n r •L ri. .. plot(bins, main "Distribut i on of Account Val ues ",

xl ab "Account value ($ USD) ", ylab = "Number of Accounts", col= "blue ")

Distribution of Account Values

0 - --<1K 1-5K 5-I OK 10-50K 50- l OOK 100.500K 500K-1M > 11.1 AccOirl value (S USO)

FIGURE 3·21 Histograms are better to show to stakeholders

3.3 Statistical Methods for Evaluation Visualization is useful for data exploration and presentation, but statistics is crucial because it may exist throughout the entire Data Analytics Lifecycle. Statistical techniques are used during the initial data explo- ration and data preparation, model building, evaluation of the final models, and assessment of how the new models improve the situation when deployed in the field. In particular, statistics can help answer the

following questions for data analytics:

• Model Building and Planning

• What are the best input variables for the model?

• Can the model predict the outcome given the input?

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

• Model Evaluation

• Is the model accurate?

• Does the model perform better than an obvious guess?

• Does the model perform better than another candidate model?

• Model Deployment

• Is the prediction sound?

• Does the model have the desired effect (such as reducing the cost}?

This sec tion discusses some useful statistical tools that may answer these questions.

3.3.1 Hypothesis Testing When comparing populations, such as testing or evaluating the difference of the means from two samples

of data (Figure 3-22}, a common technique to assess the difference or the significance of the difference is hypothesis testing.

FIGURE 3-22 Distributions of two samples of data

The basic concept of hypothesis testing is to form an assertion and test it with data. When perform- ing hypothesis tests, the common assumption is that there is no difference between two samples. This

assumption is used as the default position for building the test or conducting a scientific experiment. Statisticians refer to this as the null hypothesis (H

0 ). The alternative hypothesis (H) is that there is a

3.3 Statistical Methods for Evaluation

difference between two samples. For example, if the task is to identify the effect of drug A compared to drug Bon patients, the null hypothesis and alternative hypothesis would be th is.

• fl0: Drug A and drug B have the same effect on patients.

• fl A: Drug A has a greater effect than drug Bon patients.

If the task is to identify whether advertising Campaign C is effective on reducing customer churn, the

null hypothesis and alternative hypothesis would be as follows.

• fl0: Campaign C does not reduce customer churn better than the cu rrent campaign method.

• flA: Campaign C does reduce customer churn better than the current campaign.

It is important to state the null hypothesis and alternative hypothesis, because misstating them is likely to undermine the subsequent steps of the hypothesis testing process. A hypothesis test leads to either

rejecting the null hypothesis in favor of the alternative or not rejecting the null hypothesis.

Table 3·5 includes some examples of null and alternative hypotheses that should be answered during the analytic lifecycle.

TABLE 3-5 Example Null Hypotheses and Alternative Hypotheses

Application Null Hypothesis Alternative Hypothesis

Accuracy Forecast

Recommendation Engine

Regression Modeling

Model X does not predict better than the existing model.

Algorithm Y does not produce better recommendations than the current algorithm being used.

This variable does not affect the outcome because its coefficient is zero.

Model X predicts better than the existing model.

Algorithm Y produces better recommen· dations than the current algorithm being used.

This variable affects outcome because its coefficient is not zero.

Once a model is built over the t raining data, it needs to be evaluated over the testing data to see if the proposed model predicts better than the existing model curren tly being used. The null hypothesis is that

the proposed model does not predict better than the existing model. The alternative hypothesis is that the proposed model indeed predicts better than the existing model. In accuracy forecast, the null model could be that the sales of the next month are the same as the prior month. The hypothesis test needs to evaluate if the proposed model provides a better prediction. Take a recommendation engine as an example. The null hypothesis could be that the new algorithm does not produce better recommendations than the current algorithm being deployed. The alternative hypothesis is that the new algorithm produces better recommendations than the old algorithm.

When evaluating a model, sometimes it needs to be determined if a given input variable improves the model. In regression analysis (Chapter 6), for example, this is the same as asking if the regression coefficient for a variable is zero. The null hypothesis is that the coefficient is zero, which means the variable does not have an impact on the outcome. The alternative hypothesis is that the coefficient is nonzero, which means the variable does have an impact on the outcome.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

A common hypothesis test is to compare the means of two populations. Two such hypothesis tests are

discussed in Section 3.3.2.

3.3.2 Difference of Means Hypothesis testing is a common approach to draw inferences on whether or not the two populations, denoted pop1 and pop2, are different from each other. This section provides two hypothesis tests to com- pare the means of the respective populations based on samples randomly drawn from each population.

Specifically, the two hypothesis tests in this section consider the following null and alternative hypotheses.

• Ho: II , = ll2

• HA: II , ""' ll2

The 1', and 112 denote the population means of pop1 and pop2, respectively. The basic testing approach is to compare the observed sample means, X, and X2, corresponding to each

population. If the values of X 1 and X

2 are approximately equal to each other, the distributions of X, and

X2 overlap substantially (Figure 3-23), and the null hypothesis is supported. A large observed difference between the sample means indicates that the null hypothesis should be rejected. Formally, the difference in means can be tested using Student's t-test or the Welch's t-test.

Irx, '" :X2 . this area is

large

FIGURE 3-23 Overlap of the two distributions is large if X1 ::::: X2

Student's t-test

Student 's t- test assumes that distributions of the two populations have equal but unknown variances. Suppose n

1 and n2 samples are randomly and independently selected from two populations,

pop1 and pop2, respectively. If each population is normally distributed with the same mean (Jt 1 = Jt

2 ) and

wi th the same variance, then T (the t-statistic ), given in Equation 3-1, follows a t -distribution with n, + n2 - 2 degrees of freedom (df).

where (3-1)

3.3 Statistical Methods for Evaluation

The shape of the t-distribution is similar to the normal distribution. In fact, as the degrees of freedom approaches 30 or more, the t-distribution is nearly identical to the normal distribution. Because the numera- tor ofT is the difference of the sample means, if the observed value ofT is far enough from zero such that the probability of observing such a value of Tis unlikely, one would reject the null hypothesis that the population means are equal. Thus, for a small probability, say a= 0.05, T* is determined such that P(ITI2: T*) = 0.05. After the samples are collected and the observed value ofT is calculated according to Equation 3-1, the null hypothesis (p,1 = p2) is rejected ifiTI2: r·.

In hypothesis testing, in general, the small probability, n, is known as the significance level of the test. The significance level of the test is the probability of rejecting the null hypothesis, when the null hypothesis is actually TRUE.In other words, for n = 0.05, if the means from the two populations are truly equal, then in repeated random sampling, the observed magnitude ofT would only exceed r· 5% of the time.

In the following R code example, 10 observations are randomly selected from two normally distributed populations and assigned to the variables x andy. The two populations have a mean of 100 and 105, respectively, and a standard deviation equal to 5. Student's t-test is then conducted to determine if the obtained random samples support the rejection of the null hypothesis.

# generate random observations from the two populations

x <- rnorm(lO, mean=lOO, sd=S) # normal distribution centered at 100 y <- rnorm(20, mean=lOS, sd=S) ll no~:mal distribution centered at 105

t.test(x, y, var.equal=TRUE) Two Sample t-test

data: x and y

# run the Student's t-test

t = -1.7828, df = 28, p-value = 0.08547 alternative hypothesis: true difference in means is not equal to 0

95 percent confidence interval: -6.1611557 0.4271393

sample estimates: mean of x mean of y

102.2136 105.0806

From the R output, the observed value of Tis t = -1.7828. The negative sign is due to the fact that the sample mean of xis less than the sample mean of y. Using the qt () function in R, a Tvalue of 2.0484 corresponds to a 0.05 significance level.

# obtain t value for a two-sidec test at a 0.05 significance level

qt(p=O.OS/2, df=28, lower.tail= FALSE) 2.048407

Because the magnitude of the observed T statistic is less than the T value corresponding to the 0.05 significance level Q -1.78281< 2.0484), the null hypothesis is not rejected. Because the alternative hypothesis is that the means are not equal (p

1 :;z:: 11

2 ), the possibilities of both p, > 112 and p 1 < 112 need to be considered.

This form of Student's t-test is known as a two-sided hypothesis test, and it is necessary for the sum of the probabilities under both tails of the t-distribution to equal the significance level. It is customary to evenly

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

divide the significance level between both tails. So, p = 0.05/2 = 0.025 was used in the qt () function to obtain the appropriate t-value.

To simplify the comparison of the t-test results to the significance level, the R output includes a quantity known as the p -value. ln the preceding example, the p-value is 0.08547, which is the sum of P(T ~ - 1.7828) and P(T ~ 1.7828). Figure 3-24 illustrates the t-statistic for the area under the tail of a t-distribution. The -t

and tare the observed values of the t-statistic. ln the R output, t = 1.7828. The left shaded area corresponds to the P(T ~ - 1.7828), and the right shaded area corresponds to the P(T ~ 1.7828).

-t 0

FIGURE 3-24 Area under the tails (shaded) of a student's t-distribution

In the R output, for a significance level of 0.05, the null hypothesis would not be rejected because the likelihood of a Tvalue of magnitude 1.7828 or greater would occur at higher probability than 0.05. However,

based on the p -value, if the significance level was chosen to be 0.10, instead of 0.05, the null hypothesis would be rejected. In general, the p-value offers the probability of observing such a sample result given the null hypothesis is TRUE.

A key assumption in using Student's t-test is that the population variances are equal. In the previous example, the t . test ( ) function call includes var . equal=TRUE to specify that equality of the vari- ances should be assumed. If that assumption is not appropriate, then Welch's t-test should be used.

Welch 's t-test

When the equal population variance assumption is not justified in performing Student's t-test for the dif- ference of means, Welch's t-test [14] can be used based on T expressed in Equation 3-2.

(3-2)

where X,. 5,2, and n, correspond to the i-th sample mean, sample variance, and sample size. Notice that Welch's t-test uses the sample variance (5ll for each population instead of the pooled sample variance.

In Welch's test, under the remaining assumptions of random samples from two normal populations with the same mean, the distribution of Tis approximated by the t-distribution. The following R code performs the Welch's t-test on the same set of data analyzed in the earlier Student's t-test example.

3.3 Statistical Methods for Evaluation

t.test(x, y, var.equal=FALSE) # run the Welch's t-test

l'lelch Two Sample t-test

data: x andy

t = -1.6596, df = 15.118, p-value = 0.1176 alternative hypothesis: true difference in neans is not equal to o 95 percent confidence interval:

-6.546629 0.812663 sample estimates:

mean of x mean of y 102.2136 105.0806

In this particular example of using Welch's t-test, the p-value is 0.1176, which is greater than the p-value of 0.08547 observed in the Student's t-test example. In this case, the null hypothesis would not be rejected at a 0.10 or 0.05 significance level.

It should be noted that the degrees of freedom calculation is not as straightforward as in the Student's t-test. In fact, the degrees of freedom calculation often results in a non-integer value, as in this example. The degrees of freedom for Welch's t-test is defined in Equation 3-3.

df=l~r l~:r --+-- n,-1 n2 -1

(3-3)

In both the Student's and Welch's t-test examples, the R output provides 95% confidence intervals on the difference of the means. In both examples, the confidence intervals straddle zero. Regardless of the result of the hypothesis test, the confidence interval provides an interval estimate of the difference of the population means, not just a point estimate.

A confidence interval is an interval estimate of a population parameter or characteristic based on sample data. A confidence interval is used to indicate the uncertainty of a point estimate.lfx is the estimate of some unknown population mean f..L, the confidence interval provides an idea of how close xis to the unknown p. For example, a 95% confidence interval for a population mean straddles the TRUE, but unknown mean 95% of the time. Consider Figure 3-25 as an example. Assume the confidence level is 95%. If the task is to estimate the mean of an unknown value Jt in a normal distribution with known standard deviation u and the estimate based on n observations is x, then the interval x ± ~ straddles the unknown value of Jl with about a 95% chance. If one takes 100 different samples and computes the 95% confi- dence interval for the mean, 95 of the 100 confidence intervals will be expected to straddle the population mean Jt.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

FIGURE 3-25 A 95% confidence interval straddling the unknown population mean 1J

Confidence intervals appear again in Section 3.3.6 on AN OVA. Return ing to the discussion of hypoth-

es is testing, a key assumption in both t he Student 's and Welch 's t-test is that the relevant population

attribute is normally distributed. For non-normally dist ributed data, it is sometimes possible to transform

the co llected data to approx imate a normal distribution. For example, taking the logarithm of a dataset

can often transform skewed data to a dataset that is at least symmetric around its mean. Howeve r, if such

transformations are ineffective, there are tests like the Wi lcoxon rank-sum test that can be applied to see

if two population distributions are different.

3.3.3 Wilcoxon Rank-Sum Test At-test represents a parametric test in that it makes assumptions about the population distributions from which the samples are drawn. If the populations cannot be assumed or transformed to follow a normal

distribution, a nonparametric test can be used. The Wilcoxon rank-sum test [15] is a nonparametric

hypothesis test that checks whether two populations are identically d istributed. Assuming the two popula-

t ions are identica lly distributed, one would expect that the ordering of any sampled observations would

be evenly intermixed among themselves. For example, in ordering the observations, one would not expect

to see a large number of observations from one population grouped together, especially at the beginning

or the end of ordering.

Let the two populations again be popl and pop2, with independently random samples of size n1 and

n 2

respectively. The total number of observations is then N = n1 + n2• The first step of the Wilcoxon test is to rank the set of observations from the two groups as if they came from one large group. The smallest

observation receives a rank of 1, the second smallest observation receives a rank of 2, and so on with the

largest observation being assigned the rank of N. Ties among the observations receive a rank equal to

t he average of the ranks they span. The test uses ranks instead of numerical outcomes to avoid specific

assumptions about the shape of the distribution.

After ranking all the observations, the assigned ranks are summed for at least one population's sample.

If the distribution of popl is shifted to the right of the other distribution, the rank-sum corresponding to

popl's sample should be larger than the rank-sum of pop2. The Wilcoxon rank-sum test determines the

3.3 Statistical Methods for Evaluation

significance of the observed rank-sums. The following R code performs the test on the same dataset used for the previous t-test.

wilcox.test(x, y, conf.int TRUE)

:·:~.c :-c n r rJ.:

! 1 t

The wilcox. test ( l function ranks the observations, determines the respective rank-sums cor- responding to each population's sample, and then determines the probability of such rank-sums of such magnitude being observed assuming that the population distributions are identical. In this example, the

probability is given by the p-value of 0.04903. Thus, the null hypothesis would be rejected at a 0.05 sig- nificance level. The reader is cautioned against interpreting that one hypothesis test is clearly better than another test based solely on the examples given in this section.

Because the Wilcoxon test does not assume anything about the population distribution, it is generally considered more robust than the t-test. In other words, there are fewer assumptions to violate. However, when it is reasonable to assume that the data is normally distributed, Student's or Welch's t-test is an appropriate hypothesis test to consider.

3.3.4 Type I and Type II Errors A hypothesis test may result in two types of errors, depending on whether the test accepts or rejects the null hypothesis. These two errors are known as type I and type II errors.

• A type I error is the rejection of the null hypothesis when the null hypothesis is TRUE. The probabil- ity of the type I error is denoted by the Greek letter n.

• A type II error is the acceptance of a null hypothesis when the null hypothesis is FALSE. The prob- ability of the type II error is denoted by the Greek letter .1.

Table 3-61ists the four possible states of a hypothesis test, including the two types of errors.

TABLE 3-6 Type I and Type II Error

H 0

is true H0 is false

H0 is accepted Correct outcome Type II Error

H 0

is rejected Type/error Correct outcome

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

The significance level, as mentioned in the Student's t-test discussion, is equivalent to the type I error. For a significance level such as o = 0.05, if the null hypothesis (Jt1 = J11) is TRUE, there is a So/o chance that the observed Tvalue based on the sample data will be large enough to reject the null hypothesis. By select-

ing an appropriate sig nificance level, the probability of committing a type I error can be defined before

any data is collected or analyzed. The probability of committing a Type II error is somewhat more difficult to determine. If two population

means are truly not equal, the probability of committing a type II error will depend on how far apart the

means truly are. To reduce the probability of a type II error to a reasonable level, it is often necessary to increase the sample size. This topic is addressed in the next section.

3.3.5 Power and Sample Size The power of a test is the probability of correctly rejecting the null hypothesis. It is denoted by 1- /.3, where f] is the probability of a type II error. Because the power of a test improves as the sample size increases, power is used to determine the necessary sample size. In the difference of means, the power of a hypothesis test depends on the true difference of the population means. In other words, for a fixed significance level,

a larger sample size is required to detect a smaller difference in the means. In general, the magnitude of the difference is known as the effect size. As the sample size becomes larger, it is easier to detect a given

effect size, 6, as illustrated in Figure 3-26.

Moderate Sample Size Larger Sample Size

1------1 1------1 a' a'

FIGURE 3-26 A larger sample size better identifies a fixed effect size

With a large enough sample size, almost any effect size can appear statistically significant. However, a

very small effect size may be useless in a practical sense. It is importan t to consider an appropriate effect size for the problem at hand.

3.3.6ANOVA The hypothesis tests presented in the previous sections are good for analyzing means between two popu- lations. But what if there are more than two populations? Consider an example of testing the impact of

3.3 Statistical Methods for Evaluation

nutrition and exercise on 60 candidates between age 18 and 50. The candidates are randomly split into six groups, each assigned with a different weight loss strategy, and the goal is to determine which strategy is the most effective.

o Group 1 only eats junk food.

o Group 2 only eats healthy food.

o Group 3 eats junk food and does cardia exercise every other day.

o Group 4 eats healthy food and does cardia exercise every other day.

o Group 5 eats junk food and does both cardia and strength training every other day.

o Group 6 eats healthy food and does both cardia and strength training every other day.

Multiple t-tests could be applied to each pair of weight loss strategies. In this example, the weight loss of Group 1 is compared with the weight loss of Group 2, 3, 4, 5, or 6. Similarly, the weight loss of Group 2 is compared with that of the next 4 groups. Therefore, a total of 15 t-tests would be performed.

However, multiplet-tests may not perform well on several populations for two reasons. First, because the number oft-tests increases as the number of groups increases, analysis using the multiplet-tests becomes cognitively more difficult. Second, by doing a greater number of analyses, the probability of committing at least one type I error somewhere in the analysis greatly increases.

Analysis of Variance (ANOVA) is designed to address these issues. AN OVA is a generalization of the hypothesis testing of the difference of two population means. AN OVA tests if any of the population means differ from the other population means. The null hypothesis of A NOVA is that all the population means are equal. The alternative hypothesis is that at least one pair of the population means is not equal. In other words,

0 Ho:Jll = J12 = ··· = Jln

o H A: Jl; ::= J1i for at least one pair of i,j

As seen in Section 3.3.2, "Difference of Means," each population is assumed to be normally distributed with the same variance.

The first thing to calculate for the AN OVA is the test statistic. Essentially, the goal is to test whether the clusters formed by each population are more tightly grouped than the spread across all the populations.

Let the total number of populations be k. The total number of samples N is randomly split into the k groups. The number of samples in the i-th group is denoted as n1, and the mean of the group is X1 where iE[l,k]. The mean of all the samples is denoted as X0•

The between-groups mean sum of squares, s;, is an estimate of the between-groups variance. It measures how the population means vary with respect to the grand mean, or the mean spread across all the populations. Formally, this is presented as shown in Equation 3-4.

k

52 =-1-~n.·(x.-x )2 8 k-1L...i I I 0

1=1

(3-4)

The within-group mean sum of squares, s~. is an estimate of the within-group variance. It quantifies the spread of values within groups. Formally, this is presented as shown in Equation 3-5.

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

(3-5)

If s; is much larger than 5~, then some of the population means are different from each other. The F-test statistic is defined as the ratio of the between-groups mean sum of squares and the within-

group mean sum of squares. Formally, this is presented as shown in Equation 3-6.

(3-6)

The F-test statistic in A NOVA can be thought of as a measure of how different the means are relative to the variability within each group. The larger the observed F-test statistic, the greater the likelihood that the differences between the means are due to something other than chance alone. The F-test statistic is used to test the hypothesis that the observed effects are not due to chance-that is, if the means are significantly different from one another.

Consider an example that every customer who visits a retail website gets one of two promotional offers or gets no promotion at all. The goal is to see if making the promotional offers makes a difference. ANOVA could be used, and the null hypothesis is that neither promotion makes a difference. The code that follows randomly generates a total of 500 observations of purchase sizes on three different offer options.

offers<- sample(c("offerl", "offer2", "nopromo"), size=SOO, replace=T)

# Simulated 500 observations of purchase sizes on the 3 offer options purchasesize <- ifelse(offers=="offerl", rnorm(SOO, mean=SO, sd=30),

ifelse(offers=="offer2", rnorm(SOO, mean=SS, sd=30), rnorm(SOO, mean=40, sd=30)))

# create a data frame of offer option and purchase size offertest <- data.frame(offer=as.factor(offers),

purchase_amt=purchasesize)

The summary ofthe offertest data frame shows that 170 offerl, 161 offer2, and 169 nopromo (no promotion) offers have been made. It also shows the range of purchase size (purchase_ amt) for each of the three offer options.

# display a summary of offertest where o:fer="offer1" summary(offertest[offertest$offer=="offerl",])

offer nopromo: offe:n :170 offer2 :

purchase_amt t·li;;.. 4.521

1 s:: Qu . : 5 8 . 1 5 8

i·iedian : 76. 944 I·1ean .Sl. 936

3 rd Qu. : 1 D 4 . 9 59

t•la:·:. :130.507

# display a summary of offertest where o:fer="offer2" summary(offertest[offertest$offer=="offer2",])

offer

nopromo: 0 offer! 0

offer2 :161

purchase_amt ~lin. 14.04

1st Qu . : 6 9 . 4 6 t·ledian : 90.20 r•lean 89.09 3 rd Qu. : 10 7. 4 8 !•lax. : 154. 3 3

# display a summary of offertest where offer="nopromo"

summary(offertest[offertest$offer== 11 nopromo 11 ,]) offer

nopromo:169 offerl 0

offer2 : 0

purchase_amt Min. :-27.00

1st Qu.: 20.22 t<ledian : 42.44 f.lean 40.97

3rd Qu.: 58.96 i'olax. :164.04

3.3 Statistical Methods for Evaluation

The aov ( } function performs the AN OVA on purchase size and offer options.

# fit ANOVA test model <- aov(purchase_amt - offers, data=offertest)

The summary (} function shows a summary of the model. The degrees of freedom for offers is 2, which corresponds to the k -1 in the denominator of Equation 3-4. The degrees of freedom for residuals is 497, which corresponds to then- k in the denominator of Equation 3-5.

summary (model) Of Sum Sq !-lean Sq F value Pr (>F)

offers 2 225222 112611 130.6 <2e-16 Residuals 4 97 428470 862

Signif. codes: 0 1 *** 1 0.001 1 **' 0.01 1 * 1 0.05 '. 1 0.1 1 1 1

The output also includes the 5~ (112,611), 5~ (862), the F-test statistic (130.6), and the p-value (< 2e-16). The F-test statistic is much greater than 1 with a p-value much less than 1. Thus, the null hypothesis that the means are equal should be rejected.

However, the result does not show whether offerl is different from offer2, which requires addi- tional tests. The TukeyHSD (} function implements Tukey's Honest Significant Difference (HSD) on all pair-wise tests for difference of means.

TukeyHSD(model) Tukey multiple comparisons of means

95% family-wise confidence level

Fit: aoviformula purchase amt - offers, data

$offers diff lwr upr

offertest)

p adj offerl-nopromo 40.961437 33.4638483 48.45903 0.0000000

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

offer2 nopromo 48 . 120286 40 . 51894~6 55 . 72163 O. OOOOOCO

offer2--fferl 7 . 1"8849 -0 . 4315769 14 . 74928 o . r692895

The result includes p-values of pair-wise comparisons of the three offer options. The p-values for

of ferl- nopromo and of fer-nopromo are equal to 0, smaller than the significance level 0.05.

This suggests that both of ferl and offer2 are significantly different from nopromo. A p-value of 0.0692895 for off er2 against of fer 1 is greater than the significance level 0.05. This suggests that of fer2 is not significantly different from offerl.

Because only the influence of one factor (offers) was executed, the presented A NOVA is known as one- way ANOVA. If the goal is to analyze two factors, such as offers and day of week, that would be a two-way A NOVA [16]. 1f the goal is to model more than one outcome variable, then multivariate AN OVA (or MAN OVA)

could be used.

Summary R is a popular package and programming language for data exploration, analytics, and visualization. As an introduction toR, this chapter covers the R GUI, data 1/0, attribute and data types, and descriptive statistics.

This chapter also discusses how to useR to perform exploratory data analysis, including the discovery of dirty data, visua lization of one or more variables, and customization of visualization for different audiences.

Finally, the chapter introduces some basic statistical methods. The first statistical method presented in the chapter is the hypothesis testing. The Student's t-test and Welch's t-test are included as two example hypoth-

esis tests designed for testing the difference of means. Other statistical methods and tools presented in this chapter include confidence interva ls, Wilcoxon rank-sum test, type I and II errors, effect size, and ANOVA.

Exercises 1. How many levels does fdata contain in the following R code?

data = c(1 , 2,2,3,1,2 , 3,3 ,1 , 2,3,3 , 1)

fdata = factor(data)

2. Two vectors, vl and v2, are created with the following R code:

vl <- 1:5

v2 <- 6 : 2

What are the results of cbind (vl , v2) and rbind (vl , v2)?

3. What R command(s) would you use to remove null values from a dataset?

4. What R command can be used to install an additional R package?

5. What R function is used to encode a vector as a category?

6. What is a rug plot used for in a density plot?

7. An online retailer wants to study the purchase behaviors of its customers. Figure 3-27 shows the den- sity plot of the purchase sizes (in dol lars). What would be your recommendation to enhance the plot to detect more structures that otherwise might be missed?

Bibliography

Be-04

6e-04

£ "' ~ 4e-04

2e-04

09+(}0

0 2000 4000 6000 8000 10000 purchase size (dollars)

fiGURE 3-27 Density plot of purchase size

8. How many sections does a box-and-whisker divide the data into? What are these sections?

9. What attributes are correlated according to Figure 3-18? How would you describe their relationships?

10. What function can be used to tit a nonlinear line to the data?

11. If a graph of data is skewed and all the data is positive, what mathematical technique may be used to

help detect structures that might otherwise be overlooked?

12. What is a type I error? What is a type II error? Is one always more serious than the other? Why?

13. Suppose everyone who visits a retail website gets one promotional offer or no promotion at all. We

want to see if making a promotional offer makes a difference. What statistical method would you

recommend for this analysis?

14. You are analyzing two normally distributed populations, and your null hypothesis is that the mean f1 1 of the first population is equal to the mean 112 of the second. Assume the significance level is set at 0.05. If the observed p·value is 4.33e-05, what will be your decision regarding the null hypothesis?

Bibliography [1] The R Project for Statistical Computing, "R Licenses." [Online). Available: http : I l www. r-

proj ec t. orgiLicensesl. [Accessed 10 December 2013]. [2] The R Project for Statistical Computing, "The Comprehensive R Arch ive Network." [Online].

Available: http: I lcran . r-project. orgl. [Accessed 10 December 2013].

REVIEW OF BASIC DATA ANALYTIC METHODS USING R

[3] J. Fox and M. Bouchet-Valat, "The R Commander: A Basic-Statistics GUI for R," CRAN. [Online]. Available: http : I / soc s e rv . mcmaster. ca / j fox/ Misc / Rcmdr / . [Accessed 11 December 2013].

[4] G. Williams, M. V. Culp, E. Cox, A. Nolan, D. White, D. Medri, and A. Waljee, "Rattle: Graphical User Interface for Data Mining in R," CRAN. [Online]. Available: ht t p : I I c ran . r - p roj ect . org/ we b / pac kages / rattle/ index . html. [Accessed 12 December 2013].

[5] RStudio, "RStudio IDE" [Online]. Available: http : I / www. rstudio . com/ide / . [Accessed 11 December 2013].

[6] R Special Interest Group on Databases (R-SIG-DB), "OBI: R Database Interface." CRAN [Online]. Available: http : I I cran . r-proj ect. o rg/ we b / packages/ DBI / index . h tml . [Accessed 13 December 2013].

(7] B. Ripley, "RODBC: ODBC Database Access," CRAN. [Online]. Available: http : 11 cran . r-pr o j- e c t . o rg/ web/ packages/ RODBC/ index. html. [Accessed 13 December 2013].

[8] S. S. Stevens, "On the Theory of Scales of Measurement," Science, vol. 103, no. 2684, p. 677-680, 1946.

[9] D. C. Hoaglin, F. Mosteller, and J. W. Tukey, Understanding Robust and Exploratory Data Analysis, New York: Wi ley, 1983.

[10) F. J. Anscom be, "Graphs in Statistical Analysis," The American Statistician, vol. 27, no. 1, pp. 17- 21, 1973.

[11) H. Wickham, "ggplot2," 2013. [Online]. Available: h ttp: I I ggplo t2 . org I . [Accessed 8 January 2014].

[12) W. S. Cleveland, Visualizing Data, Lafayette, IN: Hobart Press, 1993. [13] R. A. Fisher, "The Use of Multiple Measurements in Taxonomic Problems," Annals of Eugenics, vol.

7, no. 2, pp. 179- 188, 1936. [14) B. L. Welch, "The Generalization of "Student's" Problem When Several Different Population

Variances Are Involved," Biometrika, vol. 34, no. 1-2, pp. 28- 35, 1947. [15) F. Wilcoxon, "Individual Comparisons by Ranking Methods," Biometrics Bulletin, vol. 1, no. 6, pp.

80- 83, 1945. [16) J. J. Faraway, "Practical Regression and A nova Using R," July 2002. [Online]. Available: ht tp : 11

c ran. r-pro ject . o r g / doc/c ontrib/ Far away - PRA. pdf. [Accessed 22 January 2014].

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

Building upon the introduction toR presented in Chapter 3, "Review of Basic Data Analytic Methods Using R," Chapter 4, "Advanced Analytical Theory and Methods: Clustering" through Chapter 9, "Advanced Analytical

Theory and Methods: Tex t Analysis" describe several commonly used analytical methods that may be considered for the Model Planning and Execution phases (Phases 3 and 4) of the Data Analytics Lifecycle. This chapter considers clustering techniques and algorithms.

4.1 Overview of Clustering In general, clustering is the use of unsupervised techniques for grouping sim ilar objects. In mach ine learning, unsupervised refers to the problem of finding hidden structure within unlabeled data. Clustering

techniques are unsupervised in the sense that the data scientist does not determine, in advance, the labels to apply to the clusters. The structure of the data describes the objects of interest and determines how best to group the objects. For example, based on customers' personal income, it is straightforward to divide

the customers into three groups depending on arbitrarily selected values. The customers could be divided

into three groups as follows:

• Earn less than $10,000

• Earn between 510,000 and $99,999

• Earn $100,000 or more

In this case, the income levels were chosen somewhat subjectively based on easy-to-communicate points of delineation. However, such groupings do not indicate a natural affinity of the customers within each group. In other words, there is no inherent reason to believe that the customer making $90,000 will

behave any differently than the customer making 5110,000. As additional dimensions are introduced by

adding more variables about the customers, the task of finding meaningful groupings becomes more complex. For instance, suppose variables such as age, years of education, household size, and annual purchase expenditures were considered along with the personal income variable. What are the natural

occurring groupings of customers? This is the type of question that clustering analysis can help answer. Clustering is a method often used for exploratory analysis of the data. In clustering, there are no pre-

dictions made. Rather, clustering methods find the similarities between objects according to the object

attributes and group the similar objects into clusters. Clustering techniques are utilized in marketing, economics, and various branches of science. A popular clustering method is k-means.

4.2 K-means Given a collection of objects each with n measurable attributes, k-means [1] is an analytical technique that, for a chosen value of k, identifies k clusters of objects based on the objects' proximity to the center of the k groups. The center is determined as the arithmetic average (mean) of each cluster's n-dimensional vector of attributes. This section describes the algorithm to determine the k means as well as how best to apply this

technique to several use cases. Figure 4-1 illustrates three clusters of objects with two attributes. Each object in the dataset is represented by a small dot color-coded to the closest large dot, the mean of the cluster.

4.2K-means

• • • •••• • •• • •• • • • • • • • • • • ~ 0 • • • e• o 0 • e o• • • • • 0 0 • • • 0 ••• ••• • 0 0 0 • • ,8 • e0o o • 0 0 0

0

fiGURE 4-1 Possible k-means clusters for k=3

4.2.1 Use Cases Clustering is often used as a lead-in to classification. Once the clusters are identified, labels can be applied to each cluster to classify each group based on its characteristics. Classification is covered in more detai l in Chapter 7, "Advanced Analytical Theory and Methods: Classification." Clustering is primarily an exploratory

technique to discover hidden structures of the data, possibly as a prelude to more focused analysis or decision processes. Some specific applications of k-means are image processing, medical, and customer segmentation.

Image Processing

Video is one example of the growing volumes of unstructured data being collected. Within each frame of a video, k-means analysis can be used to identify objects in the video. For each frame, the task is to deter- mine which pixels are most similar to each other. The attributes of each pixel can include brightness, color, and location, the x and y coordinates in the frame. With security video images, for example, successive frames are examined to identify any changes to the clusters. These newly identified clusters may indicate

unauthorized access to a facility.

Medical

Patient attributes such as age, height, weight, systolic and diastolic blood pressures, cholesterol level, and other attributes can identify naturally occurring clusters. These clusters could be used to target individuals for specific preventive measures or clinica l trial participation. Clustering, in general, is useful in biology for

the classification of plants and animals as well as in the field of human genetics.

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERI NG

Customer Segmentation

Marketing and sa les groups use k-means to better identify customers who have similar behaviors and spending patterns. For example, a wireless provider may look at the following customer attributes: monthly

bill, number of text messages, data volume consumed, minutes used during various daily periods, and years as a customer. The wireless company could then look at the naturally occurring clusters and consider tactics to increase sales or reduce the customer churn rate, the proportion of customers who end their

relationship with a particular company.

4.2.2 Overview of the Method To illustrate the method to find k clusters from a collection of M objects with n attributes, the two- dimensional case (n = 2) is examined. It is much easier to visualize the k-means method in two dimensions. later in the chapter, the two-dimension scenario is generalized to handle any number of attributes.

Because each object in this example has two attributes, it is useful to consider each object correspond- ing to the point (x,. y), where x andy denote the two attributes and i = 1, 2 ... M. For a given cluster of m points (m ~M), the point that corresponds to the cluster's mean is called a centroid. In mathematics, a

centroid refers to a point that corresponds to the center of mass for an object. The k-means algorithm to find k clusters can be described in the following four steps.

1. Choose the value of k and the k initial guesses for the centroids.

In this example, k = 3, and the initial centroids are indicated by the points shaded in red, green, and blue in Figure 4-2.

0 0 0

00 0 0 o 0 8

0 00

0 0 0 0

0 0

0 0 0 0 <e 0 0 0

0 o 0 o

0

0 oo0 0 0 • 0 0 0

0 0

0 0 o o 0 o0o 0 0 0 0 0 0

~ 8 0 0 0 000 0 0

0

0

FIGURE 4-2 Init ial starting points for the centroids

4.2 K-means

2 . Compute the distance from each data point (x ,, y,) to each centroid. Assign each point to the closest centroid. This association defines the first k clusters.

FIGURE4 3

In two dimensions, the distance, d, between any two points, (x 1

, y 1 ) and (x

2 , y

2 ), in the Cartesian

plane is typically expressed by using the Euclidean distance measure provided in Equation 4-1.

(4-1)

In Figure 4-3, the points closest to a centroid are shaded the corresponding color.

• • • •••• • •• • •• • • • • • • • • • • ~ 0 • • • •• o 0 • e o• • • • • 0 0 • • • 0 ••• • • • ••• 0 0 • ,8 • e8 oo • 0 0 0

0

Points are assigned to the closest centroid

3. Compute the centroid, the center of mass, of each newly defined cluster from Step 2.

In Figure 4-4, the computed centroids in Step 3 are the lightly shaded points of the correspond- ing color. In two dimensions, the centroid (xc, Y cl of them points in a k-means cluster is calcu- lated as follows in Equation 4-2.

(4-2)

Thus, (xc, Yc l is the ordered pair of the arithmetic means of the coordinates of them points in the cluster. In this step, a centroid is computed for each of the k clusters.

4. Repeat Steps 2 and 3 until the algorithm converges to an answer.

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

a. Assign each point to the closest centroid computed in Step 3.

b. Compute the centroid of newly defined clusters.

c. Repeat until the algorithm reaches the final answer.

Convergence is reached when the computed centroids do not change or the centroids and the assigned points oscillate back and forth from one iteration to the next. The latter case can occur when there are one or more points that are equal distances from the computed centroid .

• • • ••• • ••• •• • • • • • • • 0 • • • • ~ • • • • • •• • • • •• • • • • • • • •• '0 • •

••• • • O• • • • • • ,. . • •••• • • 0

FIGURE 4-4 Compute the mean of each cluster

To generalize the prior algorithm to n dimensions, suppose there are M objects, where each object is described by n attributes or property values (p,, P2 • .• • pJ Then object i is described by (p,,, P,2, • •• p,.) for i = 1,2, .. . , M. In other words, there is a matrix with M rows corresponding to theM objects and n columns to store the attribute values. To expand the earlier process to find the k clusters from two dimensions ton dimensions, the following equations provide the formulas for calculating the distances and the locations

of the centroids for n ~ 1.

For a given point, p1,at (p", P,2, ••• p,. ) and a centroid, q, located at(q,, q2, .. • q"). the distance, d, between p

1 and q, is expressed as shown in Equation 4-3.

(4-3)

The centroid, q, of a cluster of m points, (p11 , p12 , •• . p1n)• is calculated as shown in Equation 4-4.

(4-4) m

4.2K-means

4.2.3 Determining the Number of Clusters With the preceding algorithm, k clusters can be identified in a given dataset, but what value of k should be selected? The value of k can be chosen based on a reasonable guess or some predefined requirement. However, even then, it would be good to know how much better or worse having k clusters versus k- 1 or k + 1 clusters would be in explaining the structure of the data. Next, a heuristic using the Within Sum of Squares (WSS) metric is examined to determine a reasonably optimal value of k. Using the distance function given in Equation 4-3, WSS is defined as shown in Equation 4-5.

(4-5) 1=1 1=1 j=l

In other words, WSS is the sum of the squares of the distances between each data point and the clos- est centroid. The term q11l indicates the closest centroid that is associated with the ith point. If the points are relatively close to their respective centroids, the WSS is relatively small. Thus, if k + 1 clusters do not greatly reduce the value of WSS from the case with only k clusters, there may be little benefit to adding another cluster.

Using R to Perform a K-means Analysis

To illustrate how to use the WSS to determine an appropriate number, k, of clusters, the following example uses R to perform a k-means analysis. The task is to group 620 high school seniors based on their grades in three subject areas: English, mathematics, and science. The grades are averaged over their high school career and assume values from 0 to 100. The following R code establishes the necessary R libraries and imports the CSV file containing the grades.

library (plyr) library(ggplot2) library(cluster) library(lattice) library(graphics) library(grid) library(gridExtra)

#import the student grades grade_input = as.data.frame(read.csv("c:/data/grades_km_input.csv"))

The following R code formats the grades for processing. The data file contains four columns. The first column holds a student identification (10) number, and the other three columns are for the grades in the three subject areas. Because the student ID is not used in the clustering analysis, it is excluded from the k-means input matrix, kmda ta.

kmdata_orig = as. matrix (grade_input [, c ("Student" I 11 English" I 11 Math" I 11 Science")]) kmdata <- kmdata_orig[,2:4]

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

kmdata[1 :10,)

Engllsh Math Science ( 1' l 99 96 97 (2. l 99 96 97 [ 3'; 98 97 97 (·l,) 95 100 95 [<;,: 95 96 96 (6. l % 97 % [7 .: 100 96 97 [8, l 95 98 98 (9': 98 96 96

[10, l 99 'l9 95

To determine an appropriate value for k, the k-means algori thm is used to identify clusters for

k = 1, 2, .. . , 15. For each value ofk, the WSS is calculated. If an additional cluster provides a better partition- ing of the data points, the WSS should be markedly smaller than without the additional cluster.

The following R code loops through several k-means analyses for the number of centroids, k, varying from 1 to 15. For each k, the option n start= 2 5 specifies that the k-means algorithm wil l be repeated

25 times, each starting with k random initial centroids. The corresponding value ofWSS for each k-mean analysis is stored in the ws s vector.

wss <- numer ic (15) for (kin 1 :15 ) wss[k) < - sum (kmeans (kmdata, centers=k, nstart=25 ) $wi thins s )

Using the basic R plot function, each WSS is plotted against the respective number of centroids, 1 through 15. This plot is provided in Figure 4-5.

plot(1 : 15, wss, type=" b ", xlab="Number of Clusters " , ylab="l'li t h in Sum o f Squares" )

0 0

<J) 0 ~ 0 II') ro N :I cr en 0 0 0 0 E 0 :I

II')

en c 5 0 0 ~ 0 0

II')

0

\ 0

""' o....._ o-o - o - o - o - o - o-o -o- o - o - o I I

2 4 6 8 10 12 14

Nllllber of Clusters

FIOUI!E 4-5 WSS of the student grade data

As can be seen, the WSS is greatly reduced when k increases from one to two. Another substantial

reduction in WSS occurs at k = 3. However, the improvement in WSS is fairly linear fork > 3. Therefore, the k-means analysis wi ll be conducted fork = 3. The process of identifying the appropriate va lue of k is

referred to as finding the "elbow" of the WSS curve.

km kmeans(kmdata,3, nstart~2S) km

K-means clustering with 3 clusters of sizes 158, 218, 244

Cluster means:

English Math Science 1 97.21519 93.37342 94.86076

2 73.22018 64.62844 65.84862

3 85.84426 79.68033 81.50820

Clustering vector:

[1] 1 1 1 1 1 1

1 1 1 1 1 [41] 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1 1 1

1 1 1

1 1 1 1 1 1 1 1 1 1 1 1 1

1 1

1 1 1 1 1 1

1 1 1 1 1 1 1 1 1 1 1 1

[81] 1 1 1 1 1 1 1

1 1 1 1 1 1 1

1 1 1 1 1 1 1 1

1 1

1 1 1 1 1 1 1 1 1 1 1 1 1

[121] 1 1 1 1 1

3 3 3 3 3 [161] 3

1

1

1

3

1 1

3 3 3

1 1 1 1 1 1 1 1 1 1 1

3 3 3 3 1 1 3

[201] 3 3 3 3 3 3 3 3 3

3 3 3 3 3 3 3 3 3 3 [241] 3 3 3 3 3 3 3 3 3 3 3 3

3 3 3 3 3 3 [281] 3 3 3 3 3 3 3

3 3 3 3 3 3 3 [321] 3

3

[361] 3

3

3 3 3

3 3 3

3

3

2 2 2 2 3 3 2 2 2 2

3

3

3 3 3 3 3 3 3 3 3 3

3 3 3 3 3 3 3 3 3 3

3 3 3 3 3 3 3

3 3 3 3 2 2 2 2 2 2 2

1 1 1 1 1

1 3 3

3 3 3

3 3 3

3 3 3 3 3

3 3 3 3 3

2 3 2 3 3 3

[401] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

2 2 2 2 2 2 2 2 2 2 [441] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2

2 2 2 2 2 2 2 2 3 2 [481] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

2 2 2 2 2 2 2 2 2 2 [521] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

2 2 2 2 2 2 2 2 2 2 [561] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

2 2 2 2 2 2 2 2 2 2 [601] 3 2 2 3 1 1 3 3 3 2 2 3 2

Within cluster sum of squares by cluster:

[1] 6692.589 34806.339 22984.131 (between_SS I total_SS 76.5 %)

Available components:

[1] "cluster" "centers" "totss" [6] "betweenss" "size" "iter"

"withinss" "ifault"

"tot.withinss"

4.2K-means

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

The displayed contents of the variable km include the following:

o The location of the cluster means

o A clustering vector that defines the membership of each student to a corresponding cluster 1, 2, or 3

o The WSS of each cluster

o A list of all the available k-means components

The reader can find details on these components and using k-means in R by employing the help facility. The reader may have wondered whether the k-means results stored in km are equivalent to the WSS

results obtained earlier in generating the plot in Figure 4-5. The following check verifies that the results are indeed equivalent.

c( wss[3] , sum(km$withinss)

[1] 64483.06 64483.06

In determining the value of k, the data scientist should visualize the data and assigned clusters. In the following code, the ggplot2 package is used to visualize the identified student clusters and centroids.

#prepare the student data and clustering results for plotting df; as.data.frame(kmdata_orig[,2:4]) df$cluster ; factor(km$cluster) centers;as.data.frame(km$centers)

gl; ggplot(data=df, aes(x;English, y=Math, color=cluster )) + geom_point() + theme(legend.position="right") + geom_point(data=centers,

aes(x;English,y=Math, color=as.factor(c(l,2,3))), size=lO, alpha=.3, show_guide=FALSE)

g2 =ggplot(data=df, aes(x=English, y=Science, color=cluster )) + geom _point () + geom_point(data=centers,

aes(x=English,y=Science, color=as.factor(c(l,2,3))), size=lO, alpha=.3, show_guide=FALSE)

g3 = ggplot(data=df, aes(x=Math, y=Science, color=cluster )) + geom_point () + geom_point(data=centers,

aes(x;Math,y=Science, color=as.factor(c(l,2,3))), size=lO, alpha;.), show_guide=FALSE)

tmp ggplot_gtable(ggplot_build(gl))

100 - ..c:: 90 - ro so - ::2 -o -

eo -

Q) 100 - (.) 90 - ~ 80 - u -o - en eo -

Q) 100 - (.) 90 - ~ so - (.) 70 - en eo -

grid.arrange(arrangeGrob(gl + theme(legend.position="none"), g2 + theme(legend.position="none"), g3 + theme(legend.position= "none "), main ="High School Student Cluster Analysis" , ncol=l) )

4.2K-means

The resul ting plots are provided in Figure 4-6. The large circles represent the location of the cluster

means provided earlier in the display of the kmcontents. The small dots represent the students correspond-

ing to the appropriate cluster by assigned color: red, blue, or green. In general, the plots indicate the three

clusters of students: the top academic students (red), the academical ly cha llenged students (green), and

the other students (b lue) who fall somewhere between those two groups. The plots also highlight which

students may excel in one or two subject areas but struggle in other areas.

High School Student Cluster Analysis

• • • • •

• •

• • • • • • • : • • I • • I • ~~;.:,······ -=· : ~ : : I I I I i I I I I ! I I

I I

eo

• • • . I. . . . . I . . :1 •!::!• a . : ' : .

I

eo

70

• •

so Engli sh

• , . •.. d, llll:

• • • a I · • I a • : : • • • • • e I I I

70 so English

Math

9D

90

• • • •

100

;pt11! • • •

100

FIGURE 4-6 Plots of the identified student clusters

Assigning labels to the identified clusters is useful to communicate the results of an analysis. In a mar- keting context, it is common to label a group of customers as frequent shoppers or big spenders. Such

designations are especia lly useful when communicating the clustering results to business users or execu-

tives. It is better to describe the marketing plan for big spenders rather than Cluster #1.

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

4.2.4 Diagnostics The heuristic using WSS can provide at least several possible k values to consider. When the number of

attributes is relatively small, a common approach to further refine the choice of k is to plot the data to determine how distinct the identified clusters are from each other. In general, the following questions

should be considered.

• Are the clusters well separated from each other?

• Do any of the clusters have only a few points?

• Do any of the centroids appear to be too close to each other?

In the first case, ideally the plot would look like the one shown in Figure 4-7, when n = 2. The clusters are well defined, with considerable space between the four identified clusters. However, in other cases,

such as Figure 4-8, the clusters may be close to each other, and the distinction may not be so obvious.

0 0~ ~C>.>

<D og.?

- 0 0

o~,~

<D

>-

«:

N <%>0 00 <§ 0 @0(/>

I I I I

2 4 6 8

X

FIGURE • -7 Example of distinct clusters

In such cases, it is important to apply some judgment on whether anything different will result by using

more clusters. For example, Figure 4-9 uses six clusters to describe the same dataset as used in Figure 4-8. If using more clusters does not better distinguish the groups, it is almost certainly better to go with fewer clusters.

4.2 K-means

0 0

n 0 0 0 fJ ,j

(X) 0 0 0 0

Oo o o 0 00 0 C• 0

10 0 0 C> 0 0 0

oo 0 >- 0 0 0 0 C• 0 0

0

~ 00 0

0 0

8 0

0 0 0 0 0

N ~ 0 0 0

0 0

T I I

2 4 6 8

X

FIGURE 4-8 Example of less obvious clusters

0

0 0 8 0 f) 0 (X) - 0

0 0

Oo oo 0 0 0 0

10 - 0 0 0 0 0

0 >- 0 0 •:1 0 0

0

-:r - 0 0 0

8 0

0 0 0 0 0

N ~ 0 0 0

0 0 I

2 4 6 8

X

FIGURE 4-9 Six clusters applied to the points from Figure 4-8

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

4.2.5 Reasons to Choose and Cautions K-means is a simple and straightforward method for defining clusters. Once clusters and their associated centroids are identified, it is easy to assign new objects (for example, new customers) to a cluster based on the object's distance from the closest centroid. Because the method is unsupervised, using k-means helps to eliminate subjectivity from the analysis.

Although k-means is considered an unsupervised method, there are still several decisions that the practitioner must make:

o What object attributes should be included in the analysis?

o What unit of measure (for example, miles or kilometers) should be used for each attribute?

o Do the attributes need to be rescaled so that one attribute does not have a disproportionate effect on the results?

o What other considerations might apply?

Object Attributes

Regarding which object attributes (for example, age and income) to use in the analysis, it is important to understand what attributes will be known at the time a new object will be assigned to a cluster. For example, information on existing customers' satisfaction or purchase frequency may be available, but such information may not be available for potential customers.

The Data Scientist may have a choice of a dozen or more attributes to use in the clustering analysis. Whenever possible and based on the data, it is best to reduce the number of attributes to the extent pos- sible. Too many attributes can minimize the impact of the most important variables. Also, the use of several similar attributes can place too much importance on one type of attribute. For example, if five attributes related to personal wealth are included in a clustering analysis, the wealth attributes dominate the analysis and possibly mask the importance of other attributes, such as age.

When dealing with the problem of too many attributes, one useful approach is to identify any highly correlated attributes and use only one or two of the correlated attributes in the clustering analysis. As illustrated in Figure 4-10, a scatterplot matrix, as introduced in Chapter 3, is a useful tool to visualize the pair-wise relationships between the attributes.

The strongest relationship is observed to be between Attribute3 and Attribute7.lfthe value of one of these two attributes is known, it appears that the value of the other attribute is known with near certainty. Other linear relationships are also identified in the plot. For example, consider the plot of Attribute2 against Attribute3.lfthe value of Attribute2 is known, there is still a wide range of possible values for At tribu t e3. Thus, greater consideration must be given prior to dropping one of these attributes from the clustering analysis.

4.2 K-means

Another option to reduce the number of attributes is to combine several attributes into one measure. For example, instead of using two attribute variables, one for Debt and one for Assets, a Debt to Asset ratio

could be used. This option also addresses the problem when the magnitude of an attribute is not of real interest, but the relative magnitude is a more important measure.

FIGURE 4-10 Scatterplot matrix for seven attributes

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

Uni ts of Measure

From a computational perspective, the k-means algorithm is somewhat indifferent to the units of measure

for a given attribute (for example, meters or centimeters for a patient's height). However, the algorithm will identify different clusters depending on the choice of the units of measure. For example, suppose that

k-means is used to cluster pat ients based on age in years and height in centimeters. For k=2, Figure 4-11 illustrates the two clusters that would be determined for a given dataset.

0

0 0 -N

E' 0 ~ lO - J: 01

0 00 0% 00 0 0 00 g> 0 <o 0 o o o o a o o o 0 o o o 0'0 (; 0 f] <S> ~ o o 00 ~ o 0 ooooo>CX> o o o o

o Ooo 0 o 0

Qi 0 r. 0 -

0 lO -

0

I I I I

0 20 40 60 80

age (years)

FIGURE 4-11 Clusters with height expressed in centimeters

But if the height was rescaled from centimeters to meters by dividing by 100, the resulting clusters would be slightly different, as illustrated in Figure 4-12.

0

0

I

0 20 40 60 80

age (years)

FIGURE 4-12 Clusters with height expressed in meters

4.2K·means

When the height is expressed in meters, the magnitude of the ages dominates the distance calculation between two points. The height attribute provides only as much as the square between the difference of the maximum height and the minimum height or (2.0- 0)2 = 4 to the radicand, the number under the square root symbol in the distance formula given in Equation 4·3. Age can contribute as much as(S0 - 0)2 = 6,400 to the radicand when measuring the distance.

Rescaling

Attributes that are expressed in dollars are common in clustering analyses and can differ in magnitude from the other attributes. For example, if personal income is expressed in dollars and age is expressed in

years, the income attribute, often exceeding $10,000, can easily dominate the distance calculation with ages typically less than 100 years.

Although some adjustments could be made by expressing the income in thousands of dollars (for example, 10 for $10,000), a more straightforward method is to divide each attribute by the attribute's

sta ndard deviation. The resulting attributes wi ll each have a standard deviation equal to 1 and wi ll be without units. Returning to the age and height example, the standard deviations are 23.1 years and 36.4 em, respectively. Dividing each attribute value by the appropriate standard deviation and performing the

k-means analysis yields the result shown in Figure 4-13.

0

0 I I I I

00 OS 10 1 5 20 25 30 35

age (rescaled)

FIGURE4 13 Clusters with rescaled attributes

With the rescaled attributes for age and height, the borders of the resulting clusters now fall somewhere

between the two earlier clustering analyses. Such an occurrence is not surprising based on the magnitudes of the attributes of the previous clustering attempts. Some practitioners also subtract the means of the attributes to center the attributes around zero. However, this step is unnecessary because the distance formu la is only sensitive to the scale of the attribute, not its location.

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERING

In many statistical analyses, it is common to transform typically skewed data, such as income, with long

tails by taking the logarithm of the data. Such transformation can also be appied ink-means, but the Data

Scientist needs to be aware of what effect th is transformation will have. For example, if /og10 of income expressed in dollars is used, the practitioner is essentially stating that, from a clustering perspective, $1,000 is as close to S10,000as $10,000 is to $100,000 (because log10 1,000 = 3,1og10 10,000 = 4, and log10 100,000 = 5). In many cases, the skewness of the data may be the reason to perform the clustering analysis in the first place.

Additional Considerations

The k-means algorithm is sensitive to the starting positions of the initial centroid. Thus, it is important to rerun the k-means analysis several times for a particular value of k to ensure the cluster results provide the

overall minimum WSS. As seen earlier, this task is accompl ished in R by using the nstart option in the kmeans () function call.

This chapter presented the use of the Euclidean distance function to assign the points to the closest cen- troids. Other possible function choices include the cosine similarity and the Manhattan distance functions.

The cosine similarity function is often chosen to compare two documents based on the frequency of each word that appears in each of the documents [2). For two points, p and q, at (p

1 , pl' ... p

0 ) and (q

1 , q

2 , .• • q

0 ),

respectively, the Manhattan distance, d1, between p and q is expressed as shown in Equation 4-6.

n

dl(p.q) = L h - q~ (4-6) I I

The Manhattan distance function is analogous to the distance traveled by a car in a city, where the streets are laid out in a rectangular grid (such as city blocks). In Euclidean distance, the measurement is

made in a straight line. Using Equation 4-6, the distance from (1, 1) to (4, 5) would be J1 - 41 + J1 - 51 = 7. From an optimization perspective, if there is a need to use the Manhattan distance for a clustering analysis, the median is a better choice for the centroid than use of the mean [2).

K-means clustering is applicable to objects that can be described by attributes that are numerical with a meaningful distance measure. From Chapter 3, interval and ratio attribute types can certainly be used. However, k-means does not handle categorical variables well. For example, suppose a clustering analysis

is to be conducted on new car sales. Among other attributes, such as the sale price, the color of the car is considered important. Although one could assign numerical values to the color, such as red = 1, yellow

= 2, and green = 3, it is not useful to consider that ye llow is as close to red as yellow is to green from a clustering perspective. In such cases, it may be necessary to use an alternative clustering methodology. Such methods are described in the next section.

4.3 Additional Algorithms The k-means clustering method is easily applied to numeric data where the concept of distance can naturally be applied. However, it may be necessary or desirable to use an alternative clustering algorithm. As discussed at the end of the previous section, k-means does not handle categorical data. In such cases, k-modes [3) is a commonly used method for clustering categorical data based on the number of differences in the respective components of the attributes. For example, if each object has four attributes, the distance from (a, b, e, d) to (d, d, d, d) is 3. In R, the function kmode () is implemented in the klaR package.

Exercises

Because k-means and k-modes divide the entire dataset into distinct groups, both approaches are considered partitioning methods. A third partitioning method is known as Partitioning around Medoids

(PAM) [4). In general, a medoid is a representative object in a set of objects. in clustering, the medoids are the objects in each cluster that minimize the sum of the distances from the medoid to the other objects

in the cluster. The advantage of using PAM is that the "center" of each cluster is an actual object in the dataset. PAM is implemented in R by the pam () function included in the cluster R package. The fpc R package includes a function pamk () ,which uses the pam () function to find the optimal value fork.

Other clustering methods include hierarchical agglomerative clustering and density clustering methods. In hierarchical agglomerative clustering, each object is initially placed in its own cluster. The clusters are

then combined with the most similar cluster. This process is repeated until one cluster, which includes all the objects, exists. The R stats package includes the hclust () function for performing hierarchical

agglomerative clustering. in density-based clustering methods, the clusters are identified by the concentra- tion of points. The fpc R package includes a function, dbscan () ,to perform density-based clustering analysis. Density-based clustering can be useful to identify irregularly shaped clusters.

Summary Clustering analysis groups similar objects based on the objects' attributes. Clustering is applied in areas

such as marketing, economics, biology, and medicine. This chapter presented a detailed explanation of the k-means algorithm and its implementation in R. To use k-means properly, it is important to do the following:

• Properly scale the attribute values to prevent certain attributes from dominating the other attributes.

• Ensure that the concept of distance between the assigned values within an attribute is meaningful.

• Choose the number of clusters, k, such that the sum of the Within Sum of Squares (WSS) of the distances is reasonably minimized. A plot such as the example in Figure 4-5 can be helpful in this respect.

If k-means does not appear to be an appropriate clustering technique for a given dataset, then alterna- tive techniques such as k-modes or PAM should be considered.

Once the clusters are identified, it is often useful to label these clusters in some descriptive way. Especially

when dealing with upper management, these labels are useful to easily communicate the findings of the clustering analysis. In clustering, the labels are not preassigned to each object. The labels are subjectively assigned after the clusters have been identified. Chapter 7 considers several methods to perform the clas- sification of objects with predetermined labels. Clustering can be used with other analytical techniques, such as regression. Linear regression and logistic regression are covered in Chapter 6, "Advanced Analytical

Theory and Methods: Regression."

Exercises 1. Using the age and height clustering example in section 4.2.5, algebraically illustrate the impact on the

measured distance when the height is expressed in meters rather than centimeters. Explain why different clusters will result depending on the choice of units for the patient's height.

2. Compare and contrast five clustering algorithms, assigned by the instructor or selected by the student.

ADVANCED ANALYTICAL THEORY AND METHODS: CLUSTERI NG

3. Using the ruspini dataset provided with the clus ter package in R, perform a k-means analysis. Document the findings and justify the choice of k. Hint: use data ( ruspini ) to load the dataset into the R workspace.

Bibliography [1] J. MacQueen, "Some Methods for Classification and Analysis of Multivariate Observations," in

Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, Berkeley, CA, 1967.

[2] P.-N. Tan, V. Kumar, and M. Steinbach, Introduction to Data Mining, Upper Saddle River, NJ: Person, 2013.

[3] Z. Huang, "A Fast Clustering Algorithm to Cluster Very Large Categorical Data Sets in Data Mining," 1997. [Online]. Available: http : I I ci teseerx . is t . psu . edulviewdocl download ? do i=1 0 . 1. 1 . 134. 83&rep=rep1 &type =pdf. [Accessed 13 March 2014].

[4] L. Kaufman and P. J. Rousseeuw, "Partitioning Around Medoids (Program PAM)," in Finding Groups in Data: An Introduction to Cluster Analysis, Hoboken, NJ, John Wiley & Sons, Inc, 2008, p. 68-125, Chapter 2.

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

This chapter discusses an unsupervised learning method called association rules. This is a descriptive, not predictive, method often used to discover interesting relationships hidden in a large dataset. The disclosed relationships can be represented as rules or frequent itemsets. Association rules are commonly used for

mining transactions in databases. Here are some possible questions that association rules can answer:

• Which products tend to be purchased together?

• Of those customers who are similar to this person, what products do they tend to buy?

• Of those customers who have purchased this product, what other similar products do they tend to view or purchase?

5.1 Overview Figure 5-l shows the general logic behind association rules. Given a large collection of transactions (depicted as three stacks of receipts in the figure), in which each transaction consists of one or more items, associa-

tion rules go through the items being purchased to see what items are frequently bought together and to discover a list of rules that describe the purchasing behavior. The goal with association rules is to discover interesting relationsh ips among the items. (The relationship occurs too frequently to be random and is

meaningful from a business perspective, which may or may not be obvious.) The relationships that are inter-

esting depend both on the business context and the nature of the algorithm being used for the discovery.

:.• ... ... :.•

WIUIO 'iitl rtot Jl tJint't' --.••

t:UC~~o. •• t:US

lHU110 .,_,.,,,, '0 &Ol''

FIGURE 5-1 The genera/logic behind association rules

Cereal Bread Milk Milk

Rules

.. Milk (90%)

.. Milk (40%)

.. Cereal (23%)

.. Apples (10%)

Wine .. Diapers (2%)

Each of the uncovered rules is in the form X ~ Y, meaning that when item X is observed, item Y is also observed. In this case, the left-hand side (LHS) of the rule is X, and the right-hand side (RHS) of the rule is Y.

Using association rules, patterns can be discovered from the data that allow the association ru le algo- rithms to disclose rules of related product purchases. The uncovered rules are listed on the right side of

5.1 Overview

Figure 5-1. The first three rules suggest that when cereal is purchased, 90% of the time milk is purchased also. When bread is purchased, 40% of the time milk is purchased also. When milk is purchased, 23% of the time cereal is also purchased.

In the example of a retail store, association rules are used over transactions that consist of one or more items. In fact, because of their popularity in mining customer transactions, association rules are sometimes referred to as market basket analysis. Each transaction can be viewed as the shopping basket of a customer that contains one or more items. This is also known as an item set. The term itemset refers to a collection of items or individual entities that contain some kind of relationship. This could be a set of retail items purchased together in one transaction, a set of hyperlinks clicked on by one user in a single session, or a set of tasks done in one day. An item set containing k items is called a k-itemset. This chapter uses curly braces like { i tern 1, i tern 2, . . . i tern k} to denote a k-itemset. Computation of the association rules is typically based on item sets.

The research of association rules started as early as the 1960s. Early research by Hajek et al. [1] intro- duced many of the key concepts and approaches of association rule learning, but it focused on the mathematical representation rather than the algorithm. The framework of association rule learning was brought into the database community by Agrawal et al. [2] in the early 1990s for discovering regularities between products in a large database of customer transactions recorded by point-of-sale systems in supermarkets. In later years, it expanded to web contexts, such as mining path traversal patterns [3] and usage patterns [4] to facilitate organization of web pages.

This chapter chooses Apriori as the main focus of the discussion of association rules. Apriori [5] is one of the earliest and the most fundamental algorithms for generating association rules. It pioneered the use of support for pruning the itemsets and controlling the exponential growth of candidate item- sets. Shorter candidate item sets, which are known to be frequent item sets, are combined and pruned to generate longer frequent itemsets. This approach eliminates the need for all possible item sets to be enumerated within the algorithm, since the number of all possible itemsets can become exponentially large.

One major component of Apriori is support. Given an item set L, the support [2] of Lis the percentage of transactions that contain L. For example, if 80% of all transactions contain item set {bread}, then the support of {bread} is 0.8. Similarly, if 60% of all transactions contain itemset {bread, butter}, then the support of {bread, butter} is 0.6.

A frequent itemset has items that appear together often enough. The term "often enough" is for- mally defined with a minimum support criterion. If the minimum support is set at 0.5, any itemset can be considered a frequent item set if at least 50% of the transactions contain this itemset. In other words, the support of a frequent itemset should be greater than or equal to the minimum support. For the previous example, both {bread} and {bread, butter} are considered frequent item sets at the minimum support 0.5. If the minimum support is 0.7, only {bread} is considered a frequent itemset.

If an item set is considered frequent, then any subset of the frequent item set must also be frequent. This is referred to as the Apriori property (or downward closure property). For example, if 60% of the transactions contain {bread, jam}, then at least 60% of all the transactions will contain {bread} or {jam}. In other words, when the support of {bread, jam} is 0.6, the support of {bread} or { jam} is at least 0.6. Figure 5-2 illustrates how the A priori property works. If item set { B, c, D} is frequent, then all the subsets of this itemset, shaded, must also be frequent itemsets. The Apriori property provides the basis for the Apriori algorithm.

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

FIGURE 5-2 Item set {A,B,C,D} and its subsets

5.2 Apriori Algorithm The Apriori algorithm takes a bottom-up iterative approach to uncovering the frequent itemsets by fi rst

determining al l the possible items (or 1-itemsets, for example {bread}, {eggs}, {milk}, .. . ) and then identifying which among them are frequent.

Assuming the minimum support threshold (or the minimum support criterion) is set at 0.5, the algo-

rithm identifies and reta ins those itemsets that appear in at least 50% of all transactions and discards (or

"prunes away") the itemsets that have a support less than 0.5 or appear in fewer than 50% of the trans-

actions. The word prune is used like it would be in gardening, where unwanted branches of a bush are

clipped away.

In the next iteration of the Apriori algorithm, the identified frequent 1-itemsets are paired into

2-itemsets (for example, {bread, eggs} , {bread , milk}, {eggs, milk), ... ) and again evalu- ated to identify the frequent 2-itemsets among them.

At each iteration, the algorithm checks whether the support criterion can be met; if it can, the algorithm

grows the itemset, repeating the process until it runs out of support or until the itemsets reach a predefined

length. The A priori algorithm [5] is given next. Let variable Ck be the set of candidate k-itemsets and variable Lk be the set of k-itemsets that satisfy the minimum support. Given a t ransaction database 0, a minimum support threshold /5 , and an optional parameter N indicating the maximum length an itemset could reach, Apriori iteratively computes frequent itemsets Lk .1 based on Lk.

1 Apriori (0 , 6, N ) 2 k-1 3 L,- {1-itemsets that satisfy minimum support 6} 4 while L, ""0

s if ~N V (3N 1\ k < N)

5.3 Evaluation of Candidate Rules

6 C~t- 1 .... candi date i t emsets generated from Lk 7 f or each t r ansaction t in database 0 do B increment the counts of Ck _

1 containe d i n

9 Lk~ l ~ cand idate s i n Ck+l that satisfy minimum s upport 8 10 k - k + l 11 return U L

k k

The first step of the A priori algorithm is to identify the frequent item sets by starting with each item in the

transactions that meets the predefined minimum support threshold 8. These itemsets are 1-itemsets denoted as~. as each 1- itemset contains only one item. Next, the algorithm grows the item set s by joining

~onto itself to form new, grown 2-itemsets denoted as~ and determines the support of each 2-itemset

i n ~- Those itemsets that do not meet the minimum support threshold 8 are pruned away. The growing and pruning process is repeated until no itemsets meet the minimum support threshold. Optionally, a

threshold N can be set up to specify the maximum number of items the item set can reach or the maximum

number of iterations of the algorithm. Once completed, output of the Apriori algori thm is the collection

of all the frequent k-itemsets.

Next, a co llection of candidate rules is formed based on the frequent itemsets uncovered in the itera-

tive process described earlier. For example, a frequent itemset {mi lk, eggs} may suggest candidate rules {mi lk}-+{ eggs } and {eg gs} -.{milk} .

5.3 Evaluation of Candidate Rules Frequent itemsets from the previous section can form candidate ru les such as X implies Y (X -7 Y). This

section discusses how measures such as confidence, li ft, and leverage can help evaluate the appropriate-

ness of t hese candidate rules.

Confidence [2] is defined as the measure of certainty or t rustworthiness associated with each discov-

ered rule. Mathematically, confidence is the percent of transactions that contain both X and Y out of all the transactions t hat contain X (see Equation 5-1).

C ,.d (X Y) Support(X 1\ Y) on11 ence -+ = --'-'------'- Support( X)

(S-1)

For example, if {b r e ad, eggs , milk} has a support ofO.lS and {bread , eggs} also has a support of0.15, the confidence of rule (bread, egg s} ->{ milk} is 1, wh ich means 100% of the time a customer buys bread and eggs, milk is bought as well. The rule is therefore correct for 100% of the transactions

containing bread and eggs.

A relationship may be thought of as interesting when the algorithm identifi es the relationship with a

measure of confidence greater than or equal to a predefined threshold. This predefined threshold is called

the minimum confidence. A higher confidence indicates that the rule (X -7 Y) is more interesting or more

trustworthy, based on the sample dataset.

So far, th is chapter has talked about t wo common measures that the A priori algorithm uses: support

and confidence. All the rules can be ranked based on these two measures to filter out the uninteresting

rules and retain the interesting ones.

ADVANCED ANALmCAL THEORY AND METHODS: ASSOCIATION RULES

Even though confidence can identify the interesting rules from all the candidate rules, it comes with a problem. Given rules in the form of X ~ Y, confidence considers only the antecedent (X) and the co- occurrence of X and Y; it does not take the consequent of the rule (Y) into concern. Therefore, confidence cannot tell if a rule contains true implication of the relationship or if the rule is purely coincidental. X and Y can be statistically independent yet still receive a high confidence score. Other measures such as lift [6] and leverage [7] are designed to address this issue.

Lift measures how many times more often X and Y occur together than expected if they are statisti- cally independent of each other. lift is a measure [6] of how X andY are really related rather than coinci- dentally happening together (see Equation 5-2).

Lift(X -t Y) = Support(X 1\ Y) Support( X)* Support(Y)

(5-2)

Lift is 1 if X and Y are statistically independent of each other. In contrast, a lift of X ~ Y greater than 1 indicates that there is some usefulness to the rule. A larger value of lift suggests a greater strength of the association between X and Y.

Assuming 1,000 transactions, with {milk, eggs} appearing in 300 ofthem, {milk} appearing in 500, and {eggs} appearing in 400, then Lift(milk -t eggs)= 0.3/(0.5 *0.4) = 1.5. If {bread} appears in 400 transactions and {milk, bread} appears in 400, then Lift(milk -t bread)=0.4/{0.5*0.4) =2. Therefore it can be concluded that milk and bread have a stronger association than milk and eggs.

Leverage [7] is a similar notion, but instead of using a ratio, leverage uses the difference (see Equation 5-3). Leverage measures the difference in the probability of X and Y appearing together in the dataset compared to what would be expected if X and Y were statistically independent of each other.

Leverage (X -t Y) =Support (X 1\ Y)- Support( X)* Support(Y) (5-3)

In theory, leverage is 0 when X and Yare statistically independent of each other. If X and Y have some kind of relationship, the leverage would be greater than zero. A larger leverage value indicates a stronger relationship between X andY. For the previous example, Leverage(milk -t eggs)= 0.3-(0.5*0.4) = 0.1 and Leverage(milk -t bread)=0.4-(0.5*0.4) = 0.2.1t again confirms that milk and bread have a stronger association than milk and eggs.

Confidence is able to identify trustworthy rules, but it cannot tell whether a rule is coincidental. A high-confidence rule can sometimes be misleading because confidence does not consider support of the itemset in the rule consequent. Measures such as lift and leverage not only ensure interesting rules are identified but also filter out the coincidental rules.

This chapter has discussed four measures of significance and interestingness for association rules: support, confidence, lift, and leverage. These measures ensure the discovery of interesting and strong rules from sample datasets. Besides these four rules, there are other alternative measures, such as corre- lation [8], collective strength [9], conviction [6], and coverage [10]. Refer to the Bibliography to learn how these measures work.

5.5 An Example: Transactions in a Grocery Store

5.4 Applications of Association Rules The term market basket analysis refers to a specific implementation of association rules mining that many companies use for a variety of purposes, including these:

• Broad-scale approaches to better merchandising- what products should be included in or excluded from the inventory each month

• Cross-merchandising between products and high-margin or high-ticket items

• Physical or logical placement of product within related categories of products

• Promotional programs-multiple product purchase incentives managed through a loyalty card program

Besides market basket analysis, association rules are commonly used for recommender systems [11 ] and clickstream analysis [12].

Many online service providers such as Amazon and Netflix use recommender systems. Recommender systems can use association rules to discover related products or identify customers who have similar interests. For example, association rules may suggest that those customers who have bought product A

have also bought product B, or those customers who have bought products A, B, and Care more similar to this customer. These findings provide opportunities for retailers to cross-sell their products.

Clickstream analysis refers to the analytics on data related to web browsing and user clicks, which

is stored on the client or the server side. Web usage log files generated on web servers contain huge

amounts of information, and association rules can potentially give useful knowledge to web usage data analysts. For example, association rules may suggest that website visitors who land on page X click on

links A, B, and C much more often than links 0, E, and F. This observation provides valuable insight on

how to better personalize and recommend the content to site visitors. The next section shows an example of grocery store transactions and demonstrates how to useR to

perform association rule mining.

5.5 An Example: Transactions in a Grocery Store An example illustrates the application of the A priori algorithm to a relatively simple case that generalizes

to those used in practice. Using Rand the a r ules and arulesVi z packages, this example shows how to use the A priori algorithm to generate frequent itemsets and rules and to evaluate and visual ize the rules.

The following commands install these two packages and import them into the current R workspace:

ins t a ll.packages ( ' arules' ) ins tall.packages ( 'arulesViz' )

library ( ' a rul es ' ) l i b r ary( ' arulesViz ' )

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

5.5.1 The Groceries Dataset The example uses the Groceries dataset from the R arules package. The Groceries dataset is collected from 30 days of real-world point-of-sale transactions of a grocery store. The dataset contains 9,835 transactions, and the items are aggregated into 169 categories.

data(Groceries) Groceries transactions in sparse format with

9835 transactions lrowsl and 169 items (columns)

The summary shows that the most frequent items in the dataset include items such as whole milk, other vegetables, rolls/buns, soda, and yogurt. These items are purchased more often than the others.

summary(Groceries) transactions as itemMatrix in sparse format with

9835 rows (elements/itemsets/transactionsl and 169 columns !items) and a density of 0.02609146

most frequent items: whole milk other vegetables

2513 1903 y·ogurt

1372 (Other)

34055

rolls/buns

1809

element (itemset/transaction) length distribution:

sizes

1 2 4 5 6 7 9 10 2159 1643 1299 1005 855 645 545 438 350 246

15 16 17 18 19 20 21 22 23 24 55 46 29 14 14 9 ll 4 6 32

1

Min. 1st Qu. !•led ian r•lean 3rd Qu. !\lax.

1. 000 2.000 3.000 4.409 6.000 32.000

includes extended item information - examples: labels level2 levell

1 frankfurter sausage meet and sausage 2 sausage sausage meet and sausage

liver loaf sausage meet and sausage

soda 1715

11 12 13 14

132 117 78 77

26 27 28 29 l 3

The class of the dataset is transactions, as defined by the arules package. The transactions class contains three slots:

o transac tioninfo: A data frame with vectors of the same length as the number of transactions

o i teminfo: A data frame to store item labels

o data: A binary incidence matrix that indicates which item labels appear in every transaction

class(Groceries) (1] "transactions" att!: 1:, "package" ,I [1] "arules"

5.5 An Example: Transactions in a Grocery Store

For the Groceries dataset, the transactioninfo is not being used. Enter Groceries®i teminfo to display all169 grocery labels as well as their categories. The following command displays only the first 20 grocery labels. Each grocery label is mapped to two levels of catego- ries-level2 and level1-where level1 is a superset of level2. For example, grocery label sausage belongs to the sausage category in level2, and it is part of the meat and sausage category in levell. (Note that "meet" in level1 is a typo in the dataset.}

Groceries®iteminfo[1:20,] leveL::

frankfurter sa'Jsage 2 sa'Jsagt: sausa9e

l i ·.rer loal sausage 4 han sausage 5 meat. sausage 6 finished products sausage 7 organic sausaqe sausage 8 chicken p::::ul tl·:-· 9 ~u::..-key·· poultry 10 pod: n::cd: 11 beef beef 12 hamburger meat beef 13 fish fish 1 •l citrus fruit fc,lit 15 tropical :ruit fr:.:i t 16 pip fn:it fr--.:i:: 17 grapes fruit 18 berries fruit 19 nuts/prunes fruit 20 root vegetables vegetables

meet a:--.a sa·l:~~age

meet and sa~~Qge meet and sa~~age

meet and sat:o:;aqc meet ar,d sai:::,\yc

meet and Sc'lL'dLJe

mee~ a:1d sau~~· .. :=aqe

mee:: a:1d sau,,c;ge

meet and sausage meet and sausage

ftui t and vegel'lbl·:::s ,.reget~iL'l~s

~/eg~t ~d:~ l~s

veget ai; l es

vegetal' 1 es ... Jegetal_}les

f:uit anG t !_"'Ll_:_ t a.r:d

- !."tl.i t_ a:1d fn1i t a:1d fruit and fn.tit and vegetables

The following code displays the lOth to 20th transactions of the Groceries dataset. The [ 1 o : 2 o] can be changed to [ 1 : 9 8 3 5 J to display all the transactions.

apply(Groceries®data[,l0:20], 2, function(r) paste(Groceries®iteminfo[r, ''labels 11 ), collapse= 11 , 11 )

Each row in the output shows a transaction that includes one or more products, and each transaction corresponds to everything in a customer's shopping cart. For example, in the first transaction, a cus- tomer has purchased whole milk and cereals.

[1] "whole milk, cereals" [2] "tropical fruit, other vege·:ables, •:ihite ht•·:d, bottled \•later,

chocolate" [3] "citrus fruit, tropical fc·u:t, ·.·:hole :nil;.:, i·.1:ter, curd, 'iogurt,

flour, bottled ·.·:ater, d::.shes" [4] "beef"

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

[5] "frankfurter, rolls/buns, soda" [6] "chicken, tropical fruit" (7] "butter, sugar, fruit/vegetable juice, newspapers" [B] "fruit/vegetable juice" [9] "packaged fruit/vegetables"

[10] "chocolate" [11] "specialty bar"

The next section shows how to generate frequent itemsets from the Groceries dataset.

5.5.2 Frequent ltemset Generation The apriori (} function from the arule package implements the Apriori algorithm to create frequent itemsets. Note that, by default, the apriori (} function executes all the iterations at once. However, to illustrate how the Apriori algorithm works, the code examples in this section manually set the parameters of the apriori (} function to simulate each iteration of the algorithm.

Assume that the minimum support threshold is set to 0.02 based on management discretion. Because the dataset contains 9,853 transactions, an item set should appear at least 198 times to be considered a frequent item set. The first iteration of the Apriori algorithm computes the support of each product in the dataset and retains those products that satisfy the minimum support. The following code identifies 59 frequent 1-itemsets that satisfy the minimum support. The parameters of apr ior i ( ) specify the minimum and maximum lengths of the item sets, the minimum support threshold, and the target indicating the type of association mined.

itemsets <- apriori(Groceries, parameter;list(minlen=l, maxlen=l, support=0.02, target= 11 frequent itemsets 11 ))

parame:er specification: confidence minval smax arem aval originalSupport support minlen

0.8 0.1 1 none FALSE TRUE 0.02 1 max len target ext

1 frequent itemsets FALSE

algorithmic control: filter tree heap memopt load sort verbose

0.1 TRUE TRUE FALSE TRUE 2 TRUE

apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09) (c) 1996-2004 Christian Borgelt set item appearances ... [0 item(s)) done [O.OOs]. set transactions ... [169 item(s), 9835 transaction(s)] done [O.OOs]. sorting and recoding items ... [59 item(s) J done [O.OOs]. creating transaction tree ... done [O.OOs]. checking subsets of size 1 done [O.OOs]. writing ... [59 set(s)) done [O.OOs). creating S4 object ... done [0. oos].

5.5 An Example: Transactions in a Grocery Store

The summary of the itemsets shows that the support of Htemsets ranges from 0.02105 to 0.25552. Because the maximum support of the 1-itemsets in the dataset is only 0.25552, to enable the discovery of interesting rules, the minimum support threshold should not be set too close to that number.

surnrnary(iternsets) set of 59 itemsets

most frequent items: frankfurter sausage

1 1

(Other) 54

ham 1

neat 1

chicken 1

element (itemset/transaction) length distribution:sizes 1

59

Min. 1st Qu. Median 1

Mean 3rd Qu. 1 1

summary of quality measures: support

Min. :0.02105 1st Qu. :0.03015 Median :0.04809 Mean :0.06200 3 rd Qu . : 0 . 0 7 6 6 6 !'-lax . : 0 . 2 55 52

includes transaction ID lists: FALSE

mining info: data ntransactions support confidence

Groceries 9835 0.02 1

r·1ax. 1

The following code uses the inspect () function to display the top 10 frequent 1-itemsets sorted by their support. Of all the transaction records, the 59 1-itemsets such as {whole milk}, {other vegetables}, {rolls/buns}, {soda}, and {yogurt} allsatisfytheminimum support. Therefore, they are called frequent 1-itemsets.

inspect(head(sort(iternsets, by = "support 11 ), 10)) items support

1 {whole milk} 0.25551601 2 {other vegetables} 0.19349263 3 {rolls/buns} 0.18393493 4 {soda} 0.17437722 5 {yogurt} 0.13950178 6 {bottled water} 0.11052364

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

7 {root vegetables} 8 {tropical fruit} 9 {shopping bags} 10 {sausagef

0.10899847

0.10.J93137

0.09852567

0.09395018

In the next iteration, the list of frequent 1-itemsets is joined onto itself to form all possible candidate 2-itemsets. For example, 1-itemsets {who 1 e milk} and { soda} would be joined to become a 2-itemset {whole milk, soda}. The algorithm computes the support of each candidate 2-itemset and retains those that satisfy the minimum support. The output that follows shows that 61 frequent 2-itemsets have been identified.

itemsets <- apriori(Groceries, parameter~list(minlen=2, maxlen=2, support=0.02, target="frequent itemsets"))

parameter specification: confidence minval smax arem aval originalSupport support minlen

0.8 0.1 l 1:one ?i\LSE TRUE 0.02 2 ma:den target ext

2 frequent itemsets FALSE

algorithmic control: filter tree heap memopt load sort verbose

0.1 TRUE TRUE FALSE TRUE 2 TRUE

apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09) (c) 1996-2004 Christian Borgelt set item appear.:1nces ... [0 item(s)] done [O.OOs]. set transaction:; ... [169 item(s), 9835 transaction(s;] done [O.OOs). sorting and receding item.s ... [59 item(s)] done [O.OOs]. creating transaction tree ... done [O.OOs]. checking subsets of size l 2 done [O.OOs]. \•niting ... [61 set:s)] clone [O.OOs]. Cl·eating S4 object ... done [O.OOs].

The summary of the itemsets shows that the support of 2-itemsets ranges from 0.02003 to 0.07483.

summary(itemsets) set of 61 itemsets

most frequent items: whole mil~ other vegetables

25 :7 soda

S3

yogurt 9

element (itemset•tra~sactlon length distribution:si:es 2

61

rolls/buns 9

Min. 1st Qu. Median !•lean 3 rd Qu. 2 2 2

summary of quality measures: support

l·l in . : J . 0 2 0 0 3 1st Qu. :0.02227 !·ledian : 0. 02613 !·lean :0.02951 3rd Qu. :0.03223 !•lax. :0.07483

2

includes transaction ID lists: FALSE

mining info:

2

data ntransactions support confidence Groceries 9835 0.02

5.5 An Example: Transactions in a Grocery Store

2

The top 10 most frequent 2-itemsets are displayed next, sorted by their support. Notice that whole milk appears six times in the top 10 2-itemsets ranked by support. As seen earlier, {whole milk} has the highest support among all the 1-itemsets. These top 10 2-itemsets with the highest support may not be interesting; this highlights the limitations of using support alone.

inspect(head(sort(itemsets, by ="support 11 ),10)) items support {other vegetables, >·:hole milk} 0.07..;83477

2 {·.·:hole milk, rolls/buns} 0.05663-i47

{whole milk, yogurt} 0.056024-iO

{root vegetables, whole milk} 0.04890696

5 {root vegetables, other vegetables} 0.04738180

6 {other vegetables, yogurt} 0.04341637

7 {other vegetables, rolls/buns} 0.04260295

8 {tropical fruit, \•Jhole milk} 0.04229792

9 { vlhole milk, soda} 0.04006101

10 {rolls/buns, soda} 0.03833249

Next, the list of frequent 2-itemsets is joined onto itself to form candidate 3-itemsets. For example {other vegetables, whole milk} and {whole milk, rolls/buns} wouldbejoined as {other vegetables, whole milk, rolls/buns}. The algorithm retains those itemsets

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

that satisfy the minimum support. The following output shows that only two frequent 3-itemsets have been identified.

itemsets <- apriori(Groceries, parameter~list(minlen=3, maxlen~3, support~0.02, target~"frequent itemsets"))

parameter specification: confidence minval smax arem aval originalSupport support minlen

0.8 0.1 1 none FALSE TRUE 0.02 max len target ext

frequent itemsets FALSE

algorithmic control: filter tree heap memopt load sort verbose

0.1 TRUE TRUE FALSE TRUE 2 TRUE

apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09) (c) 1996-2004 Christian Borgelt set item appearances ... [0 item(s)] done [O.OOs]. set transactions ... [169 item(s), 9835 transaction(s)] done [O.OOs]. sorting and receding items ... [59 item(s)) done (O.OOs]. creating transaction tree ... done [0. OOs) . checking subsets of size 1 2 3 done [O.OOs]. writing . . . [2 set (s)] done [O. OOs]. creating S4 object ... done (O.OOs].

The 3-itemsets are displayed next:

inspect(sort(itemsets, by ="support")) items support

1 {root vegetables, other vegetables, whole milk} 0.02318251

2 {other vegetables, whole milk, yogurt} 0.02226741

In the next iteration, there is only one candidate 4-itemset {root vegetables, other vegetables, whole milk, yogurt}, and its support is below 0.02. No frequent 4-itemsets have been found, and the algorithm converges.

itemsets <- apriori(Groceries, parameter~list(minlen~4, maxlen=4, support=0.02, target~"frequent itemsets"))

parameter specification: confidence minval smax arem aval origi~alSupport support minlen

0.8 0.1 1 none FALSE TRUE 0.02 4 max len target ext

frequent itemsets FALSE

5.5 An Example: Transactions in a Grocery Store

algorithmic control: filter tree heap memopt load sort verbose

0.1 TRUE TRUE FALSE TRUE 2 TRUE

apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09) (c) 1996-2004 Christian Borgelt set item appearances ... [0 item(s)] done [O.OOs]. set transactions ... [169 item(s), 9835 transaction(s)] done [O.OOs]. sorting and receding items . . . [59 item (s)] done [0. OOs] . creating transaction tree ... done [O.OOs]. checking subsets of size 1 2 3 done [O.OOs]. writing ... [0 set(s)] done [O.OOs]. creating S4 object ... done [0. OOs] .

The previous steps simulate the Apriori algorithm at each iteration. For the Groceries dataset, the iterations run out of support when k = 4. Therefore, the frequent itemsets contain 59 frequent 1-itemsets,61 frequent 2-itemsets, and 2 frequent 3-itemsets.

When the max len parameter is not set, the algorithm continues each iteration until it runs out of support or until k reaches the default maxlen=l o. As shown in the code output that follows, 122 frequent itemsets have been identified. This matches the total number of 59 frequent 1-itemsets, 61 frequent 2-itemsets, and 2 frequent 3-itemsets.

itemsets <- apriori(Groceries, parameter=list(minlen=l, support=0.02, target= 11 frequent itemsets 11 ))

parameter specification: confidence minval smax arem aval originalSupport support minlen

0.8 0.1 1 none FALSE TRUE 0.02 max len target ext

10 frequent itemsets FALSE

algorithoic control: filter tree heap memopt load sort verbose

0.1 ~RUE TRUE FALSE TRUE TRUE

apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09! (c) 1996-2004 Christian Borgelt set item appearances ... [0 items!] dOJ:e [o.oos:. set transactions ... [169 item(s, 9835 transaction(s)) done [O.OOs). sorting and receding items ... :s9 item(s!] done [O.OOs]. creating transaction tree ... done [O.OOs]. checking subsets of size 1 2 3 done [O.OOs). ,,.;riting ... [122 setl,s)] done [O.OOs]. creating S.f object ... done [O.OOs].

Note that the results are assessed based on the specific business context of the exercise using the specific dataset. If the dataset changes or a different minimum support threshold is chosen, the Apriori algorithm must run each iteration again to retrieve the updated frequent itemsets.

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

5.5.3 Rule Generation and Visualization The apriori () function can also be used to generate rules. Assume that the minimum support threshold is now set to a lower value 0.001, and the minimum confidence threshold is set to 0.6. A lower minimum support threshold allows more rules to show up. The following code creates 2,918 rules from all the transac- tions in the Groceries dataset that satisfy both the minimum support and the minimum confidence.

rules <- apriori(Groceries, parameter=list(support=O.OOl, confidence=0.6, target= 11 rules 11 ))

parameter specification: confidence minval smax arem aval originalSupport support minlen

0.6 0.1 1 none FALSE TRUE 0.001 1 maxlen target ext

10 rules FALSE

algorithmic control: filter tree heap memopt load sort verbose

0.1 TRUE TRUE FALSE TRUE 2 TRUE

apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09) (c) 1996-2004 Christian Borgelt set item appearances ... (0 item(s)] done (O.OOs]. set transactions ... [169 item{s), 9835 transaction(s)] done (O.OOs]. sorting and receding items . . . [157 item (s) J done [0. OOs]. creating transaction tree ... done [O.OOs]. checking subsets of size 1 2 3 4 5 6 done [0.01s]. writing ... [2918 rule(s)] done [O.OOs]. creating S4 object ... done [0.01s].

The summary of the rules shows the number of rules and ranges of the support, confidence, and lift.

summary(rules) set of 2918 rules

rule length distribution {lhs + rhs) :sizes 2 3 4 5 6 3 490 1765 626 34

l\1in. 1st Qu. 2.000 4.000

l·ledian 4.000

1-lean 3 rd Qu. 4.068 4.000

l\lax. 6.000

summary of quality measures: support confidence

Min. :0.001017 Min. :0.6000 1st Qu. :0.001118 1st Qu. :0.6316 l\ledian :0. 001220 Mean :0.001480 3rd Qu. :0.001525 !>lax. :0.009354

l>'Jedian :0.6818 !•lean :0.7028 3rd Qu.: 0. 7500 Max . : 1 . 0 0 0 0

lift 1-lin. 2.348 1st Qu.: 2. 668 r-ledian : 3 . 16 8 !\lean 3.450 3rd Qu.: 3.692 !·lax. : 18. 996

5.5 An Example: Transactions in a Grocery Store

min1n 1 info: d3•1 ntt n .. f l n

Enter p lot (rules) to display the scatterplot of the 2,918 rules (Figure 5-3), where the horizontal

axis is the support, the vertical axis is the confidence, and the shading is the lift. The scatterplot shows

that, of the 2,918 rules generated from the Groceries dataset, the highest lift occurs at a low support and a low confidence.

Scatter plot for 2918 rules

0 9 15

Q) u c Q) "0 0 8 ~ 0

10 u

07

5

0 6

0.002 0 004 0.006 0.008 lift

support

FIGURE 5-3 Scatterplot of the 2,978 rules with minimum support 0.007 and minimum confidence 0.6

Entering p lot ( rules®q ual i ty) displays a scatterplot matrix (Figure 5-4) to compare the sup- port, confidence, and lift of the 2,918 rules.

Figure 5-4 shows that lift is propor tional to confidence and illustrates several linear groupings. As indicated by Equation 5-2 and Equation 5-3, Lift = Confidence / Support(Y). Therefore, when the support of Y remains the same, lift is proportional to confidence, and the slope of the linear trend is the recipro- cal of Support(Y). The following code shows that, of the 2,918 rules, there are only 18 different values for

- - 1 - , and the majority occurs at slopes 3.91, 5.17, 7.17, 9.17, and 9.53. This matches the slopes shown

Support(Y) in the third row and second column of Figure S-4, where the x-axis is the confidence and they-axis is the lift.

;; comput • Llw l/Suppot·t ry slo pe<· sort(round (rules®quality$lift I r ul es®quality$conf ide nce , 2)) = D .... sp .... 3.Y ,.. ht 1 Jtiti 1 ~ • j 1 h ~ t! ~ .1 la t :i~ ... unlist( l apply(spl it(s l o pe,f=slope) ,length ) )

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

0

"' ci cq 0

..... ci

<D 0

< . 91 <;.17 S . ·s t ') , 7 7 . • 7 9.05 9 . 17 9.53 ::.0 . 64 l::! . 08 1585 9·10 1:1 7 lclB 1r:? "5 .,

12 . 4. 11 .. 2 . 81 11 . Q') 18. • ' . 76 .. 6 . ·J.i 30.08 l 5 9 1 ::.

06 07 08 0.9 1.0

0

0 0 oo ~

L support 0 00 00 0 0

0 0 0

confidence

0

'bo 0 0

0 0

0 0 0 0

8 0 0 0 0

~ 0 lift

~B~o tp o o 0 ~~~::, ooO 0

0

:nr~~-= 0 O>c:Jb coo 0 I

0.002 0.004 0.006 0.008 5 10

FIGURE 5-4 Scatterplot matrix on the support, confidence, and lift of the 2,918 rules

The inspect () function can display content of the rules generated previously. The following code shows the top ten rules sorted by the lift. Ru le {Instant food p roducts , soda} .... ( hamburger meat} has the highest lift of 18.995654.

inspect(head(sort(rules , by="lift") , 10))

rrturg r <>a· I

0.

3 {ham

0.

CD 0 0 ci

"' 0 0 0 0 0 ci

0 0 0

~

~

l{)

15

4 {tropical fruit, other vegetables, yogurt, white bread} => {butter}

0.001016777 0.6666667 12.030581 5 {hamburger meat,

yogurt, whipped/sour cream} => {butter}

0.001016777 0.6250000 11.278670 6 {tropical fruit,

other vegetables, whole milk, yogurt, domestic eggs} => {butter}

0.001016777 0.6250000 11.278670 7 {liquor,

red/blush wine} => {bottled beer} 0.001931876 0.9047619 11.235269 8 {other vegetables,

5.5 An Example: Transactions in a Grocery Store

butter, sugar}

0.001016777 0.7142857 9 {whole milk,

butter,

=> {whipped/sour cream} 9.964539

hard cheese} 0.001423488 0.6666667 10 {tropical fruit,

other vegetables, butter,

=> {whipped/sour cream} 9.300236

fruit/vegetable juice} => {whipped/sour cream} 0.001016777 0.6666667 9.300236

The following code fetches a total of 127 rules whose confidence is above 0.9:

confidentRules <- rules[quality(rules)$confidence > 0.9] confidentRules set of 127 rules

The next command produces a matrix-based visualization (Figure 5-5) of the LHS versus the RHS of the rules. The legend on the right is a color matrix indicating the lift and the confidence to which each square in the main matrix corresponds.

plot(confidentRules, method= 11 matrix 11 , measure=c( 11 lift 11 , "confidence 11 ), control=list(reorder=TRUE))

As the previous plot () command runs, the R console would simultaneously display a distinct list of the LHS and RHS from the 127 rules. A segment of the output is shown here:

Itemsets in Antecedent (LHS) [1] "{citrus fruit,other vegetables,soda,fruit/vegetable juice}" [2] "{tropical fruit,other vegetables,whole milk,yogurt,oil}"

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

[3] " (tropical fnti t, butter, whipped/sour cream, frult/vegetable juice) "

[4] " { t1·opical fruit , g1·apes, •,:hole milk, yogu~:t)" [5] "{ham,tropical auit,pip fruit,whole mllk}"

[124] " {liquar,rec/blush '"'lne}" Itemsets in Consequent (RHS) [l] "{whole mllk}" "(rogurt} " "{root vegetables} " [ •l " {not tled beet}" " {other vegetables}"

Matrix with 127 rules

5

Cii 4 I Q;_ c Q) 3 ~ 0" Q)

"' c 0 0 2

20 40 60 80 100 120

Antecedent (LHS)

10

~ 8 6

4

FIGURE 5-5 Matrix-based visualization of LHS and RHS, colored by lift and confidence

0.92 0.96

confidence

The following code provides a visual ization of the top five rules with the highest lift. The plot

is shown in Figure S-6. In the graph, the arrow always poi nts from an item on the LHS to an item on

the RHS. For example, the arrows that connect ham, processed cheese, and whi te bread suggest rule

{h a m, p rocessed cheese} -> {wh i te b read } . The legend on the top right of t he graph shows that the size of a circle indicates the support of the rules ranging from 0.001 to 0.002. The color

(or shade} represents the li ft, which ranges from 11.279 to 18.996. The ru le with the highes t lift is

{Insta n t food produ cts , soda} -> {h a mbur ger me a t} .

h ighLi ftRules c- head(sort (rules, by= " lift " ) , 5)

p lot(highLiftRules , method="graph" , cont r ol=lis t (type="items" ))

5.6 Validation and Testing

Graph for 5 rules size: support (0.001 · 0.002)

color: lift (11.279 -1 8.996)

tropical fruit other vegetables

processed cheese

ham

popcorn

t salty snack

wgite bread

soda

FIGURE 5-6 Graph visualization of the top five rules sorted by lift

5.6 Validation and Testing

yogurt

...... butter

1

~----whipped/sour cream

hamburger meat ~

Instant food products

After gathering the output rules, it may become necessary to use one or more methods to validate the

results in the business context for the sample dataset. The first approach can be established through

statistical measures such as confidence, lift, and leverage. Rules that involve mutua lly independent items

or cover few transactions are considered uninteresting because they may capture spurious relationships.

As mentioned in Section 5.3, confidence measures the chance that X andY appear together in rela-

tion to the chance X appears. Confidence can be used to identify the interestingness of the ru les.

Lift and leverage both compare the support of X andY against their individual support. While min- ing data with association rul es, some rules generated cou ld be purely coincidenta l. For example, if 95%

of customers buy X and 90% of customers buy Y, then X and Y would occur together at least 85% of the

time, even if there is no relationship between the two. Measures like lift and leverage ensure that inter-

esting rules are identified rather than coincidental ones.

Another set of criteria can be established through subjective arguments. Even with a high confidence,

a rule may be considered subjectively uninteresting unless it reveals any unexpected profitable actions.

For example, ru les like {paper}-+ { penci 1} may not be subjectively interesting or meaningful despite high support and confidence values. In contrast, a rule like {diaper}->{ beer} that satisfies both mini- mum support and minimum confidence can be considered subjectively interesting because this rule is

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

unexpected and may suggest a cross-sell opportunity for the retailer. This incorporation of subjective

knowledge into the evaluation of rules can be a difficult task, and it requires collaboration with domain

experts. As seen in Chapter 2, "Data Ana lytics Lifecycle," the domain experts may serve as the business

users or the business intelligence analysts as part of the Data Science team. In Phase 5, the team can com-

municate the results and decide if it is appropriate to operationalize them.

5.7 Diagnostics Although the Apriori algorithm is easy to understand and implement, some of the rules generated are

uninteresting or practically useless. Additionally, some of the rules may be generated due to coincidental

relationships between the variables. Measures like confidence, lift, and leverage should be used along with

human insights to address this problem.

Another problem with association rules is that, in Phase 3 and 4 of the Data Analytics Lifecycle

(Chapter 2), the team must specify the minimum support prior to the model execution, which may lead

to too many or too few rules. In related research, a variant of the algorithm [13] can use a predefined

target range for the number of rules so that the algorithm can adjust the minimum support accordingly.

Section 5.2 presented the Apriori algorithm, which is one of the earliest and the most fundamental

algorithms for generating association rules. The A priori algorithm reduces the computational workload by

only examining itemsets that meet the specified minimum threshold. However, depending on the size of the

dataset, the Apriori algorithm can be computationally expensive. For each level of support, the algorithm

requires a scan of the entire database to obtain the result. Accordingly, as the database grows, it takes more

time to compute in each run. Here are some approaches to improve Apriori's efficiency:

• Part itioning: Any item set that is potential ly frequent in a transaction database must be frequent in at least one of the partitions of the transaction database.

• Sa mpling: This extracts a subset of the data with a lower support threshold and uses the subset to perform association rule mining.

• Transaction reduction: A transaction that does not contain frequent k-itemsets is useless in sub- sequent scans and therefore can be ignored.

• Hash-based item set counting: If the corresponding hashing bucket count of a k-itemset is below a certain threshold, the k-itemset cannot be frequent.

• Dynamic itemset counting: Only add new candidate itemsets when all of their subsets are esti- mated to be frequent.

Summary As an unsupervised analysis technique that uncovers relationships among items, association rules find many

uses in activities, includ ing market basket analysis, clickstream analysis, and recommendation engines.

Although association ru les are not used to predict outcomes or behaviors, they are good at identifying

"interesting" relationships within items from a large dataset. Quite often, the disclosed relationships that

the association rules suggest do not seem obvious; they, therefore, provide va luable insights for institutions

to improve their business operations.

Exercises

The Apriori algorithm is one of the earliest and most fundamental algorithms for association rules. This

chapter used a grocery store example to walk through the steps of A priori and generate frequent k-itemsets

and useful rules for downstream analysis and visualization. A few measures such as support, confidence,

lift, and leverage were discussed. These measures together help identify the interesting ru les and elimi-

nate the coincidental rules. Finally, the chapter discussed some pros and cons of the Apriori algorithm and

highlighted a few methods to improve its efficiency.

Exercises 1. What is the Apriori property?

2. Following is a list of five transactions that include items A, B, C, and D:

• Tl : { A,B,C

• T2: { A,C }

• T3: { B,C }

• T4: { A,D }

• TS: { A,C,D

Which itemsets satisfy the minimum support of 0.5? (Hint: An item set may include more than one item.)

3. How are interesting rules identified? How are interesting rules distinguished from coincidental rules?

4. A local retailer has a database that stores 10,000 transactions of last summer. After analyzing the data, a data science team has identified the following statistics:

• { battery} appears in 6,000 transactions.

• {sunscreen} appears in 5,000 transactions.

• {sandals} appears in 4,000 transactions.

• {bowls} appears in 2,000 transactions.

• {battery, sunscreen} appears in 1,500 transactions.

• {battery, sandals} appears in 1,000 transactions.

• {battery, bowls} appears in 250 transactions.

• {battery, sunscreen, sandals} appears in 600 transactions.

Answer the following questions:

a. What are the support values of the preceding itemsets?

b. Assuming the minimum support is 0.05, which itemsets are considered frequent?

c. What are the confidence values of {battery}-> { sunscreen} and {battery, sunscreen}->{ sandals} ? Which of the two rules is more interesting?

d. List all the candidate rules that can be formed from the statistics. Which rules are cons idered interesting at the minimum confidence 0.25? Out of these interesting rules, which rule is con- sidered the most useful (that is, least coincidental)?

ADVANCED ANALYTICAL THEORY AND METHODS: ASSOCIATION RULES

Bibliography [1] P. Hajek, I. Havel, and M. Chytil, "The GUHA Method of Automatic Hypotheses Determination,"

Computing, vol. 1, no. 4, pp. 293-308, 1966.

[2] R. Agrawal, T. lmielinski, and A. Swami, "Mining Association Ru les Between Sets of Items in Large Databases," SIGMOD '93 Proceedings of the 1993 ACM SIGMOD International Conference on Management of Data, pp. 207-216,1993.

[3] M.-S. Chen, J. S. Park, and P. Yu, "Efficient Data Mining for Path Traversal Patterns," IEEE Transactions on Knowledge and Data Engineering, vol. 10, no. 2, pp. 209-221, 1998.

[4] R. Cooley, B. Mobasher, and J. Srivastava, "Web Mining: Information and Pattern Discovery on the World Wide Web," Proceedings of the 9th IEEE International Conference on Tools with Artificial Intelligence, pp. 558-567, 1997.

[5] R. Agrawal and R. Srikant, "Fast Algorithms for Mining Association Rules in Large Databases," in Proceedings of the 20th International Conference an Very Large Data Bases, San Francisco, CA, USA, 1994.

[6] S. Brin, R. Motwani, J.D. Ullman, and S. Tsur, "Dynamic ltemset Counting and Implication Rules for Market Basket Data," SIGMOD, vol. 26, no. 2, pp. 255-264, 1997.

[7] G. Piatetsky-Shapiro, "Discovery, Analysis and Presentation of Strong Rules," Knowledge Discovery in Databases, pp. 229-248, 1991.

[8] S. Brin, R. Motwani, and C. Silverstein, "Beyond Market Baskets: Generalizing Association Rules to Correlations," Proceedings of the ACM SIGMOD/PODS '97 Joint Conference, vol. 26, no. 2, pp. 265- 276, 1997.

[9] C. C. Aggarwal and P. S. Yu, "A New Framework for ltemset Generation," in Proceedings of the Seventeenth ACM SIGACT-SIGMOD-SIGART Symposium on Principles of Database Systems (PODS '98), Seattle, Washington, USA, 1998.

[1 O] M. Hahsler, "A Comparison of Commonly Used Interest Measures for Association Rules," 9 March 2011. [Online). Available: http: I / michael. hahsler . net / research/ association_rules / measures . html. [Accessed 4 March 2014).

[11] W. Lin, S. A. Alvarez, and C. Ruiz, "Efficient Adaptive-Support Association Rule Mining for Recommender Systems," Data Mining and Knowledge Discovery, vol. 6, no. 1, pp. 83-105,2002.

[12] B. Mobasher, H. Dai, T. Luo, and M. Nakagawa, "Effective Personalization Based on Association Rule Discovery from Web Usage Data," in ACM, 2011.

[13] W. Lin, S. A. Alvarez, and C. Ruiz, "Collaborative Recommendation via Adaptive Association Rule Mining," in Proceedings of the International Workshop on Web Mining forE-Commerce (WEBKDD), Boston, MA, 2000.

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

In general, regression analysis attempts to explain the influence that a set of variables has on the outcome of

another variable of interest. Often, the outcome variable is called a dependent variable because the out- come depends on the other variables. These additional variables are sometimes called the input variables or the independent variables. Regression analysis is useful for answering the following kinds of questions:

• What is a person's expected income?

• What is the probability that an applicant will default on a loan?

Linear regression is a useful tool for answering the first question, and logistic reg ression is a popular

method for addressing the second. This chapter examines these two regression techniques and explains when one technique is more appropriate than the other.

Regression analysis is a useful explanatory tool that can identify the input variables that have the great-

est statistica l influence on the outcome. With such knowledge and insight, environmental changes can be attempted to produce more favorable values of the input variables. For example, if it is found that the reading level of 10-year-old students is an excellent predictor of the students' success in high school and

a factor in their attending college, then additional emphasis on reading can be considered, implemented, and evaluated to improve students' reading levels at a younger age.

6.1 Linear Regression Linear regression is an analytical technique used to model the relationship between several input variables and a continuous outcome variable. A key assumption is that the relationship between an input variable and the outcome variable is linear. Although this assumption may appear restrictive, it is often possible to

properly transform the input or outcome variables to achieve a linear relationship between the modified

input and outcome variables. Possible transformations will be covered in more detail later in the chapter. The physical sciences have well-known linear models, such as Ohm's Law, which states that the electri-

ca l current flowing through a resistive circuit is linearly proportional to the voltage applied to the circuit.

Such a model is considered deterministic in the sense that if the input values are known, the value of the outcome variable is precisely determined. A linear regression model is a probabilistic one that accounts for the randomness that can affect any particular outcome. Based on known input values, a linear regression

model provides the expected value of the outcome variable based on the values of the input variables, but some uncertainty may remain in predicting any particular outcome. Thus, linear regression models are

useful in physical and social science applications where there may be considerable variation in a particular outcome based on a given set of input values. After presenting possible linear regression use cases, the foundations of linear regression modeling are provided.

6.1.1 Use Cases Linear regression is often used in business, government, and other scenarios. Some common practical applications of linear regression in the real world include the following:

• Real estate: A simple linear regression analysis can be used to model residential home prices as a function of the home's living area. Such a model helps set or evaluate the list price of a home on the market. The model could be further improved by including other input variables such as number of bathrooms, number of bed rooms, lot size, school district ran kings, crime statistics, and property taxes.

6.1 Linear Regression

o Demand forecasting: Businesses and governments can use linear regression models to predict demand for goods and services. For example, restaurant chains can appropriately prepare for the predicted type and quantity of food that customers will consume based upon the weather, the day of the week, whether an item is offered as a special, the time of day, and the reservation volume. Similar models can be built to predict retail sales, emergency room visits, and ambulance dispatches.

o Medical: A linear regression model can be used to analyze the effect of a proposed radiation treat- ment on reducing tumor sizes. Input variables might include duration of a single radiation treatment, frequency of radiation treatment, and patient attributes such as age or weight.

6.1.2 Model Description As the name of this technique suggests, the linear regression model assumes that there is a linear relation- ship between the input variables and the outcome variable. This relationship can be expressed as shown in Equation 6-1.

where: y is the outcome variable

xi are the input variables, for j = 1, 2, .. . , p- 1 {30 is the value of y when each xi equals zero

f]i is the change in y based on a unit change in xi' for j = 1, 2, .. • , p- 1 Eisa random error term that represents the difference in the linear model and a particular observed value for y

(6-1)

Suppose it is desired to build a linear regression model that estimates a person's annual income as a function of two variables-age and education-both expressed in years. In this case, income is the outcome variable, and the input variables are age and education. Although it may be an over generalization, such a model seems intuitively correct in the sense that people's income should increase as their skill set and experience expand with age. Also, the employment opportunities and starting salaries would be expected to be greater for those who have attained more education.

However, it is also obvious that there is considerable variation in income levels for a group of people with identical ages and years of education. This variation is represented byE in the model. So, in this example, the model would be expressed as shown in Equation 6-2.

(6-2)

In the linear model, the pis represent the unknown p parameters. The estimates for these unknown parameters are chosen so that, on average, the model provides a reasonable estimate of a person's income based on age and education. In other words, the fitted model should minimize the overall error between the linear model and the actual observations. Ordinary least Squares (OLS) is a common technique to estimate the parameters.

To illustrate how OLS works, suppose there is only one input variable, x, for an outcome variable y. Furthermore, n observations of { x, y) are obtained and plotted in Figure 6-1.

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

II) (")

0

0 0

0 (")

II') 0 N

>- 0 0 N 0 0 0

II)

0

II) 0

2 4 6 8 10 12

X

F1GURE6- Scatcerplot of y versus x

The goal is to find the line that best approximates the relationship between the outcome variable

and the input variables. With OLS, the objec tive is to find the line through these points tha t mini-

mizes the sum of the squa res of the difference between each point and the line in the ver tical direc-

tion. In other words, find the values of -10 and .-1, such that the summation shown in Equat ion 6-3 is minimized.

(6-3)

The n individual distances to be squared and then summed are illustrated in Figure 6-2. The vertical

lines represent the distance between each observed y value and the line y = i 0

;- i,x.

II) (")

0 (")

II) N

>- 0 N

II)

0

II)

2 4 6 8 10 12

X

FIGURE 6 2 Scatterplot of y versus x with vertical distances from the observed points to a fitted line

6.1 Linear Regression

In Figure 3-7 of Chapter 3, "Review of Basic Data Analytic Methods Using R," the Anscombe's Quartet example used OLS to fit the linear regression line to each of the four data sets. OLS for multiple input vari- ables is a straightforward extension of the one input variable case provided in Equation 6-3.

The preceding discussion provided the approach to find the best linear fit to a set of observations. However, by making some additional assumptions on the error term, it is possible to provide further capa- bilities in utilizing the linear regression model. In general, these assumptions are almost always made, so the following model, built upon the earlier described model, is simply called the linear regression model.

Linear Regression Model (with Normally Distributed Errors)

In the previous model description, there were no assumptions made about the error term; no additional assumptions were necessary for OLS to provide estimates of the model parameters. However, in most linear regression analyses, it is common to assume that the error term is a normally distributed random variable with mean equal to zero and constant variance. Thus, the linear regression model is expressed as shown in Equation 6-4.

Y = f3o + fJ1X1 + fJ2X2 •• .+ f3P-1xp- 1 +E

where: y is the outcome variable

xi are the input variables, for j = 1, 2, ... , p- 1

{30 is the value of y when each xi equals zero

{3i is the change in y based on a unit change in xi' for j = 1, 2, ... , p -1

E- N(O, U 2 ) and the ES are independent of each other

(6-4)

This additional assumption yields the following result about the expected value of y, E(y) for given (x1,x2, ... xP_ 1):

E(y) = E(/30 + (31x1 + {32x2 . .. + f)P_ 1xP_ 1 +c)

= !3o + !31x1 + j32x2 •.. + {3p-1xp-1 + E(c) = {30 + ~j1 x 1 + /32x2 ••• + f3P_ 1XP_ 1

Because {3. and x .are constants, the E(y) is the value of the linear regression model for the given J I

(x 1 ,x

2 , •• • xP_ 1). Furthermore, the variance ofy, V(y), for given (x1,x2, ••• xP _1) is this:

V(y) = V(f3o + (31x1 + /32x2 ... + !3p-1xp-1 +e) =0+V(c)=a2

Thus, for a given (x1,x2, . .. xP _1), y is normally distributed with mean /30 + /31x1 + ;32x2 ... + !3P _1xP_ 1 and variance a2• For a regression model with just one input variable, Figure 6-3 illustrates the normality assumption on the error terms and the effect on the outcome variable, y, for a given value of x.

For x = 8, one would expect to observe a value of y near 20, but a value of y from 15 to 25 would appear possible based on the illustrated normal distribution. Thus, the regression model estimates the expected value of y for the given value of x. Additionally, the normality assumption on the error term provides some useful properties that can be utilized in performing hypothesis testing on the linear regression model and

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

providing confidence intervals on the parameters and the mean ofy given(x1,x2, ... xP_,). The application of these statistical techniques is demonstrated by applying R to the earlier linear regression model on income.

10 (")

0 (")

10 N

>. 0 N

10

0

10

2 4 6

X

FIGURE 6-3 Normal distribution about y for a given value of x

ExampleinR

8 10 12

Returning to the Income example, in addition to the variables age and education, the person's gender, female or male, is considered an input variable. The following code reads a comma-separated-value (CSV) file of 1,500 people's incomes, ages, years of education, and gender. The first 10 rows are displayed:

income_input = as.data.frame( read. csv ( 11 C: /data/income. csv'') income_input[l:lO,]

ID Income Age Education Gender 1 1 113 69 12 1

2 2 91 52 18 0

121 65 14 0

4 4 81 58 12 0

5 5 68 31 16 1

6 6 92 51 15 1

7 7 75 53 15 0

8 8 76 56 13 0

9 9 56 42 15

10 10 53 33 11 1

Each person in the sample has been assigned an identification number, ID. Income is expressed in thousands of dollars. (For example, 113 denotes $113,000.) As described earlier, Age and Education are expressed in years. For Gender, a 0 denotes female and a 1 denotes male. A summary of the imported data reveals that the incomes vary from $14,000 to $134,000. The ages are between 18 and 70 years. The education experience for each person varies from a minimum of 10 years to a maximum of 20 years.

summary(income_input)

ID Income Age Education f>'lin. 1.0 !>lin. : 14.00 !>lin. :18.00 Min. :10.00

6.1 linear Regression

t Qu .

'1 X

As described in Chapter 3, a scatterplot matrix is an informative tool to view the pair-wise relationships of the variables. The basic assumption of a linear regression model is that there is a linear relationship

between the outcome variable and the input variables. Using the lattice package in R, the scatterplot matrix in Figure 6-4 is generated with the following R code:

co . OQOOt.:.•OQOOOO

Gender

0 OOOO t~t~OOOOO

0 ·~..O:'C .:K1D t~a=-:-mOEll> 0 0 ·-· ••Ill) C8111:111D~-~-= 0 0 ,;:a-••wllq, CD CICI!miDCilltmlll:llllro 0 0 « Ill! »c:::-=:ra::D~ G:II::C 0 0

0 0 0 c.:::o:,.~_.I::::.::t~'21C Educabon 0 'J

<DR ao --=-t- 0 0 ~=-::w:ca::::u:-= 0 0

0 0 0 0 0 CJ'> -==-=-=-=-=~.--s::a::. 0 0

0 0

~ £-~

Income -~ - ~ ~~~- --~-~ ... ~- ,· .. . '" -:~ ... .. ...

Scatter Plol l.lalnx

FIGURE 6-4 Scatterplot matrix of the variables

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

library(lattice)

splom(-income_input[c(2:5)], groups~NULL, data=income_input, axis.line.tck = 0, axis.text.alpha ~ 0)

Because the dependent variable is typically plotted along they-axis, examine the set of scatterplots along the bottom of the matrix. A strong positive linear trend is observed for Income as a function of Age. Against Education, a slight positive trend may exist, but the trend is not quite as obvious as is the case with the Age variable. Lastly, there is no observed effect on Income based on Gender.

With this qualitative understanding of the relationships between Income and the input variables, it seems reasonable to quantitatively evaluate the linear relationships of these variables. Utilizing the normal- ity assumption applied to the error term, the proposed linear regression model is shown in Equation 6-5.

Income= {30 + {31Age + !3iducation + {33Gender + E (6-5)

Using the linear model function, lm (),in R, the income model can be applied to the data as follows:

results <- lm(Income-Age + Education + Gender, income_input) summary(results)

Call:

lm(fornula Income - Age + Education ~ Gender, data incorne_input)

Residuals:

Min 1Q Median 3Q Max

-37.340 -8.101 0.139 7.885 37.271

Coefficients:

Estimate Std. Srro!.~ t value Pl.~ (>It i ) (Intercept) 7.26299 1.95575 3.714 0.000212

.~ge 0.99520 0.02057 48.373 < 2e-l6

Education 1.75788 0.11581 15.179 < 2e-16

Gender -0.93433 0.62388 -1.498 0.134443

Signif. codes: 0 '***' 0.001 '**' 0.01 '* 1 0.05 1 • 1 0.1 1 1 1

Residual standard error: 12.07 on 1496 degrees of freedom

Multiple R-squared: 0.6364, Adjusted R-squared: 0.6357

F-statistic: 873 on 3 and 1496 DF, p-value: < 2.2e-16

The intercept term, {30 , is implicitly included in the model. The lm {) function performs the parameter estimation for the parameters {3i (j = 0, 1, 2, 3) using ordinary least squares and provides several useful calculations and results that are stored in the variable called results in this example.

After the stated call to 1m ( } , a few statistics on the residuals are displayed in the output. The residuals are the observed values of the error term for each of then observations and are defined fori= 1, 2, ... n, as shown in Equation 6-6.

e; = Y; -(bo +blxi,l +b2xi,2 ... +bp-1xi,p-1)

where bi denotes the estimate for parameter {3i for j = 0, 1, 2, ... p - 1

(6-6)

6.1 Linear Regression

From the R output, the residuals vary from approximately -37 to +37, with a median close to 0. Recall that the residuals are assumed to be normally distributed with a mean near zero and a constant variance. The normality assumption is examined more carefully later.

The output provides details about the coefficients. The column Estimate provides the OLS estimates of the coefficients in the fitted linear regression model. In general, the (Intercept) corresponds to the estimated response variable when all the input variables equal zero. In this example, the intercept cor- responds to an estimated income of $7,263 for a newborn female with no education. It is important to note that the available dataset does not include such a person. The minimum age and education in the dataset are 18 and 10 years, respectively. Thus, misleading results may be obtained when using a linear regression model to estimate outcomes for input values not representative within the dataset used to train the model.

The coefficient for Age is approximately equal to one. This coefficient is interpreted as follows: For every one unit increase in a person's age, the person's income is expected to increase by $995. Similarly, for every unit increase in a person's years of education, the person's income is expected to increase by about $1,758.

Interpreting the Gender coefficient is slightly different. When Gender is equal to zero, the Gender coefficient contributes nothing to the estimate of the expected income. When Gender is equal to one, the expected Income is decreased by about $934.

Because the coefficient values are only estimates based on the observed incomes in the sample, there is some uncertainty or sampling error for the coefficient estimates. The Std. Error column next to the coefficients provides the sampling error associated with each coefficient and can be used to perform a hypothesis test, using the t-distribution, to determine if each coefficient is statistically different from zero. In other words, if a coefficient is not statistically different from zero, the coefficient and the associ- ated variable in the model should be excluded from the model. In this example, the associated hypothesis tests' p-values, Pr (>It I), are very small for the Intercept, Age, and Education parameters. As seen in Chapter 3, a small p-value corresponds to a small probability that such a large t value would be observed under the assumptions of the null hypothesis. In this case, for a givenj = 0, 1, 2, ... , p -1, the null and alternate hypotheses follow:

H0 : !3i = 0 versus HA: .Bi 7:0

For small p-values, as is the case for the Intercept, Age, and Education parameters, the null hypothesis would be rejected. For the Gender parameter, the corresponding p-value is fairly large at 0.13.1n other words, at a 90% confidence level, the null hypothesis would not be rejected. So, dropping the variable Gender from the linear regression model should be considered. The following R code provides the modified model results:

results2 <- lm(Income - Age + Education, income_input) summary(results2)

Call: lm(formula Income - Age + Education, data income_input)

Residuals: Min lQ Median 3Q Max

-36.889 -7.892 0.185 8.200 37.740

Coefficients: Estimate Std. Error t value Pr(>jtjl

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

(Intercept) 6.75822 1. 92728 3.507 0.000467 *** Age 0. 99603 0.02057 48.412 < 2e-16 *** Education 1.75860 0.11586 15.179 < 2e-16 ***

Signif. codes: 0 '***' 0.001 '**I 0.01 I* I 0.05 I I 0.1

Residual standard error: 12.08 on 1497 degrees of freedom Multiple R-squared: 0.6359, Adjusted R-squared: 0.6354 F-statistic: 1307 on 2 and 1497 DF, p-value: < 2.2e-16

I I 1

Dropping the Gender variable from the model resulted in a minimal change to the estimates of the remaining parameters and their statistical significances.

The last part of the displayed results provides some summary statistics and tests on the linear regression model. The residual standard error is the standard deviation of the observed residuals. This value, along with the associated degrees of freedom, can be used to examine the variance of the assumed normally distributed error terms. R-squared (R2) is a commonly reported metric that measures the variation in the data that is explained by the regression model. Possible values of R2 vary from 0 to 1, with values closer to 1 indicating that the model is better at explaining the data than values closer to 0. An R2 of exactly 1 indicates that the model explains perfectly the observed data (all the residuals are equal to O).ln general, the R2 value can be increased by adding more variables to the model. However, just adding more variables to explain a given dataset but not to improve the explanatory nature of the model is known as overfitting. To address the possibility of overfitting the data, the adjusted R2 accounts for the number of parameters included in the linear regression model.

The F-statistic provides a method for testing the entire regression model. In the previous t-tests, indi- vidual tests were conducted to determine the statistical significance of each parameter. The provided F-statistic and corresponding p-value enable the analyst to test the following hypotheses:

H0 :{31 =/32 = ... =f3P_1 =0 versus HA :{3i ::cO

foratleastone j =1, 2, ... , p-1

In this example, the p-value of 2.2e- 16 is small, which indicates that the null hypothesis should be rejected.

Categorical Variables

In the previous example, the variable Gender was a simple binary variable that indicated whether a person is female or male. In general, these variables are known as categorical variables. To illustrate how to use categorical variables properly, suppose it was decided in the earlier Income example to include an additional variable, State, to represent the U.S. state where the person resides. Similar to the use of the Gender variable, one possible, but incorrect, approach would be to include a State variable that would take a value of 0 for Alabama, 1 for Alaska, 2 for Arizona, and so on. The problem with this approach is that such a numeric assignment based on an alphabetical ordering of the states does not provide a meaningful measure of the difference in the states. For example, is it useful or proper to consider Arizona to be one unit greater than Alaska and two units greater that Alabama?

6.1 Linear Regression

In regression, a proper way to implement a categorical variable that can take on m different values is to add m-1 binary variables to the regression model. To illustrate with the Income example, a binary vari- able for each of 49 states, excluding Wyoming (arbitrarily chosen as the last of 50 states in an alphabetically sorted list), could be added to the model.

results3 <- lm(Income-Age + Education, + Alabama, + Alaska, + Arizona,

+ WestVirginia, + Wisconsin, income_ input)

The input file would have 49 columns added for these variables representing each of the first 49 states. If a person was from Alabama, the Alabama variable would be equal to 1, and the other 48 vari- ables would be set to 0. This process would be applied for the other state variables. So, a person from Wyoming, the one state not explicitly stated in the model, would be identified by setting all 49 state variables equal to 0. In this representation, Wyoming would be considered the reference case, and the regression coefficients of the other state variables would represent the difference in income between Wyoming and a particular state.

Confidence Intervals on the Parameters

Once an acceptable linear regression model is developed, it is often helpful to use it to draw some infer- ences about the model and the population from which the observations were drawn. Earlier, we saw that t-tests could be used to perform hypothesis tests on the individual model parameters, {3i, j = 0, 1, ... , p- 1. Alternatively, these t-tests could be expressed in terms of confidence intervals on the parameters. R simpli- fies the computation of confidence intervals on the parameters with the use of the conf int () function. From the Income example, the following R command provides 95% confidence intervals on the intercept and the coefficients for the two variables, Age and Education.

confint(results2, level = .95)

2.5 % 97.5 % (Intercept) 2.9777598 10.538690

Age 0.955677: 1.036392

Education 1.5313393 1.985862

Based on the data, the earlier estimated value of the Education coefficient was 1.76. Using conf int (),the corresponding 95% confidence interval is (1.53, 1.99), which provides the amount of uncertainty in the estimate. In other words, in repeated random sampling, the computed confidence interval straddles the true but unknown coefficient 95% ofthe time. As expected from the earlier t-test results, none ofthese confidence intervals straddles zero.

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

Confidence Interval on the Expected Outcome

In addition to obtaining confidence intervals on the model parameters, it is often desirable to obtain a confidence interval on the expected outcome. In the Income example, the fitted linear regression provides the expected income for a given Age and Education. However, that particular point estimate does not provide information on the amount of uncertainty in that estimate. Using the predict {) function in R, a confidence interval on the expected outcome can be obtained for a given set of input variable values.

In this illustration, a data frame is built containing a specific age and education value. Using this set of input variable values, the predict {) function provides a 95% confidence interval on the expected Income for a 41-year-old person with 12 years of education.

Age <- 41 Education <- 12 new_pt <- data.frame(Age, Education)

conf_int_pt <- predict(results2,new_pt,leve1=.95,interval= 11 Confidence 11 ) conf_int_pt

fit lwr upr 1 68.69884 67.83102 69.56667

For this set of input values, the expected income is $68,699 with a 95% confidence interval of ($67,831, $69,567).

Prediction Interval on a Particular Outcome

The previous confidence interval was relatively close{+/- approximately $900} to the fitted value. However, this confidence interval should not be considered as representing the uncertainty in estimating a par- ticular person's income. The predict {) function in R also provides the ability to calculate upper and lower bounds on a particular outcome. Such bounds provide what are referred to as prediction intervals. Returning to the Income example, in R the 95% prediction interval on the Income for a 41-year-old person with 12 years of education is obtained as follows:

pred_int_pt <- predict(results2,new_pt,leve1=.95,interval= 11 prediction 11 ) pred_int_pt

fit upr 1 68.69884 44.98867 92.40902

Again, the expected income is $68,699. However, the 95% prediction interval is ($44,988, $92,409). If the reason for this much wider interval is not obvious, recall that in Figure 6-3, for a particular input vari- able value, the expected outcome falls on the regression line, but the individual observations are normally distributed about the expected outcome. The confidence interval applies to the expected outcome that falls on the regression line, but the prediction interval applies to an outcome that may appear anywhere within the normal distribution.

Thus, in linear regression, confidence intervals are used to draw inferences on the popula- tion's expected outcome, and prediction intervals are used to draw inferences on the next possible outcome.

6.1 Linear Regression

6.1 .3 Diagnostics The use of hypothesis tests, confidence intervals, and prediction intervals is dependent on the model

assumptions being true. The following discussion provides some tools and techniques that can be used to

validate a fitted linear regression model.

Evaluating the Linearity Assumption

A major assumption in linear regression modeling is that the relationship between the input variables and

the outcome variable is linear. The most fundamental way to evaluate such a relationship is to plot the

outcome variable against each input variable. In the Income example, such scatterplots were generated in Figure 6-4. If the relationship between Age and Income is represented as illustrated in Figure 6-5, a linear model would not apply. In such a case, it is often useful to do any of the following:

• Transform the outcome variable.

• Transform the input variables.

• Add extra input variables or terms to the regression model.

Common transformations include taking square roots or the logarithm of the variables. Another option

is to create a new input variable such as the age squared and add it to the linear regression model to fit a

quadratic relationship between an input variable and the outcome.

0

"' 0 0

C1> 0 (X)

E 0

0 0 !: U)

0 <T

0

"' 0

20 30 40 50 60 70

Age

FIGURE 6·5 Income as a quadratic function of Age

Additional use of transformations will be considered when evaluating the residuals.

Evaluating the Residuals

As stated previously, it is assumed that the error terms in the linear regression model are normally distributed

with a mean of zero and a constant variance. If this assumption does not hold, the various inferences that

were made with the hypothesis tests, confidence intervals, and prediction intervals are suspect.

To check for constant variance across ally values along the regression line, use a simple plot of the residu-

als against the fitted outcome values. Recall that the residuals are the difference between the observed

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

outcome variables and the fitted value based on the OLS parameter estimates. Because of the importance

of examining the residuals, the lm () function in R automatically calculates and stores the fitted va lues

and the residuals, in the components fit ted. values and residuals in the output of the l m () function. Using the Income regression model output stored in resul ts2, Figure 6-6 was generated with the following R code:

with(results2 , { plot(fitted.values, residuals,ylim=c(-40,40) )

points(c(min(fitted .values) ,max(fitted.values)),

c(O,O) , type = "1") }l

0 '<T

0 N

V> ro :::J

0 "0 ' (ii

~ 0 Ci'

0 "'i

50 60 70 80 90

fitted.values

FIGURE 6-6 Residual plot indicating constant variance

100 11 0

The plot in Figure 6-6 indicates that regardless of income value along the fitted linear regression model, the residuals are observed somewhat evenly on both sides of the reference zero line, and the spread of the

residuals is fairly constant from one fitted value to the next. Such a plot would support the mean of zero and the constant variance assumptions on the error terms.

If the residual plot appeared like any of those in Figures 6-7 through 6-10, then some of the earlier

discussed transformations or possible input variable additions should be considered and attempted. Figure 6-7 illustrates the existence of a nonlinear t rend in the residuals. Figure 6-8 illustrates that the residuals are not centered on zero. Figure 6-9 indicates a linear trend in the residuals across the various

outcomes along the linear regression model. This plot may indicate a missing variable or term from the regression model. Figure 6-10 provides an example in which the variance of the error terms is not a constant but increases along the fitted linear regression model.

Evaluating the Normality Assumption

The residual plots are useful for confirming that the residuals were centered on zero and have a con-

stant varia nce. However, the normality assumption still has to be va lidated . As shown in Figure 6-11 , the foll owing R code provides a histogram plot of the residuals from resu l ts2, the output from the Income example:

hi st(results2$residuals , main="" )

6.1 Linear Regression

0 <D

VI 0 ro N ::J "0 ·;;;

0 ~ ":'

0 "?

70 75 80 85 90

fitted. values

FIGURE 6-7 Residuals with a nonlinear trend

0 "J"

0 VI N

ro ::J "0 0 ·;;; ~

0

0 "f

50 60 70 80 90 100 110

fi tted values

FIGURE 6-8 Residuals not centered on the zero line

0 "J"

0 VI N

ro ::J

0 "0 ·;;; ~

0 "f

50 60 70 80 90 100 110

fi tted values

F IGURE 6-9 Residuals with a linear trend

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESS ION

0 'l

0

"' N

ro ::l "0 0 iii ~

0 "'f

50 60

FIGURE 6-10 Residuals with nonconstant variance

0 1/) N

0 0 N

0 1/)

0 0

0 1/)

0

-40 -20

70 80

fined values

0

results2Sresaduals

FIGURE 6 11 Histogram of normally distributed residuals

0

90 100 110

20 40

From the histogram, it is seen that the residuals are centered on zero and appear to be symmet-

ric about zero, as one wou ld expect for a normally distributed random variable. Another option is

to examin e a Q-Q p lot that com pares the ob served d ata against the quantiles (Q) of the assumed

distribution. In R, the following cod e generates the Q-Q plot shown in Figure 6-12 for the residuals

from the Income example and provides the line that the points should fo llow for va lues from a normal distribution.

qqnorm(results2$residuals, ylab="Residual s•, main="" ) qqline(results2$residuals)

A Q-Q plot as provided in Figure 6-13 would indicate that additional refinement of the model is requi red

to achieve normally distributed error terms.

0 ~

0 N

<n (ij :J "0 0 ·u; Cl)

!r 0 ~

0

-3 -2 -1 0

Theoretical Quantiles

fiGURE 6-12 Q-Q plot of normally distributed residuals

0 N

<n (ij 0 :J "0 0 ·u;

<;' Cl) !r

0 '9

0 0

-3 -2 -1 0

Theoretical Quantiles

fiGURE 6-13 Q-Q plot of non-normally distributed residuals

N-Fold Cross-Validation

6.1 Linear Regression

0

2 3

2 3

To prevent overfilling a given dataset, a common practice is to randomly split the entire dataset into a

train ing set and a testing set. Once the model is developed on the training set, the model is evaluated

against the testing set. When there is not enough data to create training and testing sets, anN-fold cross-

validation technique may be helpful to compare one fitted model against another. InN-fold cross-val idation,

the following occurs:

• The entire dataset is randomly split into N data sets of approximately equal size.

• A model is trained against N- 1 of these datasets and tested against the remaining dataset. A mea- sure of the model error is obtained.

• This process is repeated a total of N times across the various combinations of N datasets taken N- 1 at a time. Reca ll:

• The observed N model errors are averaged over theN folds.

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

The averaged error from one model is compared against the averaged error from another model. This technique can also help determine whether adding more variables to an existing model is beneficial or

possibly overfitting the data.

Other Diagnostic Considerations

Although a fitted linear regression model conforms with the preceding diagnostic criteria, it is possible to

improve the model by including additional input variables not yet considered. In the previous Income example, only three possible input variables-Age, Education, and Gender-were considered. Dozens of other additional input variables such as Housing or Marital_ Status may improve the fitted model. It is important to consider all possible input variables early in the analytic process.

As mentioned earlier, in reviewing the R output from fitting a linear regression model, the adjusted

R2 applies a penalty to the R2 value based on the number of parameters added to the model. Because the R2 value will always move closer to one as more variables are added to an existing regression model, the

adjusted R2 value may actually decrease after adding more variables. The residual plots should be examined for any outliers, observed points that are markedly different

from the majority of the points. Outliers can result from bad data collection, data processing errors, or an actual rare occurrence. In the Income example, suppose that an individual with an income of a million dollars was included in the dataset. Such an observation could affect the fitted regression model, as seen

in one of the examples of Anscombe's Quartet. Finally, the magnitudes and signs of the estimated parameters should be examined to see if they make

sense. For example, suppose a negative coefficient for the Education variable in the Income example was obtained. Because it is natural to assume that more years of education lead to higher incomes, either something very unexpected has been discovered, or there is some issue with the model, how the data was

collected, or some other factor. In either case, further investigation is warranted.

6.2 Logistic Regression In linear regression modeling, the outcome variable is a continuous variable. As seen in the earlier Income example, linear regression can be used to model the relationship between age and education to income. Suppose a person's actual income was not of interest, but rather whether someone was wealthy or poor. In

such a case, when the outcome variable is categorical in nature, logistic regression can be used to predict the likelihood of an outcome based on the input variables. Although logistic regression can be applied to an outcome variable that represents multiple values, the following discussion examines the case in which the outcome variable represents two values such as true/ false, pass/fail, or yes/no.

For example, a logistic regression model can be built to determine if a person will or will not purchase

a new automobile in the next 12 months. The training set could include input variables for a person's age, income, and gender as well as the age of an existing automobile. The training set would also include the

outcome variable on whether the person purchased a new automobile over a 12-month period. The logis- tic regression model provides the likelihood or probability of a person making a purchase in the next 12 months. After examining a few more use cases for logistic regression, the remain ing portion of this chapter examines how to build and evaluate a logistic regression model.

6.2 Logistic Regression

6.2.1 Use Cases The logistic regression model is applied to a variety of situations in both the public and the private sector.

Some common ways that the logistic regression model is used include the following:

• Medical: Develop a model to determine the likelihood of a patient's successful response to a specific medical treatment or procedure. Input variables could include age, weight, blood pressure, and cho- lesterol levels.

• Finance: Using a loan applicant 's credit history and the details on the loan, determine the probabil- ity that an applicant will default on the loan. Based on the prediction, the loan can be approved or denied, or the terms can be modified.

• Marketing: Determine a wireless customer's probability of switching carriers (known as churning) based on age, number of family members on the plan, months remaining on the existing contract, and social network contacts. With such insight, target the high-probability customers with appropri- ate offers to prevent churn.

• Engineering: Based on operating conditions and various diagnostic measurements, determine the probability of a mechanical part experiencing a malfunction or failure. With th is probability estimate, schedule the appropriate preventive maintenance activity.

6.2.2 Model Description Logistic regression is based on the logistic function f(y), as given in Equation 6-7.

eY f(y) = for - < y < x

1+ eY (6-7)

Note that as y _, , f(y) -> 1, and as y _,- , f(y) -+ 0. So, as Figure 6-14 illustrates, the va lue of the

logistic function f(y) varies from 0 to 1 as y increases.

0

(I)

z: c)

a. (0 )(

C1l 0 +

:::;: '<I' 2= 0 a. )( C1l N

c)

0 0

-2 0 2 4

y

FIGURE 6-14 The logistic function

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

Because the range of f(y) is (0, 1), the logistic function appears to be an appropriate function to model the probability of a particular outcome occurring. As the value of y increases, the probability of the outcome occurring increases. In any proposed model, to predict the likelihood of an outcome, y needs to be a func- tion of the input variables. In logistic regression, y is expressed as a linear function of the input variables. In other words, the formula shown in Equation 6-8 applies.

(6-8)

Then, based on the input variables x1,x2, •• • ,xP_ 1, the probability of an event is shown in Equation 6-9.

eY p(x1.x2, ... ,xP_ 1)=f(y)= 1

+eY for-oo<y<oo (6-9)

Equation 6-8 is comparable to Equation 6-1 used in linear regression modeling. However, one difference is that the values of yare not directly observed. Only the value of f(y) in terms of success or failure (typically expressed as 1 or 0, respectively) is observed.

Using p to denotef(y), Equation 6-9 can be rewritten in the form provided in Equation 6-10.

In[ l~p )= y= {10 + fl,x, + {i,x, ... +fl,x, .1 (6-10) The quantity In( 1 ~ P ), in Equation 6-10 is known as the log odds ratio, or the log it of p. Techniques such

as Maximum Likelihood Estimation (MLE) are used to estimate the model parameters. MLE determines the values of the model parameters that maximize the chances of observing the given dataset. However, the specifics of implementing MLE are beyond the scope of this book.

The following example helps to clarify the logistic regression model. The mechanics of using R to fit a logistic regression model are covered in the next section on evaluating the fitted model. In this section, the discussion focuses on interpreting the fitted model.

Customer Churn Example

A wireless telecommunications company wants to estimate the probability that a customer will churn (switch to a different company) in the next six months. With a reasonably accurate prediction of a person's likelihood of churning, the sales and marketing groups can attempt to retain the customer by offering various incentives. Data on 8,000 current and prior customers was obtained. The variables collected for each customer follow:

o Age (years)

o Married(true/false)

o Duration as a customer (years)

o Churned_ con tact s (count)-Number ofthe customer's contacts that have churned (count)

o Churned (true/false)-Whether the customer churned

After analyzing the data and fitting a logistic regression model, Age and Churned_ contacts were selected as the best predictor variables. Equation 6-11 provides the estimated model parameters.

y = 3.50 - 0.16 *Age + 0.38 *Churned_ contacts (6-11)

6.2 Logistic Regression

Using the fitted model from Equation 6-11, Table 6-1 provides the probability of a customer churning based on the customer's age and the number of churned contacts. The computed values of y are also provided in the table. Recalling the previous discussion of the logistic function, as the value of y increases, so does the probability of churning.

TABLe 6-1 Estimated Churn Probabilities

Customer Age (Years) Churned_ Contacts y Prob. of Churning

so -4.12 0.016

2 50 3 -3.36 0.034

3 so 6 -2.22 0.098

4 30 -0.92 0.28S

5 30 3 -0.16 0.460

6 30 6 0.98 0.727

7 20 0.68 0.664

8 20 3 1.44 0.808

9 20 6 2.58 0.930

Based on the fitted model, there is a 93% chance that a 20-year-old customer who has had six contacts churn will also churn. (See the last row ofT able 6-1.) Examining the sign and values of the estimated coef- ficients in Equation 6-11, it is observed that as the value of Age increases, the value ofy decreases. Thus, the negative Age coefficient indicates that the probability of churning decreases for an older customer. On the other hand, based on the positive sign of the Churned_ Contacts coefficient, the value of y and subsequently the probability of churning increases as the number of churned contacts increases.

6.2.3 Diagnostics The churn example illustrates how to interpret a fitted logistic regression model. Using R, this section examines the steps to develop a logistic regression model and evaluate the model's effectiveness. For this example, the churn_ input data frame is structured as follows:

head(churn_input)

ID Churned .l\ge t·larried Cust _;.·ears Churned - con:::acts l 0 61

2 2 0 50 2

3 0 47 l 2 0

' ·l 0 50

5 5 0 29

6 6 0 .;3 4

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

A Churned value of 1 indicates that the customer churned. A Churned value of 0 indicates that the customer remained as a subscriber. Out ofthe 8,000 customer records in this dataset, 1,743 customers (-22%) churned.

sum(churn_input$Churned)

[1] 1743

Using the Generalized Linear Model function, glm (),in Rand the specified family/link, a logistic regression model can be applied to the variables in the dataset and examined as follows:

Churn_logisticl <- glm (Churned-Age + Married + Cust_years + Churned_contacts, data;churn_input, family;binomial(link;"logit"))

surnmary(Churn_logisticl)

Coefficients:

Estimate Std. Errol- z value Pr(>fz )

(Intercept) 3.415201 0.163734 20.858 <2e-:.6

Age -0.156643 0.004088 -38.320 <2e-:6

l·larried 0.066432 0.068302 0.973 0.331

Cust _years 0.017857 0.030497 0.586 0.558

Churned contacts 0.382324 0.027313 13. 998 <2e-16 -

Signif. codes: o 1 *** 1 0.001 1 ** 1 0.01 1 * 1 0.05 1 • 1 0.1 I I 1

As in the linear regression case, there are tests to determine if the coefficients are significantly differ- ent from zero. Such significant coefficients correspond to small values of Pr ( > I z I } , which denote the p-value for the hypothesis test to determine if the estimated model parameter is significantly different from zero. Rerunning this analysis without the Cust_years variable, which had the largest corresponding p-value, yields the following:

Churn_logistic2 <- glm (Churned-Age + Married + Churned_contacts, data=churn_input, family=binomial(link="logit"))

summary(Churn_logistic2)

Coefficients:

Estimate stc. Error z ·la l ue Pr: > i z I', (Intercept l 3.472062 C.132107 26.282 <2e-16

Age -).156635 C.004088 -38.318 <2e-16

Narried ).066430 C.068299 0.973 0. 331

Churned contacts ).381909 0.027302 13.988 <2e-.;.6 -

Signif. codes: 0 1 *** 1 0.001 1 ** 1 0.01 1 * 1 0.05 '. 1 0.1 1 1 1

Because the p-value for the Married coefficient remains quite large, the Married variable is dropped from the model. The following R code provides the third and final model, which includes only the Age and Churned_ contacts variables:

Churn_logistic3 <- glm (Churned-Age + Churned_contacts,

6.2 Logistic Regression

data=churn_input, family=binomial(link= 11 logit 11 )) summary(Churn_logistic3)

Call: glm(formula Churned - Age + Churned_contacts,

family binomial(link = "logit"), data churn_input}

Deviance Residuals: Min 1Q Median 3Q Max

-2.4599 -0.5214 -0.1960 -0.0736 3.3671

Coefficients: Estimate Std. Error z value Pr ( > i z I}

(Intercept} 3. 502716 0.128430 27.27 <2e-16 Age -0.156551 0.004085 -38.32 <2e-16 *** Churned_contacts 0.381857 O.C27297 13.99 <2e-16 ***

Signif. codes: 0 1 *** 1 0.001 1 ** 1 0.01 '*' 0.05 '. 1 0.1 1 1 1

(Dispersion parameter for binomial family taken to be 1}

Null deviance: 8387.3 on 7999 degrees of freedom Residual deviance: 5359.2 on 7997 degrees of freedom AIC: 5365.2

Number of Fisher Scoring iterations: 6

For this final model, the entire summary output is provided. The output offers several values that can be used to evaluate the fitted model. It should be noted that the model parameter estimates correspond to the values provided in Equation 6-11 that were used to construct Table 6-1.

Deviance and the Pseudo-R2

In logistic regression, deviance is defined to be -2* logL, where Lis the maximized value ofthe likelihood function that was used to obtain the parameter estimates. In the R output, two deviance values are pro- vided. The null deviance is the value where the likelihood function is based only on the intercept term (y = /3~. The residual deviance is the value where the likelihood function is based on the parameters in the specified logistic model, shown in Equation 6-12.

y = /30 + /31 *Age + /32 *Churned_ contacts

A metric analogous to R2 in linear regression can be computed as shown in Equation 6-13.

d R2 1 residual dev.

pseu o- = ----- null dev.

null dev. - res. dev. null dev.

(6-12)

(6-13)

The pseudo-R2 is a measure of how well the fitted model explains the data as compared to the default model of no predictor variables and only an intercept term. A pseudo-R2 value near 1 indicates a good fit over the simple null model.

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

Deviance and the Log-Likelihood Ratio Test

In the pseudo-R2 calculation, the -2 multipliers simply divide out. So, it may appear that including such a multiplier does not provide a benefit. However, the multiplier in the deviance definition is based on the log-likelihood test statistic shown in Equation 6-14:

T = -2 *log [ Lnull l Lair.

= -2*1og(Lnull) -(-2)*1og(L011) (6-14)

where Tis approximately Chi-squared distributed (x~) with

k degrees of freedom (df) = dfnuJJ - dfalremare The previous description of the log-likelihood test statistic applies to any estimation using MLE. As can

be seen in Equation 6-15, in the logistic regression case,

T =null deviance- residual deviance- x~ _ 1

(6-15)

where p is the number of parameters in the fitted model.

So, in a hypothesis test, a large value ofT would indicate that the fitted model is significantly better than the null model that uses only the intercept term.

In the churn example, the log-likelihood ratio statistic would be this: T = 8387.3- 5359.2 = 3028.1 with 2 degrees of freedom and a corresponding p-value that is essentially

zero. So far, the log-likelihood ratio test discussion has focused on comparing a fitted model to the default

model of using only the intercept. However, the log-likelihood ratio test can also compare one fitted model to another. For example, consider the logistic regression model when the categorical variable Married is included with Age and Churned_ contacts in the list of input variables. The partial R output for such a model is provided here:

summary(Churn_logistic2} Call: glm(formula = Churned - Age + 1'-larried + Churned_conta::::ts,

family = binom:.al (1 ink = "logi t") , data = churn_input)

Coefficients: Estimate Std. Error z value Pr (>I z I)

(Intercept) 3.472062 0.132107 26.282 <2e-15 *** Age -0.156635 0.004088 -38.318 <2e-15 *** Married 0.066430 0.068299 0.973 0.331 Churned contacts 0.381909 0.027302 13. 988 <2e-16 ***

Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' D.l' '1

(Dispersion parameter for bino~ial family taken to be 1)

Null deviance: 8387.3 on 7999 degrees of freedom Residual deviance: 5358.3 on 7996 degrees of freedom

6.2 Logistic Regression

The residual deviances from each model can be used to perform a hypothesis test where H0 : f3Morried = 0 against H A : f3Married ;c 0 using the base model that includes the Age and Churned_ contacts variables. The test statistic follows:

T = 5359.2- 5358.3 = 0.9 with 7997- 7996 = 1 degree of freedom Using R, the corresponding p-value is calculated as follows:

pchisq(.9 , 1, lower=FALSE)

[1] 0.3427817

Thus, at a 66% or higher confidence level, the null hypothesis, H0 : ('JMarried = 0, would not be rejected. Thus, it seems reasonable to exclude the variable Married from the logistic regression model.

In general, this log-likelihood ratio test is particularly useful for forward and backward step-wise meth- ods to add variables to or remove them from the proposed logistic regression model.

Receiver Operating Characteristic (ROC) Curve

logistic regression is often used as a classifier to assign class labels to a person, item, or transaction based on the predicted probability provided by the model. In the Churn example, a customer can be classified with the label called Churn if the logistic model predicts a high probability that the customer will churn. Otherwise, a Remain label is assigned to the customer. Commonly, 0.5 is used as the default probability threshold to distinguish between any two class labels. However, any threshold value can be used depending on the preference to avoid false positives (for example, to predict Churn when actu- ally the customer will Remain) or false negatives (for example, to predict Remain when the customer will actually Churn).

In general, for two class labels, C and •C, where "•C" denotes "not C," some working definitions and formulas follow:

o True Positive: predict C, when actually C

o True Negative: predict •C, when actually •C

o False Positive: predict C, when actually •C

o False Negative: predict •C, when actually C

F I P . . R (FPR) # of false positives a se os1t1ve ate = f # o negatives

1i P .t. R t (TPR) # of true positives rue os1 1ve: a e = ----=---- # of positives

(6-16)

(6-17)

The plot of the True Positive Rate (TPR) against the False Positive Rate (FPR) is known as the Receiver Operating Characteristic (ROC) curve. Using the ROCR package, the following R commands generate the ROC curve for the Churn example:

library (ROCR)

pred = predict(Churn_logistic3, type="response")

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

predObj = prediction(pred, churn_input$Churned )

rocObj aucObj

performance(predObj, measure="tpr", x . measure="fpr") performance(predObj, measure= "auc")

plot(rocObj, main= paste( "Area under the curve:", round([email protected][[l]] ,4)))

The usefulness of this plot in Figure 6-15 is that the preferred outcome of a classifier is to have

a low FPR and a high TPR. So, when moving from left to right on the FPR axis, a good mode l/

classifier has the TPR rapidly approach values near 1, with only a small change in FPR. The closer the

ROC curve tracks along the vertical axis and approaches the upper-left hand of the plot, near the

point (0,1), the better the model/classifier performs. Thus, a useful metric is to compute the area under

the ROC curve (AUC). By examining the axes, it ca n be seen that the theoretical maximum for t he

area is 1.

~ ~ Q)

> = ·u; 0 a. Q)

2 1-

(X)

0 <0 0

~ 0

0 0

0.0

Aiea under the Curve = 0.8877

0.2 0.4 0.6

False positive rate

FIGURE 6-15 ROC curve for the churn example

0.8 1.0

To illustrate how the FPR and TPR values are dependent on the threshold value used for the classifier,

the plot in Figure 6-16 was constructed using the following R code:

~extract the alpha(threshold), FPR, and TPR values from rocObj alpha<- round(as . numeric(unlist([email protected])),4) fpr <- round(as .numeric(unlist([email protected])),4) tpr <- round(as .nume ric(unlist([email protected])),4)

# adjust margins a:1d plot TPR a nd FPR par(mar = c(5,5 , 2 , 5)) plot(alpha,tpr, xlab= "Threshold" , xlim=c(O,l),

ylab="True positive rate " , type= "l " ) par (new="True " ) plot(alpha,fpr, xlab=" " , ylab="", axes=F, xlim=c(O,l), t ype= "l " ) axis(side=4) mtext(side=4, line=3, "False positive rate" ) text(0.18 , 0.18, "FPR") text(0.58 , 0.58 , "TPR")

6 .2 Logist ic Regression

~

Q)

co ci

"§ Q) ~ >

:OJ 0

·u; 0 "<I; a. Q) 0

2 I- N

ci

~ 0

0.0 0.2 0.4 0.6

Threshold

FiGURE 6-16 The effect of the threshold value in the churn example

~

<X:l 0 2

~ ~ Q) > 0 . .,

·u; "<I;

0 a.

0 Q) V>

ro N u. ci

~ 0

0.8 1.0

For a threshold value ofO, every item is classified as a positive outcome. Thus, the TPR value is 1. However,

all the negatives are also classified as a positive, and the FPR value is also 1. As the threshold value increases, more and more negative class labels are assigned. Thus, the FPR and TPR values decrease. When the thresh- old reaches 1, no positive labels are assigned, and the FPR and TPR va lues are both 0.

For the purposes of a classifier, a commonly used threshold value is 0.5. A positive label is assigned for any probability of0.5 or greater. Otherwise, a negative label is assigned. As the following R code illustrates, in the analysis of the Churn dataset, the 0.5 threshold corresponds to a TPR va lue of 0.56 and a FPR value of 0.08.

i < - which(round(alpha,2) == . 5)

paste( "Thr e shold=", (alpha[i ] ), "TPR=" , t p r[i ] , "FPR=", f pr li])

'.] "ThrE'sh "d n.c."

Thus, 56% of customers who will churn are properly classified with the Churn label, and 8% of the customers who wi ll remain as customers are improperly labeled as Churn. If identifying only 56% of the churners is not acceptable, then the threshold could be lowered. For example, suppose it was decided to classify with a Churn label any customer with a probabi lity of churning greater than 0.15. Then the fol- lowing R code indicates that the corresponding TPR and FPR values are 0.91 and 0.29, respectively. Thus,

91% of the customers who will churn are properly identified, but at a cost of misclassifying 29% of the

customers who will remain.

i < - which(round(alpha,2) == .15 ) paste( "Threshold=", (alpha[i]), " TPR=", t p r[i] , "FPR=", fpr[i])

,1] "Threshold- O. l5•l3 TPR- 0.9116 F?R= .286 .. " ~2] "Threshold 0 . 1518 TPR 0. 0 12::! FPR= 0 . 28-5" [3] "Threshold= 0.1·179 TPR= 0 . q1·l5 F?R= 0 . 2942 11

[4] "Threshold- 0 . 14r.5 TPR- o . q174 FPR 0. 2°8,"

The ROC curve is useful fo r evaluating other classifiers and wi ll be utilized again in Chapter 7, "Advanced

Analytical Theory and Methods: Classification."

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

3000-.

: ooo ...

'E ::J 0 u

1000

0

Histogram of the Probabilities

It can be useful to visualize the observed responses against the estimated probabili ties provided by the logistic regression. Figure 6-17 provides overlaying histograms for the customers who churned and for the customers who remained as customers. With a proper fitting logistic model, the customers who remained

tend to have a low probability of churning. Conversely, the customers who churned have a high probability of churning again. This histogram plot helps visualize the number of items to be properly classified or mis-

classified.ln the Churn example, an ideal histogram plot would have the remaining customers grouped at the left side of the plot, the customers who churned at the right side of the plot, and no overlap of these

two groups.

000 0 25 050

Probabrllry 0 75

C., L>ff"ed

R•"'-'"ed

1.00

FIGURE 6-17 Customer counts versus estimated churn probability

6.3 Reasons to Choose and Cautions Linear regression is suitable when the input variables are continuous or discrete, including categorical data types, but the outcome variable is continuous. If the outcome variable is categorical, logistic regression

is a better choice. Both models assume a linear additive function of the input variables. If such an assumption does not

hold true, both regression techniques perform poorly. Furthermore, in linear regression, the assumption of normally distributed error terms with a constant variance is important for many of the statistica l inferences that can be considered. If the various assumptions do not appear to hold, the appropriate transformations need to be applied to the data.

6.4 Additional Regression Models

Although a collection of input variables may be a good predictor for the outcome variable, the analyst should not infer that the input variables directly cause an outcome. For example, it may be identified that those individuals who have regular dentist visits may have a reduced risk of heart attacks. However, simply

sending someone to the dentist almost certainly has no effect on that person's chance of having a heart

attack. It is possible that regular dentist visits may indicate a person's overall health and dietary choices, which may have a more direct impact on a person's health. This example illustrates the commonly known expression, "Correlation does not imply causation."

Use caution when applying an already fitted model to data that falls outside the dataset used to train

the model. The linear relationship in a regression model may no longer hold at va lues outside the training dataset. For example, if income was an input variable and the va lues of income ranged from $35,000 to $90,000, applying the model to incomes well outside those incomes could result in inaccurate estimates

and predictions. The income regression example in Section 6.1.2 mentioned the possibility of using categorical variables

to represent the 50 U.S. states. In a linear regression model, the state of residence would provide a simple addi tive term to the income model but no other impact on the coefficients of the other input variables,

such as Age and Education. However, if state does influence the other variables' impact to the income model, an alternative approach would be to build 50 separate linear regression models: one model for each state. Such an approach is an example of the options and decisions that the data scientist must be

willing to consider. If several of the input variables are highly correlated to each other, the condition is known as

multicollinearity. Multicollinearity can often lead to coefficient estimates that are relatively large in abso-

lute magnitude and may be of inappropriate direction (negative or positive sign). When possible, the major-

ity of these correlated variables should be removed from the model or replaced by a new variable that is a function of the correlated variables. For example, in a medical application of regression, height and weight may be considered important input va riables, but these variables tend to be correlated. In this

case, it may be useful to use the Body Mass Index (BMI), which is a function of a person's height and weight.

BMI = weight where weight is in kilograms and height is in meters height2

However, in some cases it may be necessary to use the correlated variables. The next section provides some techniques to address highly correlated variables.

6.4 Additional Regression Models In the case of multicollinearity, it may make sense to place some restrictions on the magnitudes of the estimated coefficients. Ridge regression, which applies a penalty based on the size of the coefficients, is one technique that can be applied. In fitting a linear regression model, the objective is to find the values of the coefficients that minimize the sum of the residuals squared. In ridge regression, a penalty term proportional to the sum of the squares of the coefficients is added to the sum of the residuals squared.

Lasso regression is a related modeling technique in which the penalty is proportional to the sum of the absolute values of the coefficients.

ADVANCED ANALYTICAL THEORY AND METHODS: REGRESSION

Only binary outcome variables were examined in the use of logistic regression. if the outcome variable

can assume more than two states, multinomial logistic regression can be used.

Summary This chapter discussed the use of linear regression and logistic regression to model historical data and to

predict future outcomes. Using R, examples of each regression technique were presented. Several diag- nostics to evaluate the models and the underlying assumptions were covered.

Although regression analysis is relatively straightforward to perform using many existing software pack- ages, considerable care must be taken in performing and interpreting a regression analysis. This chapter

highlighted that in a regression analysis, the data scientist needs to do the following:

• Determine the best input variables and their relationship to the outcome variable.

• Understand the underlying assumptions and their impact on the modeling results.

• Transform the variables, as appropriate, to achieve adherence to the model assumptions.

• Decide whether building one comprehensive model is the best choice or consider building many models on partitions of the data.

Exercises 1. In the Income linear regression example, consider the distribution of the outcome variable Income.

Income values tend to be highly skewed to the right (distribution of va lue has a large tail to the right). Does such a non-normally distributed outcome variable violate the general assumption of a linear regression model? Provide supporting arguments.

2. In the use of a categorica l variable with n possible va lues, explain the following:

a. Why only n - 1 binary variables are necessary

b. Why using n variables would be problematic

3. In the example of using Wyoming as the reference case, discuss the effect on the estimated model

parameters, includ ing the intercept, if another state was selected as the reference case.

4. Describe how logistic regression can be used as a classifier.

5. Discuss how the ROC curve can be used to determine an appropriate threshold value for a classifier.

6. If the probability of an event occurring is 0.4, then

a. What is the odds ratio?

b. What is the log odds ratio?

7. If b3 = - .5 is an estimated coefficient in a linear regression model, what is the effect on the odds ratio for every one unit increase in the value of x3?

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

In addition to analytical methods such as clustering (Chapter 4, "Advanced Analytical Theory and Methods: Clustering"), association rule learning Chapter 5, "Advanced Analytical Theory and Methods: Association Rules", and modeling techniques like regression (Chapter 6, "Advanced Analytical Theory and Methods:

Regression"), classification is another fundamental learning method that appears in applications related to data mining. In classification learning, a classifier is presented with a set of examples that are already classified and, from these examples, the classifier learns to assign unseen examples. In other words, the

primary task performed by classifiers is to assign class labels to new observations. Logistic regression

from the previous chapter is one of the popular classification methods. The set of labels for classifiers is predetermined, unlike in clustering, which discovers the structure without a tra ining set and allows the

data scientist optionally to create and assign labels to the clusters. Most classification methods are supervised, in that they start with a training set of prelabeled observa-

tions to learn how likely the attributes of these observations may contribute to the classification of future unlabeled observations. For example, existing marketing, sales, and customer demographic data can be used to develop a classifier to assign a "purchase" or "no purchase" label to potential future customers.

Classification is widely used for prediction purposes. For example, by building a classifier on the tran-

scripts of United States Congressional floor debates, it can be determined whether the speeches represent support or opposition to proposed legislation [1]. Classification can help health care professionals diagnose heart disease patients [2]. Based on an e-mail's content, e-mail providers also use classification to decide

whether the incoming e-mail messages are spam [3]. This chapter mainly focuses on two fundamental classification methods: decision trees and

nai"ve Bayes.

7.1 Decision Trees A decision tree (also called prediction tree) uses a tree structure to specify sequences of decisions and consequences. Given input X = {x1, x1 , ••• xn) , the goal is to predict a response or output variable Y. Each memberofthe set { x

1 ,x

1 , ... xn} is called an input variable. The prediction can be achieved by constructing

a decision tree with test points and branches. At each test point, a decision is made to pick a specific branch and traverse down the tree. Eventually, a final point is reached, and a prediction can be made. Each test

point in a decision tree involves testing a particular input variable (or attribute), and each branch represents

the decision being made. Due to its flexibility and easy visualization, decision trees are commonly deployed in data mining applications for classification purposes.

The input values of a decision tree can be categorical or continuous. A decision tree employs a structure of test points (ca lled nodes) and branches, which represent the decision being made. A node without fur- ther branches is called a l eaf node. The leaf nodes return class labels and, in some implementations, they return the probability scores. A decision tree can be converted into a set of decision rules. In the following example rule, income and mortgage_ amount are input variables, and the response is the output variable default with a probability score.

IF .1. ·om

THEN l<>f tu. t Tt•.te WITH PROBABILITY 75%

7.1 Decision Trees

Decision trees have two varieties: classification trees and regression trees. Classification trees usu- ally apply to output variables that are categorical-often binary-in nature, such as yes or no, purchase or not purchase, and so on. Regression trees, on the other hand, can apply to output variables that are numeric or continuous, such as the predicted price of a consumer good or the likelihood a subscription will be purchased.

Decision trees can be applied to a variety of situations. They can be easily represented in a visual way, and the corresponding decision rules are quite straightforward. Additionally, because the result is a series of logical if- then statements, there is no underlying assumption of a linear (or nonlinear) relationship between the input variables and the response variable.

7.1.1 Overview of a Decision Tree Figure 7-1 shows an example of using a decision tree to predict whether customers will buy a product. The term branch refers to the outcome of a decision and is visualized as a line connecting two nodes. If a decision is numerical, the "greater than" branch is usually placed on the right, and the "less than" branch is placed on the left. Depending on the nature of the variable, one of the branches may need to include an "equal to" component.

Internal nodes are the decision or test points. Each internal node refers to an input variable or an attribute. The top internal node is called the root. The decision tree in Figure 7-1 is a binary tree in that each internal node has no more than two branches. The branching of a node is referred to as a split.

<---------------------------- Root-Top internal node '----::311'01;::---'

Male <---------------------Branch - Outcome of test

<--------------Internal Node- Decision on variable

FIGURE 7-1 Example of a decision tree

Sometimes decision trees may have more than two branches stemming from a node. For example, if an input variable Weather is categorical and has three choices-Sunny, Rainy, and Snowy-the corresponding node Weather in the decision tree may have three branches labeled as Sunny, Rainy, and Snowy, respectively.

The depth of a node is the minimum number of steps required to reach the node from the root. In Figure 7-1 for example, nodes Income and Age have a depth of one, and the four nodes on the bottom of the tree have a depth of two.

Leaf nodes are at the end of the last branches on the tree. They represent class labels-the outcome of all the prior decisions. The path from the root to a leaf node contains a series of decisions made at vari- ous internal nodes.

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

In Figure 7-1, the root node spl its into two branches with a Gender test. The right branch contains all those records with the variable Gender equal to Male, and the left branch contains all those records with the variable Gen der equal to Female to create the depth 1 internal nodes. Each internal node effec- tively acts as the root of a subtree, and a best test for each node is determined independently of the other

internal nodes. The left-hand side (LHS) internal node splits on a question based on the Income variable to create leaf nodes at depth 2, whereas the right-hand side (RHS) splits on a question on the Age variable.

The decision tree in Figure 7-1 shows that females with income less than or equal to $45,000 and males

40 years old or younger are classified as people who would purchase the product. In traversing this tree, age does not matter for fema les, and income does not matter for males.

Decision trees are widely used in practice. For example, to classify animals, questions (like cold-blooded

or warm-blooded, mammal or not mammal) are answered to arrive at a certain classification. Another

example is a checklist of symptoms during a doctor's evaluation of a patient. The artificial intelligence engine of a video game commonly uses decision trees to control the autonomous actions of a character in response to various scenarios. Retailers can use decision trees to segment customers or predict response

rates to marketing and promotions. Financial institutions can use decision trees to help decide if a loan

application should be approved or denied. In the case of loan approval, computers can use the logical if- then statements to predict whether the customer will default on the loan. For customers with a clear (strong) outcome, no human interaction is required; for observations that may not generate a clear response, a human is needed for the decision.

By limiting the number of splits, a short tree can be created. Short trees are often used as components (also cal led weak learners or base learners) in ensemble methods. Ensemble methods use multiple

predictive models to vote, and decisions can be made based on the combination of the votes. Some popu- lar ensemble methods include random forest [4]. bagging, and boosting [5). Section 7.4 discusses these ensemble methods more.

The simplest short tree is called a decision stump, which is a decision tree with the root immediately

connected to the leaf nodes. A decision stump makes a prediction based on the value of just a single input variable. Figure 7-2 shows a decision stump to classify two species of an iris flower based on the petal width. The figure shows that, if the petal width is smaller than 1.75 centimeters, it's Iris versicolor; otherwise, it's Iris virgin ica.

FIGURE 7-2 Example of a decision stump

To illustrate how a decision tree works, consider the case of a bank that wants to market its term

deposit products (such as Certificates of Deposit) to the appropriate customers. Given the demographics of clients and their reactions to previous campaign phone calls, the bank's goal is to predict which clients would subscribe to a term deposit. The dataset used here is based on the original dataset collected from a Portuguese bank on directed marketing campaigns as stated in the work by Moro et al. [6). Figure 7-3 shows a subset of the modified bank marketing dataset. This dataset includes 2,000 instances randomly drawn

7.1 Decision Trees

from the original dataset, and each instance corresponds to a customer. To make the example simple, the subset only keeps the following categorical variables: (1) job, (2) marita l status, (3) education level, (4) if the credit is in default, (5) if there is a housing loan, (6) if the customer currently has a personal loan, (7) con tact type, (8) result of the previous marketing campaign contact (pou tcome), and finally (9) if the client actually subscribed to the term deposit. Attributes (1) through (8) are input variables, and (9) is considered the outcome. The ou tcome subscribed is either yes (meaning the customer will subscribe to the term deposit) or no (meaning the customer won't subscribe). All the variables listed earlier are categorical.

job ml(iUI Nuudoo dcfwlt houWng lo.on contKI poultomc wbw:r~

••naac~~ent s inalc ter-tiary ,., ccllulal" unlcnown entrepreneur aarricd tcrtilry no , .. ,., cellular' unlcnown services diYOt"CCCI SCCOtW:IIr')' no cellular unlo:now-n ,., CIIRIJt iHnt Nt"rieil u rtlary , .. cellular unknown ••n•acNnt urrico secondary no , .. unlie.no.:n unknown UMIJC IICRt sinJlC tcr tlar")' no ,., unknown unl(no..-n entrepreneur aar ricd t crthry ,., cdluler hUurc ,., adaln. • a,.ricd secondary cellulel'" unknown

blue-collar a ardcd secondary ,., cellula r- o the r 10 aiRIJCIU!Rt • •r ricd tt: r thry ,., cellular unknown II blue• collar • er ricd secondary no ,., cellula r unlc.nown 12 ••n•u~nt ohorcco secondary unknown unlenOWin

I) blue-col lar NrriC'Cl SCCOt\011")' no , .. cclluhl'" unl(no-n no 14 ret i red urdco seconda ry cellular unl(nown

15 unacetttnt sinclc tcrthry ,., cclluler unknown 16 rctlrlt(l urd~ secondary , .. ,., cellular urltnown 17 unc•ploy~ urd~ seconda ry no ,., telephone urltnown 18 unaceacnt divorced ttrt:iary , .. cclluhr urlc nown 19 ••n•cercnt aerdcd tertiary ,., cellular url<nown 20 blue·coller urrho seconoa ry no ,., unlcnown unl(ncn.n 21 aanace~nt divorced tertiary no , .. ,., cellular hilurc ,., 22 bluc·collar oivorceo seconda ry ,., cellular hilurc 23 blue·colhr sin&lc secondary ,., cellular htlure 24 a48l n. s l n&lc secondary no unlcnown unlenown

2S blue·colhr urriC'd secoruury ,., cellular failure 26 Dlue·colhr sln&lc secondary no ,., urle~n 27 hounul d carried secondary celluhr urleno-n

18 tecMlda n aarrlcd tertiary cellular urlenOMn no

FIGURE 7-3 A subset of the bank marketing dataset

A summary of the dataset shows the following statistics. For ease of display, the summary only includes

the top six most frequently occurring values for each attribute. The rest are displayed as (Other) .

;vl ' r ..... d.lc"" ·-. blt: oll l : I ') dLV0lC' Cl: 228 primary l1 : 1 61 ma:1acp>m nt : 1~3 mat·r 1ed 12 l seconda :.-y: , y tt.ChillCl 1t :33 single : 57l tertl HT .ttlmin. : •. 3 c •Jr.kno·,·:n

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

housing

no : 916

yes:1084

loan

no :1717

yes: 283

contact

cellular :1287

telephone: 136

unknown : 577

may

jul

aug

jun

nov

ap~·

month pout come

:581 failure: 210

; 34 0 other 79

:278 success: 58

:~32 unknmm: 1653

:183

:ES

1 Other'i :268

subsc:·ibed

no :1789

yes: 211

Attribute job includes the following values.

admin. blue-collar entrep~·eneur

235 435 70

management retired self -emplo;.·ed

423 92 69

student technician unemployed

36 339 60

houser.1aid

63

16 8

unknm·:n

10

Figure 7-4 shows a decision tree built over the bank marketing dataset. The root of the tree shows that the overall fraction of the clients who have not subscribed to the term deposit is 1,789 out of the total population of 2,000.

poutcome = fallure,other,unknown

poutcome =success

education = secondary,tertiary

~ ~

education = primary,unknown

job = admln.,blue-collar,management,retired,services,technician

~ ~

job = self-employed,student,unemployed

~ l§J

FIGURE 7-4 Using a decision tree to predict if a client will subscribe to a term deposit

~ l§)

7.1 Decision Trees

At each split, the decision tree algorithm picks the most informative attribute out of the remaining attributes. The extent to which an attribute is informative is determined by measures such as entropy and information gain, as detailed in Section 7.1.2.

At the first split, the decision tree algorithm chooses the pout come attribute. There are two nodes at depth=l. The left node is a leaf node representing a group for which the outcome of the previous market- ing campaign contact is a f ai 1 ure, other, or unknown. For this group, 1,763 out of 1,942 clients have not subscribed to the term deposit.

The right node represents the rest of the population, for which the outcome of the previous marketing campaign contact is a success. For the population of this node, 32 out of 58 clients have subscribed to the term deposit.

This node further splits into two nodes based on the education level. If the education level is either secondary or tertiary, then 26 out of 50 ofthe clients have not subscribed to the term deposit. If the education level is primary or unknown, then 8 out of 8 times the clients have subscribed.

The left node at depth 2 further splits based on attribute job. If the occupation is admin, blue collar, management, retired, services, or technician, then 26 out of 45 clients have not subscribed.lfthe occupation is self -employed, student, or unemployed, then 5 out of 5 times the clients have subscribed.

7.1.2 The General Algorithm In general, the objective of a decision tree algorithm is to construct a tree T from a training set s.lf all the records ins belong to some class c(subscribed =yes, for example), or if sis sufficiently pure (greater than a preset threshold), then that node is considered a leaf node and assigned the label c. The purity of a node is defined as its probability of the corresponding class. For example, in Figure 7-4, the root

P( subscribed= yes)= 1- 1789 = 1 0.55%; therefore, the root is only 10.55% pure on the subscribed= yes 2000

class. Conversely, it is 89.45% pure on the subscribed= no class.

In contrast, if not all the records in s belong to class cor if sis not sufficiently pure, the algorithm selects the next most informative attribute A (duration, marital, and so on) and partitions s according to A's values. The algorithm constructs subtrees r,, T2 ••• for the subsets of s recursively until one of the following criteria is met:

o All the leaf nodes in the tree satisfy the minimum purity threshold.

o The tree cannot be further split with the preset minimum purity threshold.

o Any other stopping criterion is satisfied (such as the maximum depth of the tree).

The first step in constructing a decision tree is to choose the most informative attribute. A common way to identify the most informative attribute is to use entropy-based methods, which are used by decision tree learning algorithms such as 103 (or Iterative Dichotomiser 3) [7] and C4.5 [8]. The entropy methods select the most informative attribute based on two basic measures:

o Entropy, which measures the impurity of an attribute

o Information gain, which measures the purity of an attribute

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

Given a class X and its label x E X , let P(x) be the probability of x. H , ,the entropy of X, is defined as

shown in Equation 7-1.

Hx =-l.":P(x)log 1 P(x)

(7-1}

·:• X

Equation 7-1 shows that entropy Hx becomes 0 when all P(x) is 0 or 1. For a binary classification (true or false}, Hx is zero if P(x) the probability of each label x is either zero or one. On the other hand, Hx achieves the maximum entropy when all the class labels are equally probable. For a binary classification, H x = 1 if the probability of all class labels is SO/SO. The maximum entropy increases as the number of pos- sible outcomes increases.

As an example of a binary random variable, consider tossing a coin with known, not necessarily fair, probabilities of coming up heads or tails. The corresponding entropy graph is shown in Figure 7-5. Let

x = 1 represent heads and x = 0 represent tails. The entropy of the unknown result of the next toss is maxi- mized when the coin is fair. That is, when heads and tails have equal probability P( x = 1) = P( x = o) = 0.5, entropy H x = - (0.5 x log1 0.5 + 0.5 x log2 0.5) = 1 . On the other hand, if the coin is not fair, the probabilities of heads and tails would not be equal and there would be less uncertainty. As an extreme case, when the probability of tossing a head is equal to 0 or 1, the entropy is minimized to 0. Therefore, the entropy for a completely pure variable is 0 and is 1 for a set with equal occurrences for both the classes (head and tail, or

yes and no}.

~ ~

(I)

0

<C! 0

r: ""· 0

"' 0

0 0

0.0 0.2 0.4 0.6 0.8 1.0

P(X=1)

FIGURE 7-5 Entropy of coin flips, where X= 7 represents heads

For the bank marketing scenario previously presented, the output variable is subscribed. The base

entropy is defined as entropy of the output variab le, that is H,ubs<n~>ro · As seen previously, P(subscribed = yes) = 0.1055 and P(subscribed = no) = 0.8945. According to Equation 7-1, the base entropy

H,ub•wt>ro = - 0.1055·1og2 0.1055 0.8945 ·log2 0.8945 :::::: 0.4862.

7.1 Decision Trees

The next step is to identify the conditional entropy for each attribute. Given an attribute x, its value x, its outcome Y, and its value y, conditional entropy HYJx is the remaining entropy ofY given X, formally defined as shown in Equation 7-2.

HYIX = .Z:::.:P( x )H(YIX = x)

=- .2::.'.: P(x) .2::.'.: P(ylx)log2 P(ylxl (7-2)

'?xr x "'yCY

Consider the banking marketing scenario, if the attribute contact is chosen, X = {ce 11 ul ar, telepho ne, unknown}. The conditional entropy of contact considers all three values.

Table 7·1 lists the probabilities related to the contact attribute. The top row ofthe table displays the probabilities of each value of the attribute. The next two rows contain the probabilities of the class labels

conditioned on the contact.

TABLE 7-1 Conditional Entropy Example

Cellular Telephone Unknown

P(contact) 0.6435 0.0680 0.2885

P(subscribed=yes I contact) 0.1399 0.0809 0.0347

P(subscribed=no I contact) 0.8601 0.9192 0.9653

The conditional entropy of the contact attribute is computed as shown here.

H,ubsc•.~omoct = - ( 0.6435· ( 0.1399·1og2 0.1399 + 0.8601·1og2 0.8601)

+ 0.0680 · ( 0.0809 ·log2 0.0809 + 0.9192 ·log2 0.9192)

+ 0.2885 · ( 0.0347 ·log2 0.0347 + 0.9653 ·log2 0.9653 )]

= 0.4661

Computation inside the parentheses is on the entropy of the class labels within a single contact value. Note that the condi tional entropy is always less than or equal to the base entropy- that is,

H,ubswbtdjmawat ~ H,ubswt>ed· The conditional entropy is smaller than the base entropy when the attribute and the outcome are correlated. In the worst case, when the attribute is uncorrelated with the outcome, the conditional entropy equals the base entropy.

The information gain of an attribute A is defined as the difference between the base entropy and the conditional entropy of the attribute, as shown in Equation 7-3.

(7·3)

In the bank marketing example, the information gain of the contact attribute is shown in Equation 7-4.

= 0.4862-0.4661 = 0.0201 (7-4)

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

Information gain compares the degree of purity of the parent node before a split with the degree of

purity of the child node after a split. At each split, an attribute with the greatest information gain is consid- ered the most informative attribute. Information gain indicates the purity of an attribute.

The result of information gain for all the input variables is shown in Table 7-2. Attribute po u tcome has the most information gain and is the most informative variable. Therefore, pout come is chosen for the first split of the decision tree, as shown in Figure 7-4. The values of information gain in Table 7-2 are small in magnitude, but the relative difference matters. The algorithm splits on the attribute with the largest information gain at each round.

TABLE 7-2 Calculating Information Gain of Input Variables for the First Split

Attribute ! Information Gain

pout come 0.0289

contact 0.0201

hous ing 0.0133

job 0.0101

education 0.0034

mar ital 0.0018

l oan 0.0010

de fault 0.0005

Detecting Significant Splits

Quite often it is necessary to measure the significance of a split in a decision tree, especially when the information gain is small, like in Table 7-2.

Let NA and N8 be the number of class A and class 8 in the parent node. Let NAt represent the number of class A going to the left child node. N81 represent the number of class 8 going to the left child node, NAR represent the number of class 8 going to the right child node, and NBR represent the number of class 8 going to the right child node.

Let p1and pR denote the proportion of data going to the left and right node, respectively.

P - NAt + NBL

L - NA + NB

7.1 Decision Trees

The following measure computes the significance of a split. In other words, it measures how much the split deviates from what would be expected in the random data.

where

If K is small, the information gain from the split is not significant. If K is big, it would suggest the information gain from the split is significant. Take the first split of the decision tree in Figure 7-4 on variable pout come for example. NA = 1789,NB =2ll,NAL = l763,NBL = 179,NAR = 26,NBR = 32. Following are the proportions of data going to the left and right node.

PL = 194_%'ooo = 0.971 and PR = 5%ooo = 0.029.

The N~L' N~L' N~R' and N~R represent the number of each class going to the left or right node if the data is random. Their values follow.

N~L = 1737.119,N~L = 204.881,N~R = 51.881 and N~R = 6.119 Therefore, K = 126.0324, which suggests the split on pout come is significant.

After each split, the algorithm looks at all the records at a leaf node, and the information gain of each candidate attribute is calculated again over these records. The next split is on the attribute with the high- est information gain. A record can only belong to one leaf node after all the splits, but depending on the implementation, an attribute may appear in more than one split of the tree. This process of partitioning the records and finding the most informative attribute is repeated until the nodes are pure enough, or there is insufficient information gain by splitting on more attributes. Alternatively, one can stop the growth of the tree when all the nodes at a leaf node belong to a certain class (for example, subscribed= yes} or all the records have identical attribute values.

In the previous bank marketing example, to keep it simple, the dataset only includes categorical vari- ables. Assume the dataset now includes a continuous variable called duration -representing the number of seconds the last phone conversation with the bank lasted as part of the previous marketing campaign. A continuous variable needs to be divided into a disjoint set of regions with the highest information gain.

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

A brute-force method is to consider every value of the continuous variable in the training data as a candi-

date split position. This brute-force method is computationally inefficient. To reduce the complexity, the training records can be sorted based on the duration, and the candidate splits can be identified by taking the midpoints between two adjacent sorted values. An examples is if the duration consists of sorted values

{140, 160, 180, 200} and the candidate splits are 150, 170, and 190.

Figure 7-6 shows what the decision tree may look like when considering the durat ion attribute. The root splits into two partitions: those clients with duration < 456 seconds, and those with duration ;:: 456

seconds. Note that for aesthetic purposes, labels for the job and contact attributes in the figure are abbreviated.

dur~bon < 456

poutcome • ftr,oth,unk

poutcome = "ec

Q dur<1l1on < 150 \

G6 duration >= 150

no 1785 I 2000

dur~tion >"' 456

conuct • ttp,unk

g dur-ation < 1004 \

G6 durabon ;.• 1004 ~ ~

conU~ct = ell

duration < 700

0 ·-~ job • <1d ,hsm ,rtt,uNn . job "" <ld. ,bl ·,hsm,mng,sl·,srv ,std,tch,unm,unk

FIGURE 7 6 Decision tree with attribute duration

Job • ~-.mng,srv,tch

~ ~ G6 job •Mt,rtr

With the decision tree in Figure 7-6, it becomes trivial to predict if a new client is going to subscribe to the term deposit. For example, given the record of a new client shown in Table 7-3, the prediction is that this client will subscribe to the term deposit. The traversed paths in the decision tree are as follows.

• duration~456

• contact= cll (cellu lar)

• dur ation<700

• job= ent (entrepreneur), rtr (retired)

7.1 Decision Trees

TABLE 7·3 Record of a New Client

Job Marital Education Default Housing Loan Contact Duration Poutcome

retired married secondary no yes No cellular 598 unknown

7.1.3 Decision Tree Algorithms Multip le algorithms exist to implement decision trees, and the methods of tree construction vary with

different algorithms. Some popular algorithms include 103 [7]. (4.5[8]. and CART [9].

103 Algorithm

103 (or Iterative Oichotomiser 3) [7] is one of the first decision tree algorithms, and it was developed by

John Ross Quinlan. Let A be a set of categorical input variables, P be the output variable (or the predicted

class), and T be the training set. The 103 algorithm is shown here.

1 ID3 (A, P, T) 2 if TE¢ 3 r e turn ¢ 4 if a ll r ecords i n T have the same value for P 5 return a single node with that value 6 if AEo 7 return a single node with the most frequent value o f P in T B Compute information gain fo r each att ribute in A relative to T 9 Pi ck a ttribute D with t he lar gest gain 10 Let { d1,d2 • . . dm } be the values of attribute D 11 Par titi on T i nto { T1,T2 . .. ~, } accord i ng to t he va lues of D 12 return a t r ee with root D and branches labeled d1,d2 .. • dm

going respectively to trees I D3(A- {D} , P, ~) . I D3(A- {D }, P, T

2 ) , •• . ID3(A-{D} , P, Tm)

(4.5

The (4.5 algorithm [8] introduces a number of improvements over the original103 algorithm. The (4.5

algorithm can handle missing data. If the training records contain unknown attribute va lues, the C4.5

evaluates the gain for an attribute by considering only the records where the attribute is defined.

Both categori cal and continuous attributes are supported by ( 4.5. Values of a continuous variable are

sorted and partitioned. For the corresponding records of each partition, the gain is calculated, and the

partition that maximizes the gain is chosen for the next split.

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

The 103 algorithm may construct a deep and complex tree, which would cause overfitting (Section 7.1.4). The C4.5 algorithm addresses the overfitting problem in 103 by using a bottom-up technique called

pruning to simplify the tree by removing the least visited nodes and branches.

CART

CART (or Classification And Regression Trees) [9] is often used as a generic acronym for the decision tree,

although it is a specific implementation. Similar to C4.5, CART can handle continuous attributes. Whereas C4.5 uses entropy-based criteria to

rank tests, CART uses the Gini diversity index defined in Equation 7-5.

Ginix = 1- LP(x)2 (7-5) Vx· X

Whereas C4.5 employs stopping rules, CART constructs a sequence of subtrees, uses cross-validation to

estimate the misclassification cost of each subtree, and chooses the one with the lowest cost.

7.1.4 Evaluating a Decision Tree Decision trees use greedy algorithms, in that they always choose the option that seems the best avail-

able at that moment. At each step, the algorithm selects which attribute to use for splitting the remain ing

records. This se lection may not be the best overall, but it is guaranteed to be the best at that step. This

characteristic reinforces the efficiency of decision trees. However, once a bad split is taken, it is propagated

through the rest of the tree. To address this problem, an ensemble technique (such as random forest) may

randomize the splitting or even randomize data and come up with a multiple tree structure. These trees

then vote for each class, and the class with the most votes is chosen as the predicted class.

There are a few ways to evaluate a decision tree. First, evaluate whether the splits of the tree make

sense. Conduct sanity checks by validating the decision rules with domain experts, and determine if the

decision rules are sound.

Next, look at the depth and nodes of the tree. Having too many layers and obtaining nodes with few

members might be signs of overfitting. In overfitting, the model fits the training set wel l, but it performs

poorly on the new samples in the testing set. Figure 7-7 illustrates the performance of an overfit model.

The x-axis represents the amount of data, and they-axis represents the errors. The blue curve is the training

set, and the red curve is the testing set. The left side of the gray vertical line shows that the model predicts

well on the testing set. But on the right side of the gray line, the model performs worse and worse on the

testing set as more and more unseen data is introduced.

X

fiGURE 7-7 An overfrt model describes the training data well but predicts poorly on unseen data

7.1 Decision Trees

For decision tree learning, overfitting can be caused by either the lack of training data or the biased data

in the training set. Two approaches [10] can help avoid overfitting in decision tree learning.

• Stop growing the tree early before it reaches the point where all the training data is perfectly classified.

• Grow the full tree, and then post-prune the tree with methods such as reduced-error pruning and rule-based post pruning.

Last, many standard diagnostics tools that apply to classifiers can help evaluate overfitting. These tools

are further discussed in Section 7.3.

Decision trees are computationally inexpensive, and it is easy to classify the data. The outputs are

easy to interpret as a fixed sequence of simple tests. Many decision tree algorithms are able to show the

importance of each input variable. Basic measures, such as information gain, are provided by most statisti· cal software packages.

Decision trees are able to handle both numerical and categorical attributes and are robust with redun-

dant or correlated variables. Decision trees can handle categorical attributes with many distinct values, such

as country codes for telephone numbers. Decision trees can also handle variables that have a nonlinear

effect on the outcome, so they work better than linear models (for example, linear regression and logistic

regression) for highly nonlinear problems. Decision trees naturally handle variable interactions. Every node

in the tree depends on the preceding nodes in the tree.

In a decision tree, the decision regions are rectangular surfaces. Figure 7-8 shows an example of five

rectangular decision surfaces (A, B, (, D, and E) defined by four values-{\.\. A. 3

, >-. 4

} -of two attributes

(x1 and x). The corresponding decision tree is on the right side of the figure. A decision surface corresponds to a leaf node of the tree, and it can be reached by traversing from the root of the tree following by a series

of decisions according to the value of an attribute. The decision surface can only be axis-aligned for the

decision tree.

E

~ · B

c D A

A B c D E FIGURE 7-8 Decision surfaces can only be axis-aligned

The structure of a decision tree is sensitive to small variations in the training data. Although the dataset is the same, constructing two decision trees based on two different subsets may result in very different trees. If

a tree is too deep, overfitting may occur, because each split reduces the training data for subsequent splits. Decision trees are not a good choice if the dataset contains many irrelevant variables. This is different

from the notion that they are robust with redundant variables and correlated variables. If the dataset

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

contains redundant variables, the resulting decision tree ignores all but one of these variables because the algorithm cannot detect information gain by including more redundant variables. On the other hand, if the dataset contains irrelevant variables and if these variables are accidentally chosen as splits in the tree, the tree may grow too large and may end up with less data at every split, where overfitting is likely to occur. To address this problem, feature selection can be introduced in the data preprocessing phase to eliminate the irrelevant variables.

Although decision trees are able to handle correlated variables, decision trees are not well suited when most of the variables in the training set are correlated, since overfitting is likely to occur. To overcome the issue of instability and potential overfitting of deep trees, one can combine the decisions of several randomized shallow decision trees-the basic idea of another classifier called random forest [4]-or use ensemble methods to combine several weak learners for better classification. These methods have been shown to improve predictive power compared to a single decision tree.

For binary decisions, a decision tree works better if the training dataset consists of records with an even probability of each result. In other words, the root of the tree has a 50% chance of either classification. This occurs by randomly selecting training records from each possible classification in equal numbers. It counteracts the likelihood that a tree will stump out early by passing purity tests because of bias in the training data.

When using methods such as logistic regression on a dataset with many variables, decision trees can help determine which variables are the most useful to select based on information gain. Then these variables can be selected for the logistic regression. Decision trees can also be used to prune redundant variables.

7.1.5 Decision Trees in R In R, rpart is for modeling decision trees, and an optional package rpart . plot enables the plotting of a tree. The rest of this section shows an example of how to use decision trees in R with rpart . p 1 ot to predict whether to play golf given factors such as weather outlook, temperature, humidity, and wind.

In R, first set the working directory and initialize the packages.

setwd { "c: /") install.packages("rpart.plot") # install package rpart.plot library("rpart") # load libraries library("rpart.plot")

The working directory contains a comma-separated-value (CSV) file named DTdata. csv. The file has a header row, followed by 10 rows of training data.

Play,Outlook,Temperature,Humidity,Wind yes,ra:ny,cool,normal,FALSE no,rainy,cool,normal,TRUE yes,overcast,hot,high,FALSE no,sunny,mild,high,FALSE yes,ra~ny,cool,normal,FALSE

yes,sunny,cool,normal,FALSE yes,rainy,cool,normal,FALSE yes,sunny,hot,normal,FALSE yes,overcast,mild,high,TRUE no,sunny,mild,high,TRUE

7.1 Decision Trees

The CSV file contains five attributes: Play, Outlook, Temperature, Humidity, and Wind. Playwould be the output variable (or the predicted class}, and outlook, Temperature, Humidity, and Wind would be the input variables. In R, read the data from the CSV file in the working directory and display the content.

play_decision <- read. table ( 11 DTdata. csv", header=TRUE, sep=", ") play_decision

Play Outlook Ternperatur·e Humidity ;·iind

1 yes rainy cool n::Jrmal FALSE 2 no r-a1n:/ cool rDrmal TRUE

yes overcast hot high FJ:..LSE

4 no sun~y r.li ld high F.Z..LSE

5 yes rain;.· cool r:::Jrmal FALSE

6 yes sunny cool :nnnal FJ:..LSE 7 )'es rai::y cool r,:Jrmal FJ:,.LSE

yes sunny hot rDrmal FJ..LSE

9 yes overcast mild high TRUE

10 no sunny mild high TRUE

Display a summary of play_decision.

summary(play_decision)

Play·

no :3 yes:7

Outlook Temperature Humidity

overcast::?.

rain;.· sunny :4

cool:5 bot :2 mild:3

high :·l normal:6

·::ind

:•loje :logical FJ.<.i~SE: 7

TRUE :3 NA's :0

The rpart function builds a model of recursive partitioning and regression trees [9]. The following code snippet shows how to use the rpart function to construct a decision tree.

fit <- rpart(Play- Outlook+ Temperature +Humidity+ Wind, method="class 11 , data=play_decision, control=rpart.control(minsplit=l), parms=list(split=•information•))

The rpart function has four parameters. The first parameter, Play - Out look + Temperature + Hurnidi ty + Wind, is the model indicating that attribute Play can be predicted based on attri- butes Outlook, Temperature, Humidity, and Wind. The second parameter, method, is set to "class," telling R it is building a classification tree. The third parameter, data, specifies the dataframe containing those attributes mentioned in the formula. The fourth parameter, control, is optional and controls the tree growth. In the preceding example, control=rpart. control (minspli t=l) requires that each node have at least one observation before attempting a split. The rninspl it= 1 makes sense for the small dataset, but for larger datasets rninspl it could be set to 10% of the dataset size to combat overfitting. Besides minsp 1 it, other parameters are available to control the construction of the decision tree. For example, rpart. control (rnaxdepth=10, cp=O. 001) limits the depth ofthe

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

tree to no more than 10, and a split must decrease the overall lack of fit by a factor of 0.001 before being attempted. The last parameter (parms) specifies the purity measure being used for the splits. The value of sp 1 it can be either information (for using the information gain) or g ini (for using the Gini index).

Enter sununary (fit) to produce a summary of the model built from rpart. The output includes a summary of every node in the constructed decision tree. If a node is a leaf, the out-

put includes both the predicted class label (yes or no for Play) and the class probabilities-P (Play). The leaf nodes include node numbers 4, 5, 6, and 7.1f a node is internal, the output in addition displays the number of observations that lead to each child node and the improvement that each attribute may bring for the next split. These internal nodes include numbers 1, 2, and 3.

summary(fit) Call:

rpart(formula = P:ay- Outlook t Temperature+ Humidity+ Wind,

data= play_dec:..sion, method= "class",

parrr.s = list 1:sp'Cit = "in!'ormation"),

control= rpart.controllminsplit 1) i

n= 10

CP nsplit rel error xerror xstd

0.3333333

2 0.0100000

1.000000 0.~830~59

1.666667 0.5270~63

Variable importance

Wind Outlook Temperature

51 29 20

Node number 1: 10 obse!·vations, complexity param=0.3333333

predicted c:ass=yes expected loss=0.3 P 1nodel

class counts: 7

probabilities: 0.300 J.700

left son=2 I 3 obs :· rig:1t son=3 ! 7 obs •

Primary splits:

Temperature splits as RRL, :..rr.prove=1. 3282860, 10 missing)

\'lind < 0.5 to the !·ight, in~prove=1.3282860, ·.0 missing)

Outlook splits as ?.LL,

Humidity splits as LE, Surrogate splits:

improve=0.8161371, (0 missing)

improve=C.6326870, (0 missing;

Wind< 0.5 to the right, agree=O.B, adj=0.333, 0 split'

Node number 2: 3 observations, complexity param=0.3333333

predicted class=no expected loss=0.3333333 PinojeJ =0.3

class counts:

probabilities: 0.667 0.333

left son=4 (2 obs) right son=S (1 obsJ

Primar}· splits:

Outlook splits as R-L, improve=l.9095430, (0 missing)

\·lind < O.S :-.o the left, improve=0.523248l, (0 missing)

Node number 3: 7 observat io:1s, complexi t·_.: p<uam= 0. 3 3 33 33 3

predicted class=yea expected loss=O.l428571 P(node) =0.7

class counts:

probabilities: 0.143 0.857

le~t son=6 l obs right san=- 16 obsi

Primary splits:

\'lind c :'.5 to the !.ight, ir:lprc·:e=:.:.3708l.;:J, missing'

Outlook splits as RLE, improve=0.621.;736, '0 m1ssing1

Temperature splits as LR-, irnprc·.·e=0.~68802l, !0 missing!

Humidity spl1ts as RL, improve=J.:67.;47D, !0 missing!

Node number~= 2 observatio~s

predicted class=no expected loss=O P~nod~ =0.2

class co;.~nts:

probabilities: l.JDO 0.0

Node number 5: l observations

predicted class=yes expected loss=8 Plnode .l

class cot:nts:

probabilities: O.JOO 1.000

Node number 6: 1 observations

predicted class=no

class counts:

expected loss=O Plnocle:, ~o.l

0

probabilities: 1.000 0.000

Node number 7: 6 observations

predicted class=yes expected loss=O Plnode) =0.6

class counts: 0

probabilities: 0.000 1.000

7.1 Decision Trees

The output produced by the summary is difficult to read and comprehend. The rpart. plot (} function from the rpart. plot package can visually represent the output in a decision tree. Enter the following command to see the help file of rpart . plot:

?rpart.plot

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

Enter the following R code to plot the tree based on the model being built. The resulting tree is shown in Figure 7-9. Each node of the tree is labeled as either yes or no referring to the Play action of whether to play outside. Note that, by default, R has converted the values of Wind (True I False) into numbers. rpart.plot(fit, type~4, extra=l)

7

Temperat=

/ col,h~ot yes 1 6

Outlook Wind >a 0.6

I 0~ ! <~ ® ~ @ ~

FIGURE 7-9 A decision tree built from DTdata.csv

The decisions in Figure 7-9 are abbreviated. Use the following command to spell out the full names and display the classification rate at each node.

rpart.plot(fitl type=4 1 extra=2~ clip.right.labs=FALSE, varlen~0 1 faclen=O)

The decision tree can be used to predict outcomes for new datasets. Consider a testing set that contains the following record.

Outlook= 11 rainy 11 , Temperature="mild 11 , Humidity= 11 high 11 , Wind=FALSE

The goal is to predict the play decision of this record. The following code loads the data into Rasa data frame newda ta. Note that the training set does not contain this case.

newdata <- data.frame(Outlook= 11 rainy 11 , Temperature= 11 mild 11 , Humidity= 11 high", Wind::FALSE)

newdata Outlook Temperature Humidity Wind

1 rainy mild high FALSE

Next, use the predict function to generate predictions from a fitted rpart object. The format of the predict function follows.

predict(object 1 newdata = list(), type :: C ("vector II 1 11 probll 1 11 Classll 1 11 matrix"))

7.2 Na..-ve Bayes

Parameter type is a character string denoting the type of the predicted value. Set it to either p rob or clas s to predict using a decision tree model and receive the result as either the class probabi lities or just the class. The output shows that one instance is classified as Play=no, and zero instances are

classified as P 1 a y=ye s . Therefore, in both cases, the decision tree predicts that the play decision of the testing set is not to play.

predi ct (fit,newdata=ne wdata, type= "prob" )

no ye-s

c

predict (fi t ,newdata=newdata,type="class ")

no Levels : r.o yes

7.2 Na·ive Bayes Na'ive Bayes is a probabilistic classification method based on Bayes' theorem (or Bayes' law) with a few tweaks. Bayes' theorem gives the relationship between the probabilities of two events and their conditional

probabilities. Bayes' law is named after the English mathematician Thomas Bayes. A na'ive Bayes classifier assumes that the presence or absence of a particular feature of a class is unre-

lated to the presence or absence of other features. For example, an object ca n be classified based on its attributes such as shape, color, and weight. A reasonable classification for an object that is spherical,

yellow, and less than 60 grams in weight may be a tennis ball. Even if these features depend on each other or upon the existence of the other features, a na'ive Bayes classifier considers all these properties to contribute

independently to the probabil ity that the object is a tennis ball. The input variables are generally categorical, but variations of the algorithm can accept continuous

variables. There are also ways to convert continuous variables into categorical ones. This process is often

referred to as the discre tization of continuous variables. In the tennis ball example, a continuous variable such as weight can be grouped into intervals to be converted into a categorical variable. For an attribute such as income, the attribute can be converted into categorical values as shown below.

• Low Income: income < $10,000

• Working Class: $10,000 s income < $50,000

• Middle Class: $50,000 s income < $1,000,000

• Upper Class: income ~ $1,000,000

The output typica lly includes a class label and its corresponding probability score. The probability score is not the true probabi lity of the class label, but it's proportional to the true probability. As shown later in the chapter, in most implementations, the output includes the log probabili ty for the class, and class labels

are assigned based on the highest values.

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

Because na"ive Bayes classifiers are easy to implement and can execute efficiently even without prior knowledge of the data, they are among the most popular algorithms for classifying text documents. Spam filtering is a classic use case of na'ive Bayes text classification. Bayesian spam filtering has become a popular mechanism to distinguish spam e-mail from legitimate e-mail. Many modern mail clients implement vari- ants of Bayesian spam filtering.

Na"ive Bayes classifiers can also be used for fraud detection [11]. In the domain of auto insurance, for example, based on a training set with attributes such as driver's rating, vehicle age, vehicle price, historical claims by the policy holder, police report status, and claim genuineness, na"ive Bayes can provide probability- based classification of whether a new claim is genuine [12].

7.2.1 Bayes' Theorem The conditional probability of event C occurring, given that event A has already occurred, is denoted as P(CjA) , which can be found using the formula in Equation 7-6.

P(CjA)= P(AnC) P(A) (7-6)

Equation 7-7 can be obtained with some minor algebra and substitution of the conditional probability:

P(CjA)= P(A!C)·P(C) P(A) (7-7)

whereCistheclasslabel C E {c1,c2, . .. c) and A is the observed attributes A= {a1,a2, ... am} . Equation 7-7 is the most common form of the Bayes' theorem.

Mathematically, Bayes' theorem gives the relationship between the probabilities of C and A, P(C) and P(A), and the conditional probabilities of C given A and A given C, namely P(CjA) and P(AIC).

Bayes' theorem is significant because quite often P(C I A) is much more difficult to compute than P(A I C) and P(C) from the training data. By using Bayes' theorem, this problem can be circumvented.

An example better illustrates the use of Bayes' theorem. John flies frequently and likes to upgrade his seat to first class. He has determined that if he checks in for his flight at least two hours early, the probability that he will get an upgrade is 0.75; otherwise, the probability that he will get an upgrade is 0.35. With his busy schedule, he checks in at least two hours before his flight only 40% of the time. Suppose John did not receive an upgrade on his most recent attempt. What is the probability that he did not arrive two hours early?

let C= {John arrived at least two hours early}, and A= {John received an upgrade}, then -,c ={John did not arrive two hours early}, and -,A= {John did not receive an upgrade}.

John checked in at least two hours early only 40% of the time, or P(C)=0.4. Therefore, P( -,() =1-P(C)=0.6.

The probability that John received an upgrade given that he checked in early is 0.75, or P( A I C)= 0.75. The probability that John received an upgrade given that he did not arrive two hours early is 0.35, or

P(AI-,C) = 0.35. Therefore, P(•AI•C) = 0.65. The probability that John received an upgradeP(A) can be computed as shown in Equation 7-8.

P(A)= P(AnC) +P(An•C)

= P( C)·P(A IC)+P( ·C)·P(AI·C)

= 0.4 X 0.75 + 0.6 X 0.35

=0.51

7.2 Na'ive Bayes

(7-8)

Thus, the probability that John did not receive an upgrade P( •A) = 0.49. Using Bayes' theorem, the probability that John did not arrive two hours early given that he did not receive his upgrade is shown in Equation 7-9.

P( .q ·A) = P( ·AI•C) · P( •C) P( ·A)

0.65 X 0.6 ::::;: 0.796 0.49

(7-9)

Another example involves computing the probability that a patient carries a disease based on the result of a lab test. Assume that a patient named Mary took a lab test for a certain disease and the result came back positive. The test returns a positive result in 95% of the cases in which the disease is actually present, and it returns a positive result in 6% of the cases in which the disease is not present. Furthermore, 1% of the entire population has this disease. What is the probability that Mary actually has the disease, given that the test is positive?

let c = {having the disease} and A = {testing positive}. The goal is to solve the probability of having the disease, given that Mary has a positive test result, P(CjA). From the problem description, P( C)= 0.01,

P( ·C)= 0.99, P(AIC) = 0.95 and P(AI·C) = 0.06.

Bayes' theorem defines P(C I A)= P(A I C)P(C) I P(A). The probability of testing positive, that is P(A), needs to be computed first. That computation is shown in Equation 7-10.

P(A) = P(AnC)+P(An•C) = P(C). P(AIC) + P( ·C). P(A I·C) = 0.01 X 0.95 + 0.99 X 0.06 = 0.0689 (7-10}

According to Bayes' theorem, the probability of having the disease, given that Mary has a positive test result, is shown in Equation 7-11.

P(CjA)= P(AIC)P(C) = 0.95x0.01 ::::::0.1379 P(A) 0.0689

(7-11)

That means that the probability of Mary actually having the disease given a positive test result is only 13.79%. This result indicates that the lab test may not be a good one. The likelihood of having the disease

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

was 1% when the patient walked in the door and only 13.79% when the patient walked out, which would suggest further tests.

A more general form of Bayes' theorem assigns a classified label to an object with multiple attributes A= {a1,a2 , ••. ,am} such that the label corresponds to the largest value of P(c1IA). The probability that a set of attribute values A (composed of m variables a1,a2, ••• ,am) should be labeled with a classification label c1 equals the probability thatthe set of variables al' a2, ••• , am given c1 is true, times the probability of c1 divided by the probability ofa1,a2, •• • ,am. Mathematically, this is shown in Equation 7-12.

P( lA) _ P(a

1 ,a

2 , ••• ,amlc1)·P(c) . _ 1 2 c. - ,1-, , ... n

' P(a1,a2 , ••• ,am) (7-12)

Consider the bank marketing example presented in Section 7.1 on predicting if a customer would subscribe to a term deposit. LetA be a listofattributes{job, marital, education, default, housing, loan, contact,poutcome}. According to Equation 7-12, the problem is essentially to calculate P(c1IA), where

c 1 E {subscribed= yes,subscribed =no}.

7.2.2 Na·ive Bayes Classifier With two simplifications, Bayes' theorem can be extended to become a na"ive Bayes classifier.

The first simplification is to use the conditional independence assumption. That is, each attribute is conditionally independent of every other attribute given a class label 'r See Equation 7-13.

m

P(al'a2, •• • ,amlc1) = P(a1lc1)P(a2 lc1)···P(amlc1) = f]P(a1lc1) }=1

Therefore, this na'ive assumption simplifies the computation of P(al'a2, ••• ,amlc;l.

(7-13)

The second simplification is to ignore the denominatorP(a1,a2 , ••• ,am). BecauseP(a1,a2 , ... ,am) appears in the denominator of P(c1IA) for all values of i, removing the denominator will have no impact on the relative probability scores and will simplify calculations.

Na"ive Bayes classification applies the two simplifications mentioned earlier and, as a result, P(c

1 la

1 ,a

2 , ••• ,am) is proportional to the product of P(a

1 lc1) times P(c;). This is shown in Equation 7-14.

m

P(c1IA) 0< P(c1)· f1P(a1lc1) }=1

i = 1,2, ... n

The mathematical symbol 0< indicates that the LHS P(c1IA) is directly proportional to the RHS.

(7-14)

7.2 Na'ive Bayes

Section 7.1 has introduced a bank marketing dataset (Figure 7-3). This section shows how to use the naiVe Bayes classifier on this dataset to predict if the clients would subscribe to a term deposit.

Building a na'ive Bayes classifier requires knowing certain statistics, all calculated from the training set. The first requirement is to collect the probabilities of all class labels, P(c1).1n the presented example, these would be the probability that a client will subscribe to the term deposit and the probability the client will not. From the data available in the training set, P( subscribed= yes)~ 0.11 and P( subscribed= no)~ 0.89.

The second thing the na'ive Bayes classifier needs to know is the conditional probabilities of each attribute a1 given each class label c1, namely P(a1lc1) • The training set contains several attributes: job, marital, education, default, housing, loan, contact,andpoutcome. For each attribute and its possible values, computing the conditional probabilities given subscribed= yes or subscribed= no is required. For example, relative to the marital attribute, the following conditional probabilities are calculated.

P(single I subscribed= yes)~ 0.35

P(married I subscribed= yes)~ 0.53

P(divorced I subscribed= yes)~ 0.12

P(single I subscribed= no)~ 0.28

P(married I subscribed = no) ~ 0.61

P(divorced I subscribed= no)~ 0.11

After training the classifier and computing all the required statistics, the na'ive Bayes classifier can be tested over the testing set. For each record in the testing set, the na'ive Bayes classifier assigns the classifier

label c1 that maximizesP(c1) ·Tij : 1 P(a1lc1). Table 7-4 contains a single record for a client who has a career in management, is married, holds a sec-

ondary degree, has credit not in default, has a housing loan but no personal loans, prefers to be contacted via cellular, and whose outcome of the previous marketing campaign contact was a success. Is this client likely to subscribe to the term deposit?

TABLE 7-4 Record of an Additional Client

Job Marital Education Default Housing Loan Contact Poutcome

management married secondary no yes no cellular Success

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

The conditional probabilities shown in Table 7-5 can be calculated after building the classifier with the training set.

TABLE 7-5 Compute Conditional Probabilities for the New Record

j a 1

P(a 1 I subscribed= yes) P(a

1 I subscribed=no)

job= management 0.22 0.21

2 marital= married 0.53 0.61

3 education = 0.46 0.51 secondary

4 default = no 0.99 0.98

5 housing= yes 0.35 0.57

6 loan = no 0.90 0.85

7 contact= cellular 0.85 0.62

8 poutcome= 0.15 0.01 success

Because P(c1la1,a2 , .. . ,am) is proportional to the product of P(a11c, )(j E [1,m]) times (c1), the na'ive Bayes classifier assigns the class label c

1 • which results in the greatest value over all i. Thus, P(c1la1,a2 , . •• ,am) is

computed for each c1 with P(c11Al P(c1) • IJ j : 1 P( a1lc1) • For A ={management, married, secondary, no, yes, no, cellular, success},

P(yesiA )<X 0.1 1·(0.22 ·0.53·0.46·0.99·0.35·0.90·0.85·0.1 5)::::: 0.00023

P( nolA) ::x 0.89 · ( 0.21-0.61 · 0.51· 0.98 · 0.57 ·0.85 · 0.62 · 0.01)::::: 0.00017

Because P(subscribed = yesiAl > P(subscribed = nolA), the client shown in Table 7-4 is assigned with the label subscribed = yes. That is, the client is classified as likely to subscribe to the term deposit.

Although the scores are small in magnitude, it is the ratio of P(yesiA) and P(naiA) that matters. In fact, the scores of P(yesiA) and P( nolA) are not the true probabi lities but are only proportional to the true prob- abilities, as shown in Equation 7-14. After all, if the scores were indeed the true probabilities, the sum of P(yesiA) and P(noiA) would be equal to one. When looking at problems with a large number of attributes, or attributes with a high number of levels, these va lues can become very smal l in magnit ude (close to zero), resulting in even smaller differences of the scores. This is the problem of numerical underflow, caused by multiplying several probability values that are close to zero. A way to alleviate the problem is to compute

7.2 Naive Bayes

the logarithm of the products, which is equivalent to the summation of the logarithm of the probabilities. Thus, the na'ive Bayes formula can be rewritten as shown in Equation 7-15.

m

P(c;IA) ex: logP(c;}+ L:.::logP(ailc;) j=l

i=1,2, ... n (7-15}

Although the risk of underflow may increase as the number of attributes increases, the use of logarithms is usually applied regardless of the number of attribute dimensions.

7.2.3 Smoothing If one of the attribute values does not appear with one of the class labels within the training set, the corresponding P(ailc;} will equal zero. When this happens, the resulting P(c;IA) from multiplying all the P(ailc)(j E [1,m]} immediately becomes zero regardless of how large some of the conditional probabilities are. Therefore overfitting occurs. Smoothing techniques can be employed to adjust the probabilities of P(ailc;} and to ensure a nonzero value ofP(c;IA). A smoothing technique assigns a small nonzero probability to rare events not included in the training dataset. Also, the smoothing addresses the possibility of taking the logarithm of zero that may occur in Equation 7-15.

There are various smoothing techniques. Among them is the Laplace smoothing (or add-one} tech- nique that pretends to see every outcome once more than it actually appears. This technique is shown in Equation 7-16.

• count(x)+1 P (x)= E)count(x)+ 1]

(7-16}

For example, say that 100 clients subscribe to the term deposit, with 20 of them single, 70 married, and 10 divorced. The "raw" probability is P(singlelsubscribed=yes)=20/100=0.2. With Laplace smoothing adding one to the counts, the adjusted probability becomes P'(singlelsubscribed =yes)= (20+ 1}1[(20+ 1)+(70+ 1)+(10+ 1}] ~ 0.2039.

One problem of the Laplace smoothing is that it may assign too much probability to unseen events. To address this problem, Laplace smoothing can be generalized to use£ instead of 1, where typically£ E [0, t See Equation 7-17.

•• count( x) + £ P ( x) = -E-) c-o-un-t.,-( x.,--) +-~-=] (7-17)

Smoothing techniques are available in most standard software packages for na"ive Bayes classifiers. However, if for some reason (like performance concerns) the na·ive Bayes classifier needs to be coded directly into an application, the smoothing and logarithm calculations should be incorporated into the implementation.

7.2.4 Diagnostics Unlike logistic regression, na'ive Bayes classifiers can handle missing values. Na"ive Bayes is also robust to irrelevant variables-variables that are distributed among all the classes whose effects are not pronounced.

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

The model is simple to implement even without using libraries. The prediction is based on counting the occurrences of events, making the classifier efficient to run. Na'ive Bayes is computationally efficient and is able to handle high-dimensional data efficiently. Related research [13] shows that the naive Bayes classifier in many cases is competitive with other learning algorithms, including decision trees and neural networks. In some cases na"ive Bayes even outperforms other methods. Unlike logistic regression, the na"ive Bayes classifier can handle categorical variables with many levels. Recall that decision trees can handle categorical variables as well, but too many levels may result in a deep tree. The na"ive Bayes classifier overall performs better than decision trees on categorical values with many levels. Compared to decision trees, na'ive Bayes is more resistant to overfitting, especially with the presence of a smoothing technique.

Despite the benefits of na"ive Bayes, it also comes with a few disadvantages. Na"ive Bayes assumes the variables in the data are conditionally independent. Therefore, it is sensitive to correlated variables because the algorithm may double count the effects. As an example, assume that people with low income and low credit tend to default. If the task is to score "default" based on both income and credit as two separate attributes, na'ive Bayes would experience the double-counting effect on the default outcome, thus reduc- ing the accuracy of the prediction.

Although probabilities are provided as part of the output for the prediction, na"ive Bayes classifiers in general are not very reliable for probability estimation and should be used only for assigning class labels. Na'ive Bayes in its simple form is used only with categorical variables. Any continuous variables should be converted into a categorical variable with the process known as discretization, as shown earlier. In com- mon statistical software packages, however, na"ive Bayes is implemented in a way that enables it to handle continuous variables as well.

7.2.5 Na·ive Bayes in R This section explores two methods of using the na'ive Bayes classifier in R. The first method is to build from scratch by manually computing the probability scores, and the second method is to use the nai veBayes function from the el o 71 package. The examples show how to use na'ive Bayes to predict whether employ- ees would enroll in an onsite educational program.

In R, first set up the working directory and initialize the packages.

setwd ( "c: I") install.packages("el071") # install pac~age e1071 library(el071) # load the library

The working directory contains a CSV file (samplel. csv). The file has a header row, followed by 14 rows of training data. The attributes include Age, Income, JobSatisfaction, and Desire. The output variable is Enrolls, and its value is either Yes or No. Full content of the CSV file is shown next.

Age,Income,JobSatisfaction,Desire,Enrolls <=30,High,No,Fair,No <=30,High,No,Excellent,No 31 to 40,High,No,Fair,Yes >40,Medium,No,Fai~.Yes

>40,Low,Yes,Fai~.Yes

>40,Low,Yes,Excellent,No 31 to 40,Low,Yes,Excellent,Yes

<=30,Medium,No,Fair,No <=30,Low,Yes,Fair,Yes >40,Medium,Yes,Fair,Yes <=30,Medium,Yes,Excellent,Yes 31 to 40,Medium,No,Excellent,Yes

31 to 40,High,Yes,Fair,Yes >40,Medium,No,Excellent,No

<=30,Medium,Yes,Fair,

7.2 Na'ive Bayes

The last record of the CSV is used later for illustrative purposes as a test case. Therefore, it does not include a value for the output variable Enrolls, which should be predicted using the na'ive Bayes classifier built from the training set.

Execute the following R code to read data from the CSV file.

# read the data into a table from the file

sample <- read. table ( 11 samplel . csv n , header= TRUE, sep= 11 , " ) # define the data frames for the NB classifier traindata <- as.data.frame(sample[l:l4,]) testdata <- as.data.frame(sample[lS,])

Two data frame objects called trainda ta and test data are created for the na'ive Bayes classifier. Enter traindata and testdata to display the data frames.

The two data frames are printed on the screen as follows.

traindata Age Income JobSatisfaction Desire Enrolls

1 <=30 High No Fai~ No 2 <=30 High No Excellent No 3 31 to 40 High No Fai:.- Yes 4 >40 i-ledi urn No Fai:.- Yes 5 >40 Lo~,o: Yes Fai:- Yes 6 >40 Low Yes Excellent No 7 31 to 40 Low "les Excellent Yes 8 <=30 f.lediurn No Fai:- No 9 <=30 Low Yes Fai:- Yes 10 >40 Medium Yes Fah· Yes 11 <=30 Ivledium Yes Excellent Yes 12 31 to 40 Medium No Excellent Yes 13 31 to 40 High Yes Fair· Yes 14 >40 1-!ediurn No Excellent No

testdata Age Income JobSatisfaction Cesire Enrolls

15 <=30 !•ledium Yes Fair

The first method shown here is to build a na'ive Bayes classifier from scratch by manually computing the probability scores. The first step in building a classifier is to compute the prior probabilities ofthe attributes,

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

including Age, Income, JobSatisfaction, and Desire. According to the naive Bayes classifier, these attributes are conditionally independent. The dependent variable (output variable) is Enrolls.

Compute the prior probabilities P(c;) for Enrolls, where c; E C and C = {Yes,No}.

tprior <- table(traindata$Enrolls) tprior

No Yes

tprior <- tprior/sum(tprior) tprior

No Yes

0.0000000 0.3571429 0.6428571

The next step is to compute conditional probabilitiesP(AIC), where A ={Age, Income, JobSatisfaction,Desire} and C ={Yes, No}. Count the number of "No" and "Yes" entries for each Age group, and normalize by the total number of"No" and "Yes" entries to get the conditional probabilities.

ageCounts <- table (traindata [, c ("Enrolls", "Agen)]) age Counts

f1.ge

ageCounts <- ageCounts/rowSums(ageCounts) ageCounts

Age Em.,olls <=30 >40 31 ::o 40

No 0.6000000 0.4000000 0.0000000

Yes 0.2222222 0.3333333 0.44~444~

Do the same for the other attributes including Income, JobSatisfaction, and Desire.

incomeCounts <- table (traindata [, c ( 11 Enrolls", "Income 11 )]) incomeCounts <- incomeCounts/rowSums(incomeCounts) incomecounts

Yes 0.2222222 0.3333333 .4444444

jsCounts <- table(traindata[,c("Enrolls", "JobSatisfaction")]) jsCounts <- jsCounts/rowSums(jsCounts)

jsCounts Jobsatisfaction

Enrolls No Yes

No o.soooooo o.~oooca Yes 0.3333333 0.6GGG667

desireCounts <- table (traindata [, c ("Enrolls", "Desire'•) 1) desireCounts <- desireCounts/rowSums(desireCounts) desireCounts

Desire

Enrolls Exce:lent Fair

No 0.60000CO 8.~0080CO

Yes 0.3333333 O.E66GGG7

7.2 Na'ive Bayes

According to Equation 7-7, probability P(c1IA) is determined by the product of P(ajlc,) times the (c1) where c1 =Yes and c2 =No. The larger value of P(YesiA) and P(NoiA) determines the predicted result of the output variable. Given the test data, use the following code to predict the Enrolls.

prob_yes <- agecounts [ '1Yes 11 , testdata [, c ("Age 11 ) 1 1 * incomeCounts ["Yes 11 , testdata [,c ( 11 Income'1 ) 11 * j sCounts [ 11 Yes ., , testdata [, c ( '1JobSatisfaction 11 ) 1 1 * desireCounts [ 11 Yes", testdata [, c ( '1Desire 11 ) 1 1 * tprior [ 11 Yes 11 1

prob_no <- ageCounts [ 11 No", testdata [, c ( '1Age") 11 * incomeCounts ["No 11 , testdata [, c ( 11 Income 11 ) 1 1 * jsCounts ["No", testdata [, c ( 11 JobSatisfaction") 1 1 * desireCounts [ "No'•, testdata [, c ( "Desire 11 ) 1 1 * tprior["No"1

max(prob_yes,prob_no)

As shown below, the predicted result of the test set is Enrolls= Yes.

prob_yes Yes

0.02821869

prob_no No

0.006857:..43

max(prob_yes, prob_no) [l! 0.0282l869

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

Theel o 71 package in R has a built-in nai veBayes function that can compute the conditional probabilities of a categorical class variable given independent categorical predictor variables using the Bayes rule. The function takes the form of nai veBayes (formula I data I ••• ) I where the argu- ments are defined as follows.

o formula: A formula ofthe form class - xl + x2 + ... assuming xll x2 ... are conditionally independent

o data: A data frame of factors

Use the following code snippet to execute the model and display the results.

model <- naiveBayes(Enrolls - Age+Income+JobSatisfaction+Desire 1 traindata)

# display model

model

The output that follows shows that the probabilities of model match the probabilities from the previous method. The default laplace= laplace setting enables the Laplace smoothing.

Naive Bayes Classif~er f2r Discrete Predictors

Call:

naiveBayes.default'v '!, laplace laplace,

h-priori probabilit~es: y No ''les

0.0000000 0.35714~9 0.6428571

Conditional probabilities:

P..ge y >40 31 to 40

No 0.6000000 0.4000000 0.0000000

Yes 0. 2222222 0. 33 3333~ 0 . •l444•l4'l

Income y High LO'd i•ledium

No 0 .4000000 C.20000,'JO ·:J . ·l 0 0 :) 0 0 0

"/es 0.2222222 0 3 3 3 3 3 3 ~ 0 .. J.;4444·l

~obSatisfac:ion

"l No Y•:;:"

No 0 8 0 8• ()I~ 0 c ~ ] ~c~' ·:: 0 ;J '£es 0.3333333 il.((GhGE7

y

Desire

Excellent Fair

No 0.6000000 0.40COOOO Yes 0.3333333 0.6666667

7.2 Na'ive Bayes

Next, predicting the outcome of Enrolls with the t es tda t a shows the result is Enrolls= Yes.

# predict with testdata results <- predict (model,testdata) # display results results [l] Yes

Levels: ~~o Yes

The nai veBayes function accepts a Laplace parameter that allows the customization of the c value of Equation 7-17 for the Laplace smoothing. The code that follows shows how to build a na"ive Bayes clas- sifier with Laplace smoothing c = 0.01 for prediction. # use the NB classifier with Laplace smoothing modell = naiveBayes(Enrolls -., traindata, laplace=.Ol)

# display model

modell Naive Bayes Classifier for ~~scre~e ?redictcrs

Call: naiveaayes.defaul:,v Z, y

h-priori probabilities: y

0.0000000 0.3571429 C.642857l

Conditional probabilities: .i'-.ge

y < = 3 C: >~ '= 0.333333333 0 333333332

No 0 598409543 0 399602386

Yes 0.222591362 0 ::33333333

Inco:ne y High Low

Y, laplace

Jl to .;o 0 333333333

0 00198807:.2

0 .444075305

t·ledium

0.3333333 0.3333333 O.l333333

No 0.3996024 0.2007952 0.3996024 Yes 0.2225914 0.33:33333 0.4440753

laplace1

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

y

r:

The test case is again classified as Enroll s=Yes.

:: predirt ·.·:.:..~"" .. · ~ d:-1 .. ~

results! <- predict (modell,testdata)

results!

~ v ...

7.3 Diagnostics of Classifiers So far, this book has talked about three classifiers: logistic regression, decision trees, and na"lve Bayes. These

three methods can be used to classify instances into distinct groups according to the similar characteristics

they share. Each of these classifiers faces the same issue: how to evaluate if they perform well.

A few tools have been designed to evaluate the performance of a classifier. Such tools are not limited

to the three classifiers in this book but rather serve the purpose of assessing classifiers in general.

A confusion matrix is a specific table layout that allows visualization of the performance of a classifier.

Table 7-6 shows the confusion matrix for a two-class classifier. True positives (TP) are the number

of positive instances the classifier correctly identified as positive. False positives (FP) are the number of

instances in which the classifier identified as positive but in reality are negative. True negatives (TN) are the number of negative instances the classifier correctly identified as negative. False negatives (FN) are the

number of instances classified as negative but in reality are positive. In a two-class classification, a preset threshold may be used to separate positives from negatives. TP and TN are the correct guesses. A good

classifier should have large TP and TN and small (ideally zero) numbers for FP and FN.

TABLE 7 6 Confusion Matrix

True Positives (TP) False Negatives (FN)

False Positives (FP) True Negatives (TN)

7.3 Diagnostics of Classifiers

In the bank marketing example, the training set includes 2,000 instances. An additional100 instances are included as the testing set. Table 7-7 shows the confusion matrix of a na"ive Bayes classifier on 100 clients to predict whether they would subscribe to the term deposit. Of the 11 clients who subscribed to the term deposit, the model predicted 3 subscribed and 8 not subscribed. Similarly, of the 89 clients who did not subscribe to the term, the model predicted 2 subscribed and 87 not subscribed. All correct guesses are located from top left to bottom right of the table. It's easy to visually inspect the table for errors, because they will be represented by any nonzero values outside the diagonal.

TABLE 7-7 Confusion Matrix of Naive Bayes from the Bank Marketing Example

The accuracy {or the overall success rate) is a metric defining the rate at which a model has classified the records correctly. It is defined as the sum ofTP and TN divided by the total number of instances, as shown in Equation 7-18.

TP+TN Accuracy= x 100%

TP+TN+FP+FN (7-18)

A good model should have a high accuracy score, but having a high accuracy score alone does not guarantee the model is well established. The following measures can be introduced to better evaluate the performance of a classifier.

As seen in Chapter 6, the true positive rate (TPR) shows what percent of positive instances the classifier correctly identified. It's also illustrated in Equation 7-19.

TPR = ____!!!___ TP+FN

(7-19)

The false positive rate {FPR) shows what percent of negatives the classifier marked as positive. The FPR is also called the false alarm rate or the type I error rate and is shown in Equation 7-20.

FPR=_!!_ FP+TN

(7-20)

The false negative rate (FNR) shows what percent of positives the classifier marked as negatives. It is also known as the miss rate or type II error rate and is shown in Equation 7-21. Note that the sum of TPR and FNR is 1.

FNR=__!!!_ TP+FN

{7-21)

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

A well-performed model should have a high TPR that is ideally 1 and a low FPR and FNR that are ideally 0. In reality, it's rare to have TPR = 1, FPR = 0, and FNR = 0, but these measures are useful to compare the perfor- mance of multiple models that are designed for solving the same problem. Note that in general, the model that is more preferable may depend on the business situation. During the discovery phase of the data analytics lifecycle, the team should have learned from the business what kind of errors can be tolerated. Some business situations are more tolerant of type I errors, whereas others may be more tolerant of type II errors. In some cases, a model with a TPR of 0.95 and an FPR of 0.3 is more acceptable than a model with a TPR of 0.9 and an FPR of 0.1 even if the second model is more accurate overall. Consider the case of e-mail spam filtering. Some people (such as busy executives) only want important e-mail in their inbox and are tolerant of having some less important e-mail end up in their spam folder as long as no spam is in their inbox. Other people may not want any important or less important e-mail to be specified as spam and are willing to have some spam in their in boxes as long as no important e-mail makes it into the spam folder.

Precision and recall are accuracy metrics used by the information retrieval community, but they can be used to characterize classifiers in general. Precision is the percentage of instances marked positive that really are positive, as shown in Equation 7-22.

, . . TP rfeCISIOn = ---

TP+fP (7-22)

Recall is the percentage of positive instances that were correctly identified. Recall is equivalent to the TPR. Chapter 9, "Advanced Analytical Theory and Methods: Text Analysis," discusses how to use precision and recall for evaluation of classifiers in the context of text analysis.

Given the confusion matrix from Table 7-7, the metrics can be calculated as follows:

TP+TN 3+87 Accuracy= x 1 00% = x 100% = 90%

TP+ TN +FP+FN 3+87 +2+8 TP 3

TPR (or Recall)=--=--~ 0.273 TP+FN 3+8

FPR = _FP_ = - 2- ~ 0.022 FP+TN 2+87

FNR = _FN_ = - 8- ~ 0.727 TP+FN 3+8

, . . TP 3 06 rreCISIOn = ---= -- = .

TP+FP 3+2

These metrics show that for the bank marketing example, the na"ive Bayes classifier performs well with accuracy and FPR measures and relatively well on precision. However, it performs poorly on TPR and FNR. To improve the performance, try to include more attributes in the datasets to better distinguish the characteristics of the records. There are other ways to evaluate the performance of a classifier in general, such as N-fold cross validation (Chapter 6) or bootstrap [14].

Chapter 6 has introduced the ROC curve, which is a common tool to evaluate classifiers. The abbre- viation stands for receiver operating characteristic, a term used in signal detection to characterize the trade-off between hit rate and false-alarm rate over a noisy channel. A ROC curve evaluates the performance of a classifier based on the TP and FP, regardless of other factors such as class distribution and error costs. The vertical axis is the True Positive Rate (TPR), and the horizontal axis is the False Positive Rate (FPR).

7.3 Diagnostics of Classifiers

As seen in Chapter 6, any classifier can achieve the bottom left of the graph where TPR = FPR = 0 by classifying everything as negative. Similarly, any classifier can achieve the top right of the graph where TPR = FPR = 1 by classifying everything as positive. If a classifier performs "at chance" by random guessing the results, it can achieve any point on the diagonal line TPR=FPR by choosing an appropriate threshold of positive/negative. An ideal classifier should perfectly separate positives from negatives and thus achieve the top-left corner (TPR = 1, FPR = 0). The ROC curve of such classifiers goes straight up from TPR = FPR = 0 to the top-left corner and moves straight right to the top-right corner. In reality, it can be difficult to achieve the top-left corner. But a better classifier should be closer to the top left, separating it from other classifiers that are closer to the diagonal line.

Related to the ROC curve is the area under the curve (AUC). The AUC is calculated by measuring the area under the ROC curve. Higher AUC scores mean the classifier performs better. The score can range from 0.5 (for the diagonal line TPR=FPR) to 1.0 (with ROC passing through the top-left corner).

In the bank marketing example, the training set includes 2,000 instances. An additional100 instances are included as the testing set. Figure 7-10 shows a ROC curve ofthe na'ive Bayes classifier built on the training set of 2,000 instances and tested on the testing set of 100 instances. The figure is generated by the following R script. The ROCR package is required for plotting the ROC curve. The 2,000 instances are in a data frame called bank train, and the additional100 instances are in a data frame called bank test.

library (ROCR)

# training set banktrain <- read.table("bank-sample.csv",header=TRUE,sep=",") # drop a few columns drops<- c("balance", "day", "campaign", "pdays", "previous 11 , "month") banktrain <- banktrain [,! (names(banktrain) %in% drops)]

# testing set banktest <- read.table("bank-sample-test.csv",header=TRUE,sep= 11 , 11 ) banktest <- banktest [,! (names(banktest) %in% drops)]

# build the naive Bayes classifier nb_model <- naiveBayes(subscribed-.,

data=banktrain) # perform on the testing set nb_prediction <- predict(nb_model,

# remove column "subscribed" banktest[,-ncol(banktest)], type=' raw' )

score <- nb _prediction [, c ("yes") 1

actual_class <- banktest$subscribed == 'yes'

pred <- prediction(score, actual_class)

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

perf <- performance (pred, "tpr" , " fpr " )

plot(perf, lwd=2, xlab="False Positive Rate (FPR) ", ylab="True Positive Rate (TPR) " )

abline (a=O, b=l, col="gray50" , lty=3 )

The following R code shows that the corresponding AUC score of the ROC curve is about 0.915.

auc < - performance (pred, "auc" ) auc <- unlist (slot (auc, "y . values" )) auc

0

(X)

[ 0 t:.

"' U) 1;j 0 a: "' > Q .... ill 0 0

Q.

"' 2 N .... 0

0 0

00 02 04 06

False PoSlOve Rate (FPR)

08 10

FIGURE 7 10 ROC curve of the naive Bayes classifier on the bank marketing dataset

7.4 Additional Classification Methods Besides the two classifiers introduced in this chapter, several other methods are commonly used for clas- sification, including bagging [15], boosting [5], random forest [4], and support vector machines (SVM) [16]. Bagging, boosting, and random forest are all examples of ensemble methods that use multiple models to obtain better predictive performance than can be obtained from any of the constituent models.

Bagging (or bootstrap aggregating) [15] uses the bootstrap technique that repeatedly samples with replacement from a dataset accord ing to a uniform probability distribution. "With replacement" means

that when a sample is selected for a training or testing set, the sample is still kept in the dataset and may be selected again. Because the sampling is with replacement, some samples may appear several times in a training or testing set, whereas others may be absent. A model or base classifier is trained separately on each bootstrap sample, and a test sample is assigned to the class that received the highest number of votes.

Similar to bagging, boosting (or Ada Boost) [17] uses votes for classification to combine the output of indi-

vidual models. In addition, it combines models of the same type. However, boosting is an iterative procedure

Summary

where a new model is influenced by the performances of those models built previously. Furthermore,

boosting assigns a weight to each training sample t hat reflects its importance, and the weight may adap-

tively change at the end of each boosting round. Bagging and boosting have been shown to have better

performances [5) than a decision tree.

Random forest [4] is a class of ensemble methods using decision tree classifiers. It is a combination of tree

predictors such that each tree depends on the values of a random vector sampled independently and with

the same distribution for all trees in the forest. A special case of random forest uses bagging on decision

trees, where samples are randomly chosen with replacement from the original training set.

SVM [16] is another common classification method that combines linear models with instance-based

learning techniques. Support vector machines select a small number of critical boundary instances cal led

support vectors from each class and build a linear decision function that separates them as widely as

possible. SVM by default can efficiently perform linear classifications and can be configured to perform

nonlinear classifications as well.

Summary This chapter focused on two classification methods: decision trees and na'ive Bayes. It discussed the theory

behind these classifiers and used a bank marketing example to explain how the methods work in practice.

These classifiers along with logistic regression (Chapter 6) are often used for the classification of data. As

this book has discussed, each of these methods has its own advantages and disadvantages. How does one

pick t he most suitable method for a given classification problem? Table 7-8 offers a list of things to consider

when selecting a classifier.

TABLE 7·8 Choosing a Suitable Classifier

Concerns Recommended Method(s)

Output ofthe classification should include class Logistic regression, decision tree

probabilities in addition to the class labels.

Analysts want to gain an insight into how the vari- Logistic regression, decision tree

abies affect the model.

The problem is h igh dimensional. Na'ive Bayes

Some of the input variables might be correlated. Logistic regression, decision tree

Some of the input variables might be irrelevant. Decision tree, na'ive Bayes

The data contains categorical variables with a Decision tree, na'ive Bayes large number of levels.

The data contains mixed variable types. Logistic regression, decision tree

There is nonlinear data or discontinuities in the Decision tree

input variables that would affect the output.

ADVANCED ANALYTICAL THEORY AND METHODS: CLASSIFICATION

After the classification, one can use a few evaluation tools to measure how well a classifier has performed

or compare the performances of multiple classifiers. These tools include confusion matrix, TPR, FPR, FNR, precision, recall, ROC curves, and AUC.

In addition to the decision trees and na'ive Bayes, other methods are commonly used as classifiers. These

methods include but are not limited to bagging, boosting, random forest, and SVM.

Exercises 1. For a binary classification, describe the possible values of entropy. On what conditions does

entropy reach its minimum and maximum values?

2. In a decision tree, how does the algorithm pick the attributes for splitting?

3. John went to see the doctor about a severe headache. The doctor selected John at random to have a blood test for swine nu, which is suspected to affect 1 in 5,000 people in this country. The test is 99% accurate, in the sense that the probability of a false positive is 1%. The probability of a false negative is zero. John's test came back positive. What is the probability that John has swine flu?

4. Which classifier is considered computationally efficient for high-dimensional problems? Why?

5. A data science team is working on a classification problem in which the dataset contains many correlated variables, and most of them are categorical variables. Which classifier should the team consider using? Why?

6. A data science team is working on a classification problem in which the dataset contains many correlated variables, and most of them are continuous. The team wants the model to output the probabilities in addition to the class labels. Which classifier should the team consider using? Why?

7. Consider the following confusion matrix:

What are the true positive rate, false positive rate, and false negative rate?

Bibliography

Bibliography [1] M. Thomas, B. Pang, and L. Lee, "Get Out the Vote: Determining Support or Opposition from

Congressional Floor-Debate Transcripts," in Proceedings of the 2006 Conference on Empirical Methods in Natural Language Processing, Sydney, Australia, 2006.

[2) M. Shouman, T. Turner, and R. Stocker, "Using Decision Tree for Diagnosing Heart Disease Patients," in Australian Computer Society, Inc., Ballarat, Australia, in Proceedings of the Ninth Australasian Data Mining Conference (AusDM '11).

[3) I. Androutsopoulos, J. Koutsias, K. V. Chandrinos, G. Paliouras, and C. D. Spyropoulos, "An Evaluation of Na'fve Bayesian Anti-Spam Fi ltering," in Proceedings of the Workshop on Machine Learning in the New Information Age, Barcelona, Spain, 2000.

[4) L. Brei man, "Random Forests," Machine Learning, vol. 45, no. 1, pp. 5- 32, 2001 . [5] J. R. Quinlan, "Bagging, Boosting, and C4. 5," AAAI/IAAI, vol. 1, 1996. [6) S. Moro, P. Cortez, and R. Laureano, "Using Data Mining for Bank Direct Marketing: An Application

of the CRISP-DM Methodology," in Proceedings of the European Simulation and Modelling Conference- ESM'2011, Guimaraes, Portugal, 2011.

[7) J. R. Quinlan, "Induction of Decision Trees," Machine Learning, vol. 1, no. 1, pp. 81-106, 1986. [8) J. R. Quinlan, C4. 5: Programs for Machine Learning, Morgan Kaufmann, 1993. [9) L. Brei man, J. H. Friedman, R. A. Olshen, and C. J. Stone, Classification and Regression Trees,

Belmont, CA: Wadsworth International Group, 1984. [10) T. M. Mitchell, "Decision Tree Learning," in Machine Learning, New York, NY, USA, McGraw-Hill, Inc.,

1997, p. 68. [11) C. Phua, V. C. S. Lee, S. Kate, and R. W. Gayler, "A Comprehensive Survey of Data Mining-Based Fraud

Detection," CaRR, vol. abs/1009.6119, 2010. [12) R. Bhowmik, "Detecting Auto Insurance Fraud by Data Mining Techniques," Journal of Emerging

Trends in Computing and Information Sciences, vol. 2, no. 4, pp. 156- 162,2011. [13) D. Michie, D. J. Spiegel halter, and C. C. Taylor, Machine Learning, Neural and Statistical

Classification, New York: Ell is Horwood, 1994. [14) I. H. Witten, E. Frank, and M. A. Hall, "The Bootstrap," in Data Mining, Burlington, Massachusetts,

Morgan Kaufmann, 2011, pp. 155-156. [15) L. Breiman, "Bagging Predictors," Machine Learning, vol. 24, no. 2, pp. 123-140, 1996. [16) N. Cristianini and J. Shawe-Taylor, An Introduction to Support Vector Machines and Other Kernel-

Based Learning Methods, Cambridge, United Kingdom: Cambridge university press, 2000. [17) Y. Freund and R. E. Schapire, "A Decision-Theoretic Generalization of On-Line Learning and an

Application to Boosting," Journal of Computer and System Sciences, vol. 55, no. 1, pp. 119-139, 1997.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

This chapter examines the topic of time series analysis and its applications. Emphasis is placed on identifying the underlying structure of the time series and fitting an appropriate Autoregressive Integrated Moving

Average (ARIMA) model.

8.1 Overview of Time Series Analysis Time series analysis attempts to model the underlying structure of observations taken over time. A time series, denoted Y = a+ bX , is an ordered sequence of equally spaced values over time. For example, Figure 8-1 provides a plot of the monthly number of international airline passengers over a 12-year period.

u;- '0 c ro

0 V> ::J 0 0 I()

§. V>

iii 0 0) c 0 Q) (")

V> V> ro 0.. ~ 0

< 0

0 20 40 60 80 100 120 140

Time (Monlhs)

FIGURE 8-1 Monthly international airline passengers

In this example, the time series consists of an ordered sequence of 144 values. The analyses presented in this chapter are limited to equally spaced time series of one variable. Following are the goals of time series analysis:

• Identify and model the structure of the time series.

• Forecast future values in the time series.

Time series analysis has many applications in finance, economics, biology, engineering, retai l, and manufacturing. Here are a few specific use cases:

• Retai l sa les: For various product lines, a clothing retailer is looking to forecast future monthly sa les. These forecasts need to account for the seasonal aspects of the customer's purchasing decisions. For example, in the northern hemisphere, sweater sales are typically brisk in the fall season, and swimsuit sales are the highest during the late spring and early summer. Thus, an appropriate time series model needs to account for fluctuating demand over the ca lendar year.

• Spare parts planning: Companies' service organizations have to forecast future spare part demands to ensure an adequate supply of parts to repair customer products. Often the spares inven- tory consists of thousands of distinct part numbers. To forecast future demand, complex models for each part number can be built using input variables such as expected part failure rates, service diag- nostic effectiveness, forecasted new product shipments, and forecasted trade-ins/decommissions.

8.1 Overview ofTime Series Analysis

However, time series analysis can provide accurate short-term forecasts based simply on prior spare part demand history.

• Stock trading: Some high-frequency stock traders utilize a technique called pairs trading. In pairs trading, an identified strong positive correlation between the prices of two stocks is used to detect a market opportunity. Suppose the stock prices of Company A and Company B consistently move together. Time series analysis can be applied to the difference of these companies' stock prices over time. A statistically larger than expected price difference indicates that it is a good time to buy the stock of Company A and sell the stock of Company B, or vice versa. Of course, th is trading approach depends on the abi lity to execute the trade quickly and be able to detect when the correlation in the stock prices is broken. Pairs trading is one of many techniques that fa lls into a trading strategy called statistical arbitrage.

8.1 .1 Box-Jenkins Methodology In this chapter, a time series consists of an ordered sequence of equally spaced values over time. Examples

of a time series are monthly unemployment rates, daily website visits, or stock prices every second. A time series can consist of the following components:

• Trend

• Seasonality

• Cyclic

• Random

The trend refers to the long-term movement in a time series. It indicates whether the observation values are increasing or decreasing over t ime. Examples of trends are a steady increase in sales month over month or an annual decline of fata lities due to car accidents.

The seasonality component describes the fixed, periodic fluctuation in the observations over time. As the name suggests, the seasonality component is often related to the calendar. For example, monthly retail sales can fluctuate over the year due to the weather and holidays.

A cyclic component also refers to a periodic fluctuation, but one that is not as fixed as in the case of a seasonality component. For example, retails sales are influenced by the general state of the economy. Thus, a retail sales time series can often follow the lengthy boom-bust cycles of the economy.

After accounting for the other three components, the random component is what remains. Although noise is certainly part of this random component, there is often some underlying structure to this random component that needs to be modeled to forecast future values of a given time series.

Developed by George Box and Gwilym Jenkins, the Box-Jenkins methodology for time series analysis involves the following three main steps:

1. Condition data and select a model.

• Identify and account for any trends or seasonality in the time series.

• Examine the remaining time series and determine a suitable model.

2. Estimate the model parameters.

3. Assess the model and return to Step 1, if necessary.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

The primary focus of this chapter is to use the Box-Jenkins methodology to apply an A RIMA model to

a given time series.

To fully explain an ARIMA (Autoregressive Integrated Moving Average) model, this section describes the

model's various parts and how they are combined. As stated in the first step of the Box-Jenkins methodol-

ogy, it is necessary to remove any trends or seasonality in the time series. This step is necessary to achieve

a time series with certain properties to which autoregressive and moving average models can be appl ied.

Such a time series is known as a stationary time series. A time series, Y, fort = 1,2,3, ... ,, is a stationary time

series if the following three conditions are met:

(a) The expected value (mean) of Y, is a constant for all values oft.

(b) The variance of Y, is finite.

• (c) The covariance of Y, andY, h depends only on the value of h = 0, 1, 2, .. .for all t.

The covariance of Y, andY,. his a measure of how the two variables, Y, andY, _ h• vary together. It is expressed in Equation 8-1.

(8-1)

If two variables are independent of each other, their covariance is zero. If the variables change together

in the same direction, the variables have a positive covariance. Conversely, if the variables change together

in the opposite direction, the variables have a negative covariance.

For a stationary time series, by condition (a), the mean is a constant, say''· So, for a given stationary

sequence, Y,. the covariance notation can be simplified to what's shown in Equation 8-2.

(8-2)

By part (c), the covariance between two points in the time series can be nonzero, as long as the value

of the covariance is only a function of h. Equation 8-3 is an example for h = 3.

(8-3)

It is important to note that for h 0, the cov(O) = cov(y,,y,) = var(y,) fo r all t. Because the

var (y,) < , by condition (b), the variance of Y, is a constant for all t. So the constant variance coupled with part (a), E [y,] = I'· for all t and some constant 1', suggests that a stationary time series can look like Figure

8-2. In this plot, the points appear to be centered about a fixed constant, zero, and the variance appears to be somewhat constant over time.

8.2.1 Autocorrelation Function (ACF) Although there is not an overall trend in the time series plotted in Figure 8-2, it appears that each point is

somewhat dependent on the past points. The difficulty is that the plot does not provide insight into the

covariance of the variables in the time series and its underlying structure. The plot of autocorrelation

function (ACF) provides this insight. For a stationary time series, the ACF is defined as shown in Equation 8-4.

8.2 ARIMA Model

ACF (h)= cov(y,,y, . h) cov(h)

Jcov (y,, Y,) cov (y, . h, Y, h) cov(O) (8-4)

0 100 200 300 400 500 600

Time

fiGURE 8· A plot of a stationary series

Because the cov(O) is the variance, the ACF is analogous to the correlation function of two variables, carr (y,, Y, , h), and the value of the ACF falls between - 1 and 1. Thus, the closer the absolute value of ACF(h) is to 1, the more useful Y, can be as a predictor of Y, . h .

Using the same dataset plotted in Figure 8-2, the plot of the ACF is provided in Figure 8-3.

~ -

CD c) -

u.. (() 0 c) <i

<:J: 0

~ 0 JIJIIJ I l I I _l

I I

0 5 10 15 20 25

Lag

f iGURE 8-3 Autocorrelation function (ACF)

By convention, the quantity h in the ACF is referred to as the lag, the difference between the time points t and t +h. At lag 0, the ACF provides the correlation of every point with itself. So ACF(O) always equals 1. According to the ACF plot, at lag 1 the correlation between Y, andY, 1 is approximately 0.9, which is very close to 1. SoY, 1 appears to be a good predictor of the value of Y,· Because ACF(2) is around 0.8, Y, 2 also appears to be a good predictor of the value of Y,. A similar argument could be made for lag 3 to lag 8. (All

the autocorrelations are greater than 0.6.) In other words, a model can be considered that would express Y, as a linear sum of its previous 8 terms. Such a model is known as an autoregressive model of order 8.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

8.2.2 Autoregressive Models For a stationary time series, y, t= 1, 2, 3, ... , an autoregressive model of order p, denoted AR(p), is expressed as shown in Equation 8-5:

Y, =5+4i Yr-1 +~Yr-2 + ... +~Yr-p +c,

where 6 is a constant for a nonzero-centered time series: <f1 is a constant for j = 1, 2, ... , p Y, _ i is the value of the time series at timet - j ¢p ;:0 c-,- N (0, CT~) for all t

(8-5)

Thus, a particular point in the time series can be expressed as a linear combination of the prior p values, Y, _ i for j = 1, 2, ... p, of the time series plus a random error term, c,. In this definition, the c, time series is often called a white noise process and is used to represent random, independent fluctuations that are part of the time series.

From the earlier example in Figure 8-3, the autocorrelations are quite high for the first several lags. Although it appears that an AR(8) model might be a good candidate to consider for the given dataset, examining an AR(l) model provides further insight into the ACF and the appropriate value of p to choose. For an AR(1) model, centered around 6 = 0, Equation 8-5 simplifies to Equation 8-6.

Y, =</J1 Yr-1 +c-, (8-6)

Based on Equation 8-6, it is evident that Yr-1 = ¢ 1 Y,_ 2 + c-,_ 1. Thus, substituting for y,_ 1 yields Equation 8-7.

Y, =4i(¢y,_2 +c,_1)+c,

= 4i2Yr-2 +<Acr-1 +c, (8-7)

Therefore, in a time series that follows an AR(1) model, considerable autocorrelation is expected at lag 2. As this substitution process is repeated, Y, can be expressed as a function of Y, -h for h = 3, 4 ... and a sum of the error terms. This observation means that even in the simple AR(1) model, there will be considerable autocorrelation with the larger lags even though those lags are not explicitly included in the model. What is needed is a measure ofthe autocorrelation between Y, andY,+ h for h = 1, 2, 3 ... with the effect of the Y, + 1 toY,+ h _ 1 values excluded from the measure. The partial autocorrelation function (PACF) provides such a measure and is expressed as shown in Equation 8-8.

PACF(h)=corr(y,- y;,y,+h- y;+h)forh~2

=corr(y,,y,+1) forh=1 (8-8)

where y; = !31Yr+1 + J32Yr+2 ··· + J3h-1Yt+h-1, y;+h = J3,Yr+h-1 + J32Yr+h-2 ... + J3h-1Yr+1 I and the h-1 values of the J3s are based on linear regression.

8.2 A RIMA Model

In other words, after linear regression is used to remove the effect of the variables between Y, andY, , h

on Y, andY, +-1, , the PACF is the correlation of what remains. For h = 1, there are no varia bles between Y, and Y, ~ 1• So the PACF(1) equals ACF(1). Although the computation of the PACF is somewhat complex, many software tools hide this complexity from the analyst.

For the earlier example, the PACF plot in Figure 8-4 illustrates that after lag 2, the value of the PACF is

sha rply reduced. Thus, after removing the effects of Y, , 1 andY, , 2, the partial correlation between

Y, and Y, _3 is relatively small. Similar observations can be made for h = 4, 5, .... Such a plot indicates that

an AR(2) is a good candidate model for the time series plotted in Figure 8-2. 1n fact, the time series data for

this example was randomly generated based on Y, = 0.6y, 1 + 0.35y, 2 +£, where £, - N(O, 4) .

~ 0

~ lL 0 () ~

'<I: ro 0 t C1l

0... ~ 0

q I I I 0 I I I I

I I I I

0 5 10 15 20 25

Lag

FIGURE 8-4 Partial autocorrelation function (PACF) plot

Because the ACF and PACF are based on correlations, negative and positive values are possible. Thus,

the magnitudes of the functions at the various lags should be considered in terms of absolute va lues.

8.2.3 Moving Average Models For a time series, y

1 , centered at zero, a moving average model of order q, denoted MA(q), is expressed

as shown in Equation 8-9.

where Ok is a constant fork = 1, 2, ... , q oq "" o t:

1 - N (0, a1 ) for all t

(8-9)

In an MA(q) model, the value of a time series is a linear combination of the current white noise term and

the prior q white noise terms. So earlier random shocks directly affect the current value of the time series. For

MA(q) models, the behavior of the ACF and PACF plots are somewhat swapped from the behavior of these plots for AR(p) models. For a simulated MA(3) time series of the form Y, = E1 - 0.4 E, 1 + 1.1 £1 2 - 2.S E:1 3 where e, - N(O, 1), Figure 8-5 provides the scatterplot of the simulated data over time.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

0 0

0 100 200 300 400 500 600

Time

FIGURE 8-5 Scatterplot of a simulated MA(3) time series

Figure 8-6 provides the ACF plot for the simulated data. Again, the ACF(O) equals 1, because any vari- able is perfectly correlated with itself. At lags 1, 2, and 3, the value of the ACF is relatively large in absolute

value compared to the subsequent terms. In an autoregressive model, the ACF slowly decays, but for an MA(3) model, the ACF somewhat abruptly cuts off after lag 3. In general, this pat tern can be extended to any MA(q) model.

C) -

- <D c) -

IJ.. - 0 < N -c)

I I

I I I

N 9 - I I

I I I I

0 5 10 15 20 25

Lag

FIGURE 8-6 ACF plot of a simulated MA(3) time series

To understand why this phenomenon occurs, it is useful to examine Equations 8-10 through 8-14 for an MA(3) time series model:

8.2 ARIMA Model

Yr = er + (}1 er-1 + (}2 €1-2 + ()3 Er-a Y1-1 = £1-1 + 01 £1-2 + (}2 £1-3 + fJ3 et-1

£H + (}1 £1-3 + 02 el-·1 + 03 €1 € 1-3 + 61£ 1-1 + 02£ Hi +Ol

Y1-2 =

Yl-3 =

Yl-4 = € r-1 + 01£ 1-a +02€ r-6 + (}3

(8-10)

(8-11)

(8-12)

(8-13)

(8-14)

Because the expression of Y1 shares specific white noise variables with the expressions for Y1 _ 1 through Y1 _ 3, inclusive, those three variables are correlated to y1• However, the expression of Yr in Equation 8-10 does not share white noise variables with Y1_ 4 in Equation 8-14. So the theoretical correlation between Y1 and Y1 _ 4 is zero. Of course, when dealing with a particular dataset, the theoretical autocorrelations are unknown, but the observed autocorrelations should be close to zero for lags greater than q when working with an MA(q) model.

8.2.4 ARMA and ARIMA Models In general, the data scientist does not have to choose between an AR(p) and an MA(q) model to describe a time series. In fact, it is often useful to combine these two representations into one model. The combination of these two models for a stationary time series results in an Autoregressive Moving Average model, ARMA(p,q), which is expressed as shown in Equation 8-15.

Yr =15 +4>, Y,_. +t/>2 Yr-2 + ... +¢ P Yr-p + g I + 91 g I_ 1 + ... + {Jq g I_ q

where 15 is a constant for a nonzero-centered time series

4> i is a constant for j = 1, 2, ... , p

tj>P=;e.O

(}*is a constant fork= 1, 2, ... , q

oq =;e.O c

1 - N (0, a~) for all t

(8-15)

If p = 0 and q =;e. 0, then the ARMA(p,q) model is simply an AR(p) model. Similarly, if p = 0 and q =;e. 0, then the ARMA(p,q) model is an MA(q) model.

To apply an ARMA model properly, the time series must be a stationary one. However, many time series exhibit some trend over time. Figure 8-7 illustrates a time series with an increasing linear trend over time. Since such a time series does not meet the requirement of a constant expected value (mean), the data needs to be adjusted to remove the trend. One transformation option is to perform a regres- sion analysis on the time series and then to subtract the value of the fitted regression line from each observed y-value.

If detrending using a linear or higher order regression model does not provide a stationary series, a second option is to compute the difference between successive y-values. This is known as differencing. In other words, for the n values in a given time series compute the differences as shown in Equation 8-16.

d 1 = Y,- y1 _ 1 fort=2,3, ... ,n (8-16)

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

0 "' -

0 0

0

"' 0

0 0 0

0

FIGURE 8-7 A rime series wirh a rrend

I

10 20 30

T1me

I I

40 50

The mean of the time series plotted in Figure 8-8 is certainly not a constant. Applying differencing to

the time series results in the plot in Figure 8-9. This plot illustrates a time series with a constant mean and a fairly constant variance over time.

g -

0 (0 -

>-

0 '<I' -

0 N -

I I I I

0 50 100 150

T1me

FIGURE 8-8 Time series for differencing example

If the differenced series is not reasonably stationary, applying differencing additional times may help. Equation 8-17 provides the twice differenced time series for r = 3, 4, ... n.

d, _,- d, 2={ y, - y, ,) - {y, , - y, 2)

= Y, - 2y, , 1- Y, 2 {8-17)

Successive differencing can be applied, but over-differencing should be avoided. One reason is that over-differencing may unnecessarily increase the variance. The increased variance can be detected by

plotting the possibly over-differenced values and observing that the spread of the values is much larger, as seen in Figure 8-10 after differencing the va lues of y twice.

0

on 0 ..... I

0 50 100

Time

FIGURE 8-9 Detrended time series using differencing

Cll u

~ on

0

0 0 0

0 0 0

o oo o o oo o oo

8.2 A RIMA Model

150

0

0

0) c u c Cll Q:;

:t::

oo o 0 o0 0 o o o~ oo o oo ooo o Cb CO>"'" o o9 ooo o ooo o 0 9 0 0 ,... " 9 0 ,,p ""' 0 Qo o '0 ...

Cll

15 en Cll ::J (ij > >

on ..... I

0

FIGURE 8-10 Twice differenced series

0

9 9

50 100 150

Time

Because the need to make a time series stationary is common, the differencing can be included (inte- grated) into the ARMA model definition by defining the Autoregressive Integrated Moving Average model, denoted ARIMA(p,d,q). The structure of the ARIMA model is identica l to the expression in

Equation 8-15, but the ARMA(p,q) model is applied to the time series, Y,, after applying differencing d times. Additionally, it is often necessary to account for seasonal patterns in time series. For example, in the

retail sales use case example in Section 8.1, monthly clothing sales track closely with the calendar month. Similar to the earlier option of detrending a series by first applying linear regression, the seasonal pattern could be determined and the time series appropriately adjusted. An alternative is to use a seasonal autoregressive integrated moving average model, denoted ARIMA(p,d,q) x (P,D,Q), where:

• p, d, and q are the same as defined previously.

• s denotes the seasonal period.

• Pis the number of terms in the AR model across the s periods.

• Dis the number of differences applied across the s periods.

• Q is the number of terms in the MA model across the s periods.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

For a time series with a seasonal pattern, following are typical values of s:

• 52 for weekly data

• 12 for monthly data

• 7 for daily data

The next section presents a seasonal ARIMA example and describes several techniques and approaches to identify the appropriate model and forecast the future.

8.2.5 Building and Evaluat ing an ARIMA Model For a large country, the monthly gasoline production measured in millions of barrels has been obtained

for the past 240 months (20 years). A market research firm requires some short-term gasoline production

forecasts to assess the petroleum industry's ability to deliver future gasoline supplies and the effect on gasoline prices.

l i brary (f orecast )

~ read in gasoline produc•1on t1me series M monthly gas producti n •xpte~dEd in mill1ons of barrels gas__prod_ input <- as. data . f rame ( r ead.csv ( "c: / data / gas__prod. csv" )

~create a time seti s ob1e·t gas__prod <- ts (gas__prod_input[ , 2])

Hexamine the time series plo t (gas __prod, xlab = "Time (months) ",

ylab = "Gas oline production (mi llions of barrels ) " )

Using R, the dataset is plotted in Figure 8-11.

U> a; t:: ., D

0 0 0 (I) v c 0

~ 0 co c (") 0

""' 0 :> '0 0 0 <D a. (") Cl> s 0 0 (I) ro ;3; (!)

0 50 100 150 200

Time (months)

FIGURE 8 11 Monthly gasoline production

8 .2 A RIMA Model

In R, the ts () function creates a t ime series object from a vector or a matrix. The use of time series objects in R simplifies the analysis by providing several methods that are tailored specifical ly for handling equal ly time spaced data series. For example, the plot ( ) function does not require an explicitly speci- fied variable for the x-axis.

To apply an ARMA model, the dataset needs to be a stationary time series. Using the d i f f () function, the gasoline production time series is differenced once and plotted in Figure 8-12.

plot(di ff(gas _prod ))

abline (a =O , b =O)

0 ...,

0 N

::0 0 e '1 "' 0 ro !!: :::: 0 '6 ~

' 0 ~

0 <{

0 50 100 150 200

FtGURE 8·12 Differenced gasoline production time series

The differenced time series has a constant mean near zero with a fairly constant variance over time. Thus, a stationary time series has been obtained. Using the following R code, the ACF and PACF plots for the differenced series are provided in Figures 8-13 and 8-14, respectively.

# exam nt ACF and PArF of difftrenced ser ~s acf(diff (ga s_prod), xaxp = c(O, 4 8, 4), l ag.max=48 , ma i n= " " )

pacf(diff (gas _prod) , xaxp = c(O , 48 , 4 ) , lag. max=48 , main='"' }

The dashed lines provide upper and lower bounds at a 95% significance level. Any value of the ACF or PACF outside of these bounds indicates that the va lue is significantly different from zero.

Figure 8-13 shows several signi f icant ACF values. The slowly decaying ACF values at lags 12, 24,

36, and 48 are of particular interest. A similar behavior in the ACF was seen in Figure 8-3, but for lags 1, 2, 3, ... Figure 8-13 indicates a seasonal autoregressive pattern every 12 months. Examining the PACF plot in Figure

8-14, the PACF value at lag 12 is quite large, but the PACF values are close to zero at lags 24, 36, and 48. Thus, a seasonal AR(1) model with period = 12 wi ll be considered. lt is often useful to address the seasonal portion of the overa ll ARMA model before addressing the nonseasonal portion of the model.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

u. u <

0 12

FIGURE 8 13 ACF of the differenced gasoline time series

u.

N 0

u 0 < 0 ;;; i: N 8'_ 9

0 12

FIGURE 8 1 PACF of the differenced gasoline time series

24

Lag

24

Lag

36 48

36 48

The a rima () function in R is used to fit a (0,1,0) x (1,0,0) 12

model. The analysis is applied to the original

time series variable, gas _prod. The differencing, d = 1, is specified by the order= c(0,1,0) term.

arima 1 <- arima (gas_prod, order=c(0 ,1, 0) , seasonal= list(order=c (1,0 , 0) ,period=1 2))

arima 1

s.e. O . .J32--i

sigmaA2 estimated as 37.29: log like:ihood=-778.69

AIC=l561.38 AICc=l561.43 BIC=l568.33

8.2 ARIMA Model

The value of the coefficient for the seasonal AR(1) model is estimated to be 0.8335 with a standard error of 0.0324. Because the estimate is several standard errors away from zero, this coefficient is consid- ered significant. The output from this first pass ARIMA analysis is stored in the variable arima _1, which contains several useful quantities including the residuals. The next step is to examine the residuals from fitting the (0, 1,0) x (1,0,0)12 A RIMA model. The ACF and PACF plots of the residuals are provided in Figures 8-15 and 8-16, respectively.

#examine ACF and PACF of the (O,l,O)x(l,O,O)l2 residuals acf(arima_l$residuals, xaxp = c(O, 48, 4), lag.max=48, main='11') pacf(arima_l$residuals, xaxp = c(O, 48, 4), lag.max=48, main= 1111 )

It)

0 LL 0 <

0 0

It)

q 0 12 24 36 48

Lag

FIGURE 8-15 ACF of residuals from seasonal AR(1) model

The ACF plot of the residuals in Figure 8-15 indicates that the autoregressive behavior at lags 12, 24, 26, and 48 has been addressed by the seasonal AR(1) term. The only remaining ACF value of any significance occurs at lag l.ln Figure 8-16, there are several significant PACF values at lags 1, 2, 3, and 4.

Because the PACF plot in Figure 8-16 exhibits a slowly decaying PACF, and the ACF cuts off sharply at lag 1, an MA(1) model should be considered for the nonseasonal portion of the ARMA model on the differenced series. In other words, a (0,1,1) x (1,0,0)12 ARIMA model will be fitted to the original gasoline production time series.

arima_2 <- arima (gas_prod, order=c(O,l,l), seasonal= list(order=c(l,O,O),period=l2))

arima_2

Series: gas_pr:Jd

.=-.P.I;·LZ.. ( 0' l' 1 ! :1' 0 ' 0 I [ L]

Coefficients:

mal sa.rl

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

acf(arima_2$res iduals, xaxp = c(O , 48 , 4 ) , lag .max=48, main="" ) pacf(arima_2$residuals , xaxp = c(O , 48 , 4 ) , l ag .max=48, main="" )

0

0 0

u. u < 15 N € 9 II) a.

oq-

9

0 12 24 36 48

Lag

FIGURE 8 16 PACF of residuals from seasonal AR(I) model

Based on the standard errors associated with each coefficient estimate, the coefficients are significantly different from zero. In Figures 8-17 and 8-18, the respective ACF and PACF plots for the residuals from the second pass ARIMA model indicate that no further terms need to be considered in the ARIMA model.

Cl

<D c)

10 0

u.. u oq- < 0

N 0

0 - -------------; -----i--------- ~ --------- - -- ------- --- i -------;-----

0

--------- j_ -- _I_ -~ ------ ~ ----------'--J _'_-- _'_ ---- ~ ~--__ '_-----~--- - -- ~ - 0 12 24 36 48

Lag

fiGURE 8 17 ACF for the residuals from the (0, 1, 1) x (1, 0,0)12 model

8.2 A RIMA Model

0 ~

ci OJ')

IL 0

q 0

c( 0 10 0 e ci ., a.

0 ~

9 --------------------------------------------------------------------

0 12 24

Lag

FrGURE 8-18 PACF for the residuals from the (0,1, l) x {1,0,0}12 model

36 48

It should be noted that the ACF and PACF plots each have several points that are close to the bounds at a 95% significance level. However, these points occur at rela tively large lags. To avoid overfi tting

the model, these values are attributed to random chance. So no attempt is made to include these

lags in the model. However, it is advisable to compare a reasonab ly fitting model to slight variations

of that model.

Comparing Fitted Time Series Models

The arima () function in Ruses Maximum Likelihood Estimation (MLE) to estimate the model coefficients. In the R output for an ARIMA model, the log-likelihood (logLl va lue is provided. The values of the model

coefficients are determined such that the value of the log likel ihood function is maximized. Based on the

log L value, the R output provides several measures that are useful for comparing the appropriateness of one fitted model against another fitted model. These measures follow:

• AIC (Aka ike Information Criterion)

• A ICc (Aka ike Information Criterion, corrected)

• BIC (Bayesian Information Criterion)

Because these criteria impose a penalty based on the number of parameters included in the models,

the preferred model is the fitted model with the smallest AI(. AICc, or BIC value. Table 8-1 provides the

information criteria measures for the ARIMA models already fitted as well as a few additional fitted models.

The highlighted row corresponds to the fitted ARIMA model obtained previously by examining the ACF

and PACF plots.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

TABLE 8 -1 Information Criteria to Measure Goodness of Fit

ARIMAModel (p,d,q) x (P,Q,0)

5 AIC AICc BIC

(0, 1 ,0) X (1 ,0,0)12 1561.38 1561.43 1568.33

(0 ,1,1) X (1,0,0)12 1472.43 1472.53 1482.86

(0,1,2) X (1,0,0)12 1474.25 1474.42 1488.16

(1,1,0) X (1,0,0)12 1504.29 1504.39 15 14.72

(1,1,1) X {1,0,0) 12 1474.22 1474.39 1488.12

In this dataset, the (0,1,1) x (1 ,0,0) 12

model does have the lowest AIC, AICc, and BIC values compared to

the same criterion measures for the other ARIMA models.

Normality and Constant Variance

The last model va lidation step is to examine the normality assumption of the residuals in Equation 8-15. Figure 8-19 indicates residuals with a mean near zero and a constant variance over time. The histogram in Figure 8-20 and the 0-0 plot in Figure 8-21 support the assumption that the error terms are normally

distributed. 0 -Q plots were presented in Chapter 6, "Advanced Analytical Theory and Methods: Regression."

plot(arima_2$residuals, ylab = "Residuals") abline(a=O , b=O)

hist (arima_2$residuals , xlab= "Residuals " , xlim=c ( -20 , 20) )

qqnorm(arima_2$r esidua l s, main= "" ) qqline(arima_2$residua l s)

"' 1/)

Iii ::> "0

0 ;;; .. 0:

'£?

0 ~

' l/) ~

' 0 50 100

Time

FIGURE 8-19 Plot of residuals from the fitted (0,1,1) x {1,0,0)12 model

150 200

0 (I)

0

~ co

c GJ ;::,

0 CT ~

<q'

lL

0 N

0 I I I

-20 -10 0

Residuals

FIGURE 8-20 Histogram of the residuals from the fitted (0,1,1) x {1,0,0) 12

model

10 T'""

0 T'""

fh GJ ::5 10 c (I) ;::, 0 0 GJ a. E aq (I) (/)

0 ...... I

l() .... I

-3 -2 -1 0

Theoretical auantiles

FIGURE 8-21 Q-Q plot of the residuals from the fitted (0,1,1) x (1,0,0) 12

model

8.2 ARIMA Model

I

I I

10 20

2 3

If the normality or the constant variance assumptions do not appear to be true, it may be necessary to transform the time series prior to fitting the ARIMA model. A common transformation is to apply a logarithm function.

Forecasting

The next step is to use the fitted (0,1,1) x (1,0,0)12 model to forecast the next 12 months of gasoline produc- tion.ln R, the forecasts are easily obtained using the predict () function and the fitted model already stored in the variable a rima_ 2. The predicted values along with the associated upper and lower bounds at a 95% confidence level are displayed in R and plotted in Figure 8-22.

#predict the next 12 months arima_2.predict <- predict(arima_2,n.ahead=l2)

matrix(c(arima_2.predict$pred-1.96*arima_2.predict$se,

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

arima_2.predict$pred, arima_2 .predict$pred+l . 96 *arima_2 .predict$se ) , 12,3, dimnames=list ( c(241:252) ,c (" LB","Pred","UB") )

-41 4.

242 37d.6ll. 4 1 94.9913

: H I 5.0188 • 45

plot (gas_prod, xlim=c (l45,2 52), xlab = "Time (months )" , ylab = "Gasoline production (millions of barrels ) ", ylim=c (360,44 0))

lines(ari ma_2 .predict$pred) lines(arima_2 .predict$pred+l . 96*arima_2 .predict$se , col=4 , lty=2) lines(ari ma_2 .predict$pred-1 . 96*arima_2 .predict $se , col=4 , lty=2)

"' ~ 0 '<f ro '<f .0

0 0

"' c N ~

'<T

§. 0 c 0 0 '<f Q 0 ::J '0 0 e <D a. r') Ql

.!: 0 0 "' <D ro r') (!)

160 180 200 220 240

nme (months)

FIGURE 8-22 Actual and forecasted gasoline production

8.2.6 Reasons to Choose and Cautions One advantage of ARIMA modeling is that the analysis can be based simply on historical time series data

for the variable of interest. As observed in the chapter about regression (Chapter 6), various input variables

8.3 Additional Methods

need to be considered and evaluated for inclusion in the regression model for the outcome variable. Because

A RIMA modeling, in general, ignores any additional input variables, the forecasting process is simplified.

If regression analysis was used to model gasoline production, input variables such as Gross Domestic

Product (GOP), oil prices, and unemployment rate may be useful input variables. However, to forecast the

gasoline production using regression, predictions are required for the GOP, oil price, and unemployment rate input variables.

The minimal data requirement also leads to a disadvantage of ARIMA modeling; the model does not

provide an indication of what underlying variables affect the outcome. For example, if ARIMA modeling

was used to forecast future retai l sales, the fi tted model would not provide an indication of what could be

done to increase sales. In other words, causal inferences cannot be drawn from the fitted ARIMA model.

One caution in using time series analysis is the impact of severe shocks to the system. In the gas pro-

duction example, shocks might include refinery fires, international incidents, or weather-related impacts

such as hurricanes. Such events can lead to short-term drops in production, followed by persistently high

increases in production to compensate for the lost production or to simply capital ize on any price increases.

Along simi lar lines of reasoning, time series analysis should only be used for short-term forecasts. Over

time, gasoline production vo lumes may be affected by changing consumer demands as a result of more

fuel-efficient gasoline-powered vehic les, electric vehicles, or the introduction of natural gas-powered

vehicles. Changing market dynamics in addition to shocks wi ll make any long-term forecasts, several years

into the future, very questionable.

8.3 Additional Methods Additional time series methods include the following:

• Autoregressive Moving Average with Exogenous inputs (ARM AX) is used to analyze a time series that is dependent on another time series. For example, retail demand for products can be modeled based on the previous demand combined with a weather-related time series such as tem- perature or rainfall.

• Spectral analysis is commonly used for signal processing and other engineering applications. Speech recognition software uses such techniques to separate the signal for the spoken words from the overall signal that may include some noise.

• Generalized Autoregressive Conditionally Heteroscedastic (GARCH) is a useful model for addressing time series with nonconstant variance or volatility. GARCH is used for model ing stock market activity and price fluctuations.

• Kalman filtering is useful for analyzing real-time inputs about a system that can exist in certa in states. Typica lly, there is an underlying model of how the various components of the system interact and affect each other. A Kalman filter processes the various inputs, attempts to identify the errors in the input, and predicts the current state. For example, a Kalman filter in a vehicle navigation system can process various inputs, such as speed and direction, and update the estimate of the current location.

• Multivariate time series analysis examines multiple time series and their effect on each other. Vector ARIMA (VARIMA) extends ARIMA by considering a vector of several time series at a particular time, t. VARIMA can be used in marketing analyses that examine the t ime series related to a com- pany's price and sa les volume as well as related time series for the competitors.

ADVANCED ANALYTICAL THEORY AND METHODS: TIME SERIES ANALYSIS

Summary This chapter presented time series analysis using A RIMA models. Time series analysis is different from other

statistical techniques in the sense that most statistical analyses assume the observations are independent of each other. Time series analysis implicitly addresses the case in which any particular observation is

somewhat dependent on prior observations. Using differencing, ARIMA models allow nonstationary series to be transformed into stationary series

to which seasonal and nonseasonal ARMA models can be appl ied. The importance of using the ACF and PACF plots to evaluate the autocorrelations was illustrated in determining ARIMA models to consider fitting.

Aka ike and Bayesian Information Criteria can be used to compare one fitted A RIMA model against another.

Once an appropriate model has been determined, future values in the time series can be forecasted.

Exercises 1. Why use autocorrelation instead of autocovariance when examining stationary t ime series?

2 . Provide an example that if the cov(X, Y) = 0, the two random variables, X andY, are not necessar- ily independent.

3. Fit an appropriate ARIMA model on the following datasets included in R. Provide supporting evi- dence on why the fitted model was selected, and forecast the time series for 12 time periods ahead.

a. faithful : Waiting times (in minutes) between Old Faithful geyser eruptions

b. JohnsonJohnson: Quarterly earnings per J&J share

c. sunspot.month: Monthly sunspot activity from 1749 to 1997

4. When should an ARIMA(p,d,q) model in which d > 0 be considered instead of an ARMA(p,q) model?

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

Text analysis, sometimes called text analytics, refers to the representation, processing, and modeling of textual data to derive useful insights. An important component of text analysis is text mining, the process of discovering relationships and interesting patterns in large text collections.

Text analysis suffers from the curse of high dimensional ity. Take the popular children's book Green Eggs and Ham [1) as an example. Author Theodor Geisel (Dr. Seuss) was challenged to write an entire book with just SO distinct words. He responded with the book Green Eggs and Ham, which contains 804 total words,

only SO of them distinct. These SO words are:

a, am, and, anywhere, are, be, boat, box, car, cou ld, dark, do, eat, eggs, fox, goat, good, green, ham, here, house, I, if, in, let, like, may, me, mouse, not, on, or, rain, Sam, say, see, so, thank, that, the, them, there, they, train, tree, try, will, with, would, you

There's a substantial amount of repetition in the book. Yet, as repetitive as the book is, modeling it as a vector of counts, or features, for each distinct word still results in a SO-dimension problem.

Green Eggs and Ham is a simple book. Text analysis often deals with textual data that is far more com-

plex. A corpus (plural: corpora) is a large collection of texts used for various purposes in Natural Language Processing (NLP). Table 9-1 lists a few example corpora that are commonly used in NLP research.

TABLE 9-1 Example Corpora in Natural Language Processing

Corpus Word Count Domain Website

Shakespeare 0.88million Written http : // shakespeare.mit.edu/

Brown Corpus 1 million Written http://icame.uib.no/brown/bcm.html

Penn Treebank 1 million Newswire http : //www.cis .upenn . edu/ -treebank/

Switchboard Phone 3million Spoken http://catalog.ldc.upenn.edu/ LDC97S62 Conversations

British National 100million Written and http: //www.natcorp.ox.ac. Corpus spoken uk/

NA News Corpus 350million Newswire http://catalog.ldc.upenn.edu/LDC95T21

European Parliament 600 million Legal http: //www . statmt.org/ Proceedings Parallel europarl / Corpus

Google N-Grams 1 trillion Written http://catalog.ldc.upenn.edu/ Corpus LDC2006T13

The smallest corpus in the list, the complete works of Shakespeare, contains about 0.88 million words. In contrast, the Google n-gram corpus contains one trill ion words from publicly accessible web pages. Out of the one trillion words in the Google n-gram corpus, there might be one million distinct words, which

would correspond to one million dimensions. The high dimensionality of text is an important issue, and it has a direct impact on the complexities of many text analysis tasks.

9.1 Text Analysis Steps

Another major challenge with text analysis is that most of the time the text is not structured. As intro-

duced in Chapter 1, "Introduction to Big Data Analytics," this may include quasi-structured, semi-structured,

or unstructured data. Table 9-2 shows some example data sources and data formats that text analysis may

have to deal with. Note that this is not meant as an exhaustive list; rather, it highlights the challenge of

text analysis.

TABLE 9-2 Example Data Sources and Formats for Text Analysis

Data Source Data Format Data Structure Type

News articles TXT, HTML, or Scanned PDF Unstructured

Literature TXT, DOC, HTML, or PDF Unstructured

E-mail TXT, MSG, or EML Unstructured

Web pages HTML Semi-structured

Server logs LOG or TXT Semi-structured or Quasi-structured

Social network API firehoses XML, JSON, or RSS Semi-structured

Call center transcripts TXT Unstructured

9.1 Text Analysis Steps A text analysis problem usual ly consists of three important steps: parsing, search and retrieval, and text

mining. Note that a text analysis problem may also consist of other subtasks (such as discourse and seg-

mentation) that are outside the scope of this book.

Parsing is the process that takes unstructured text and imposes a structure for further analysis. The

unstructured text could be a plain text file, a weblog, an Extensible Markup Language (XML) fi le, a HyperText

Markup Language (HTML) fi le, or a Word document. Parsing deconstructs the provided text and renders

it in a more structured way for the subsequent steps.

Search and retrieval is the identification of the documents in a corpus that contain search items such

as specific words, phrases, topics, or entities like people or organizations. These search items are genera lly

called key terms. Search and retrieval originated from the field of library science and is now used exten-

sively by web search engines. Text mining uses the terms and indexes produced by the prior two steps to discover meaningful insights

pertaining to domains or problems of interest. With the proper representation of the text, many of the

techniques mentioned in the previous chapters, such as clustering and classification, can be adapted to text

mining. For example, the k-means from Chapter 4, "Advanced Analytical Theory and Methods: Clustering,"

can be modified to cluster text documents into groups, where each group represents a collect ion of docu-

ments with a similar topic [2]. The distance of a document to a centroid represents how closely the document

talks about that topic. Classification tasks such as sentiment analysis and spam filtering are prominent use

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

cases for the na'ive Bayes classifier (Chapter 7, "Advanced Analytical Theory and Methods: Classification"). Text mining may utilize methods and techniques from various fields of study, such as statistical analysis, information retrieval, data mining, and natural language processing.

Note that, in reality, all three steps do not have to be present in a text analysis project. If the goal is to

construct a corpus or provide a catalog service, for example, the focus would be the parsing task using one or more text preprocessing techniques, such as part-of-speech (POS) tagging, named entity recognition, lemmatization, or stemming. Furthermore, the three tasks do not have to be sequential. Sometimes their

orders might even look like a tree. For example, one cou ld use parsing to build a data store and choose to either search and retrieve the related documents or use text mining on the enti re data store to gain insights.

Part-of-Speech (POS) Tagging, Lemmatization, and Stemming

The goal of POS tagging is to build a model whose input is a sentence, such as:

he saw a fox

and whose output is a tag sequence. Each tag marks the POS for the corresponding word, such as:

PRPVBD DT NN

accord ing to the Penn Treebank POS tags [3]. Therefore, the four words are mapped to pronoun (personal), verb (past tense). determiner, and noun (singular), respectively.

Both lemmatization and stemming are techniques to reduce the number of dimensions and reduce inflections or variant forms to the base form to more accurately measure the number of times each word appears.

With the use of a given dictionary, lemmatization finds the correct dictionary base form of a word. For example, given the sentence:

obesity causes many problems

the output of lemmatization would be:

obesity cause many problem

Different from lemmatization, stemming does not need a dictionary, and it usually refers to a crude process of stripping affixes based on a set of heuristics with the hope of correctly achieving the goal to reduce inflections or variant forms. After the process, words are stripped to become stems. A stem is not necessarily an actual word defined in the natural language, but it is sufficient to dif- ferentiate itself from the stems of other words. A well-known rule-based stemming algorithm is Porter's stemming algorithm. It defines a set of production ru les to iteratively transform words into their stems. For the sentence shown previously:

obesity causes many problems

the output of Porter's stemming algorithm is:

obes caus mani problem

9.2 A Text Analysis Example

9.2 A Text Analysis Example To further describe the three text analysis steps, consider the fictitious company ACME, maker of two products: bPhone and bEbook. ACME is in strong competition with other companies that manufacture

and sell similar products. To succeed, ACME needs to produce excellent phones and eBook readers and increase sales.

One of the ways the company does this is to monitor what is being said about ACME products in social

media. In other words, what is the buzz on its products? ACME wants to search all that is said about ACME products in social media sites, such as Twitter and Facebook, and popular review sites, such as Amazon

and ConsumerReports. It wants to answer questions such as these.

• Are people mentioning its products?

• What is being said? Are the products seen as good or bad? If people think an ACME product is bad, why? For example, are they complaining about the battery life of the bPhone, or the response time in their bEbook?

ACME can monitor the social media buzz using a simple process based on the three steps outlined in

Section 9.1. This process is illustrated in Figure 9-1, and it includes the modules in the nex t list.

2. Represent Text 6. Gain Insights

FIGURE 9-1 ACME's Text Analysis Process

1. Collect raw text (Section 9.3). This corresponds to Phase 1 and Phase 2 of the Data Analytic Lifecycle. In this step, the Data Science team at ACME monitors websites for references to specific products. The websites may include social media and review sites. The team could interact with social network application programming interfaces (APis) process data feeds, or scrape pages and use product names as keywords to get the raw data. Regular expressions are commonly used in this case to identify text that matches certain patterns. Additional filters can be appl ied to the raw data for a more focused study. For example, only retrieving the reviews originating in New York instead of the entire United States would allow ACME to conduct regional studies on its products. Generally, it is a good practice to apply filters during the data collection phase. They can reduce 1/0 workloads and minimize the storage requirements.

2. Represent text (Section 9.4). Convert each review into a suitable document representation with proper indices, and build a corpus based on these indexed reviews. This step corresponds to Phases 2 and 3 of the Data Analytic Lifecycle.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

3. Compute the usefulness of each word in the reviews using methods such as TFIDF (Section 9.5). This and the following two steps correspond to Phases 3 through 5 of the Data Analytic Lifecycle.

4. Categorize documents by topics (Section 9.6). This can be achieved through topic models (such as latent Dirichlet allocation).

5. Determine sentiments of the reviews (Section 9.7). Identify whether the reviews are positive or negative. Many product review sites provide ratings of a product with each review. If such infor- mation is not available, techniques like sentiment analysis can be used on the textual data to infer the underlying sentiments. People can express many emotions. To keep the process simple, ACME considers sentiments as positive, neutral, or negative.

6. Review the results and gain greater insights (Section 9.8). This step corresponds to Phase 5 and 6 of the Data Analytic Lifecycle. Marketing gathers the results from the previous steps. Find out what exactly makes people love or hate a product. Use one or more visualization techniques to report the findings. Test the soundness of the conclusions and operationalize the findings if applicable.

This process organizes the topics presented in the rest of the chapter and calls out some of the difficul-

ties that are unique to text analysis.

9.3 Collecting Raw Text Recall that in the Data Analytic Lifecycle seen in Chapter 2, "Data Analytics Lifecycle," discovery is the first

phase. In it, the Data Science team investigates the problem, understands the necessary data sources, and formulates initial hypotheses. Correspondingly, for text analysis, data must be collected before anything can happen. The Data Science team starts by actively monitoring vari ous websites for user-generated

contents. The user-generated contents being collected could be related articles from news portals and blogs, comments on ACME's products from online shops or reviews sites, or social media posts that contain keywords b Phone or bEbook. Regardless of where the data comes from, it's likely that the team would

deal with semi-structured data such as HTML web pages, Really Simple Syndication (RSS) feeds, XML, or JavaScript Object Notation (JSON) files. Enough structure needs to be imposed to find the part of the raw text that the team really cares about. In the brand management example, ACME is interested in what the

reviews say about bPhon e or bEb ook and when the reviews are posted. Therefore, the team will actively collect such information.

Many websites and services offer public A Pis [4, 5) for th ird-party developers to access their data. For

example, the Twitter API [6) allows developers to choose from the Streaming API or the REST API to retrieve public Twitter posts that contain the keywords bPhone or bEbook. Developers can also read tweets in real time from a specific user or tweets posted near a specific venue. The fetched tweets are in the JSON format.

As an example, a sample tweet that contains the keyword b Phone fetched using the Twitter Streaming API version 1.1 is shown next.

:4

06

07

08

09 },

-157.81538521787621,

21.3002578885766

10 "favorite_count": 0,

11 "id": 36810148827682401J.

12 "id_str": "36810148827632401--i",

13 "lang": "en'',

14

15

16

17

18

19

20

"metadata": {

"iso_language_code": "en",

"result_type": "recent"

}, "retweet count": 0,

"retto.'eeted": false,

"source": "<a href=\."http://•.•rJ!Vl.t•t:ittel·.com\"

9.3 Collecting Raw Text

21

22

23

rel=\"nofollow\">Twitter for bPhone</a>",

"text": "I once had a gf back in the day. Then the bPhone

came out lol", 24

25

26 27

28

29

30

31 32

33

34

35

36 37

38

39 40

-!1

42

43

45

"truncated": false,

"user": {

"contributors enabled": false,

"created at": ,.i·ion Jun 24 09:15:54 ~oooo 2013",

"default_profile": false,

"default_profile_image": false,

"description": "Love Life and Live Good",

"favourites count": 23, "follow_request_sent": false,

"followers_count": 96,

"following": false,

"friends count": 347,

"geo enabled": false,

"id": 2542887414,

"id str": "2542887414",

"is_translator": false, 11 lang": "e:1-gb",

"listed_count": 0, "location": "Beautiful Ha\·:aii", "name": "The Original DJ Ice",

"notifications": false, "profile_background_color": "CO;)EED",

46 "profile_background_image_url": 47 "http://aO.twimg.com/profile_bg_imgs/378BOOOOO/b12e56725ee.jpeg",

48 "profile_background_tile": true,

49 "profile_image_url": 50 "http://aO.twimg.com/profile_imgs/378800010/2d55a4388bcffd5.jpeg",

51

52

"profile_link_color": "008484",

"profile_sidebar_bcrder_color": "FFFFFF",

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

53

54

55

56

57

58

59

60

61

62

63

64

"profile sidebar fill colo!.-": "DDEEFE",

"profile_tezt_color": "333333",

"prof::._ le _use_ bac~:ground _image": true, 11 protec~ed": false,

"screen_nameu: "DJ~Ice",

"statuses_ccunt": 186,

"time zone": "Ha•t\faii",

"url": null,

"utc_offset": -36000,

"verified": false

Fields ere at ed _at at line 2 and text at line 22 in the previous tweet provide the information that interests ACME. The created_ at entry stores the timestamp that the tweet was published, and the text field stores the main content of the Twitter post. Other fields could be useful, too. For example, utilizing fields such as coordinates (line 3 to 9), user's local language (1 ang, line 40), user's 1 oca t ion (line 42), time_zone (line 59), and utc_ offset (line 61) allows the analysis to focus on tweets from a specific region. Therefore, the team can research what people say about ACME's products at a more granular level.

Many news portals and blogs provide data feeds that are in an open standard format, such as RSS or XML. As an example, an RSS feed for a phone review blog is shown next.

01 <channel>

02 <title>hll about Phones< title>

03 <description>My Phone Review Site</description>

04 <link>http:; /wwwophonesocom/linkohtm< link>

05

06 <item>

07 <title>bPhone: The best!</title>

08 <description>! love LOVE my bPhone!</description>

09 < l ink>ht tp: I /www 0 phones 0 com/link 0 htm< /link> 10 <guid isPermaLink="false">1102345</guid>

11 <pubDate>Tue, 29 Aug 2011 09:00:00 -0400</pubDate>

12 <item>

13 </channel>

The content from the t i t1 e (line 7), the description (line 8), and the published date (pubDa t e, line 11) is what ACME is interested in.

If the plan is to collect user comments on ACME's products from online shops and review sites where APis or data feeds are not provided, the team may have to write web scrapers to parse web pages and automatically extract the interesting data from those HTML files. A web scraper is a software program (bot) that systematically browses the World Wide Web, downloads web pages, extracts useful information, and stores it somewhere for further study.

Unfortunately, it is nearly impossible to write a one-size-fits-all web scraper. This is because websites like online shops and review sites have different structures. It is common to customize a web scraper for a specific website. In addition, the website formats can change over time, which requires the web scraper to

9.3 Collecting Raw Text

be updated every now and then. To build a web scraper for a specific website, one must study the HTML source code of its web pages to find patterns before extracting any useful content. For example, the team may find out that each user comment in the HTML is enclosed by a DIV element inside another DIV with the ID usrcommt, or it might be enclosed by a DIVelement with the CLASS commtcls.

The team can then construct the web scraper based on the identified patterns. The scraper can use the cur 1 tool [7] to fetch HTML source code given specific URLs, use XPath [8] and regular expressions to select and extract the data that match the patterns, and write them into a data store.

Regular expressions can find words and strings that match particular patterns in the text effectively and efficiently. Table 9-3 shows some regular expressions. The general idea is that once text from the fields of interest is obtained, regular expressions can help identify if the text is really interesting for the project. In this case, do those fields mention bPhone, bEbook, or ACME? When matching the text, regular expres- sions can also take into account capitalizations, common misspellings, common abbreviations, and special formats for e-mail addresses, dates, and telephone numbers.

TABLE 9-3 Example Regular Expressions

Regular Expression Matches Note

b(Pip)hone bPhone, bphone Pipe "r means "or" bEbo*k bEbk, bEbok, bEbook, bEboook, "*"matches zero or more occur-

bEbooook, bEboooook, ••• rences of the preceding letter

bEbo+k bEbok, bEbook, bEboook, "+"matches one or more occur- bEbooook, bEboooook, ••• rences of the preceding letter

bEbo{2,4}k bEboo~bEbooo~bEbooook "{2,4}" matches from two to four repetitions of the preceding letter "o"

""I love Text starting with "I love" "A" matches the start of a string

ACME$ Text ending with "ACME" "$" matches the end of a string

This section has discussed three different sources where raw data may come from: tweets that contain keywords bPhone or bEbook, related articles from news portals and blogs, and comments on ACME's products from online shops or reviews sites.

If one chooses not to build a data collector from scratch, many companies such as GNIP [9] and DataSift [10] can provide data collection or data reselling services.

Depending on how the fetched raw data will be used, the Data Science team needs to be careful not to violate the rights of the owner of the information and user agreements about use of websites during the data collection. Many websites place a file called robots. txt in the root directory-that is, http: I I . .. /robots. txt (for example, http: I /www. amazon. com/robots. txt).lt lists the directories and files that are allowed or disallowed to be visited so that web scrapers or web crawlers know how to treat the website correctly.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

9.4 Representing Text After the previous step, the team now has some raw text to start with.ln this data representation step, raw text is first transformed with text normalization techniques such as tokenization and case folding. Then it

is represented in a more structured way for analysis. Tokenization is the task of separating (also called tokenizing) words from the body of text. Raw text is

converted into collections of tokens after the tokenization, where each token is generally a word. A common approach is tokenizing on spaces. For example, with the tweet shown previously:

tokenization based on spaces would output a list of tokens.

1 e_~ , IJ 1, 1, I

Note that token "day . " contains a period. This is the result of only using space as the separator. Therefore, tokens "day." and "day" would be considered different terms in the downstream analysis unless an additional lookup table is provided. One way to fix the problem without the use of a lookup table is to remove the period if it appears at the end of a sentence. Another way is to tokenize the text based on

punctuation marks and spaces. In th is case, the previous tweet would become:

However, tokenizing based on punctuation marks might not be well suited to certain scenarios. For example, if the text contains contractions such as we 1 11, tokenizing based on punctuation will split them into separated words we and 11. For words such as can 1 t , the output would be can and t . It would be more preferable either not to tokenize them or to tokenize we 1 11 into we and 1 11, and can 1 t into can and 1 t . The 1 t token is more recognizable as negative than the t token. If the team is dealing with certain tasks such as information extraction or sentiment analysis, tokenizing solely based on punctuation

marks and spaces may obscure or even distort meanings in the text. Tokenizat ion is a much more difficult task than one may expect. For example, should words like

state-of- the -art, Wi- Fi, and San Francisco be considered one token or more? Should words like Resume, resume, and resume all map to the same token? Tokenization is even more difficult beyond English. In German, for example, there are many unsegmented compound nouns. In Chinese, there are no spaces between words. Japanese has several alphabets intermingled. This list can go on.

It's safe to say that there is no single tokenizer that wi ll work in every scenario. The team needs to decide what counts as a token depending on the domain of the task and select an appropriate tokenization tech- nique that fits most situations well. In reality, it's common to pair a standard tokenization technique with

a lookup table to address the contractions and terms that should not be tokenized. Sometimes it may not be a bad idea to develop one's own tokenization from scratch.

Another text normalization technique is ca lled case folding, which reduces all letters to lowercase (or the opposite if applicable). For the previous tweet, after case folding the text would become this:

)Jl I ! ,j , l. ll . .. ... ::. ,...

9.4 Representing Text

One needs to be cautious applying case folding to tasks such as information extraction, sentiment analysis, and machine translation. If implemented incorrectly, case folding may reduce or change the mean- ing of the text and create additional noise. For example, when General Motors becomes general and motors, the downstream analysis may very likely consider them as separated words rather than the name of a company. When the abbreviation of the World Health Organization WHO or the rock band The Who become who, they may both be interpreted as the pronoun who.

If case folding must be present, one way to reduce such problems is to create a lookup table of words not to be case folded. Alternatively, the team can come up with some heuristics or rules-based strategies for the case folding. For example, the program can be taught to ignore words that have uppercase in the middle of a sentence.

After normalizing the text by tokenization and case folding, it needs to be represented in a more struc- tured way. A simple yet widely used approach to represent text is called bag-of-words. Given a document, bag-of-words represents the document as a set of terms, ignoring information such as order, context, inferences, and discourse. Each word is considered a term or token (which is often the smallest unit for the analysis). In many cases, bag-of-words additionally assumes every term in the document is independent. The document then becomes a vector with one dimension for every distinct term in the space, and the terms are unordered. The permutation 0* of a document D contains the same words exactly the same number of times but in a different order. Therefore, using the bag-of-words representation, document D and its permutation D* would share the same representation.

Bag-of-words takes quite a na..-ve approach, as order plays an important role in the semantics of text. With bag-of-words, many texts with different meanings are combined into one form. For example, the texts "a dog bites a man" and "a man bites a dog" have very different meanings, but they would share the same representation with bag-of-words.

Although the bag-of-words technique oversimplifies the problem, it is still considered a good approach to start with, and it is widely used for text analysis. A paper by Salton and Buckley [11] states the effective- ness of using single words as identifiers as opposed to multiple-term identifiers, which retain the order of the words:

In reviewing the extensive literature accumulated during the past 25 years in the area of retrieval system evaluation, the overwhelming evidence is that the judicious use of single-term identifiers is preferable to the incorporation of more complex entities extracted from the texts themselves or obtained from available vocabulary schedules.

Although the work by Salton and Buckley was published in 1988, there has been little, if any, substantial evidence to discredit the claim. Bag-of-words uses single-term identifiers, which are usually sufficient for the text analysis in place of multiple-term identifiers.

Using single words as identifiers with the bag-of-words representation, the term frequency (TF) of each word can be calculated. Term frequency represents the weight of each term in a document, and it is proportional to the number of occurrences of the term in that document. Figure 9-2 shows the 50 most frequent words and the numbers of occurrences from Shakespeare's Hamlet. The word frequency distribu- tion roughly follows Zipf's Law [12, 13]-that is, the i-th most common word occurs approximately 1 I i as

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

often as the most frequent term. In other words, the frequency of a word is inversely proportional to its rank in the frequency table. Term frequency is revisited later in this chapter.

800

600

200

FIGURE 9-2 The 50 most frequent words in Shakespeare's Hamlet

What's Beyond Bag-of-Words?

Bag-of-words is a common technique to start with. But sometimes the Data Science team prefers other methods of text representation that are more sophisticated. These more advanced methods consider factors such as word order, context, inferences, and discourse. For example, one such method can keep track of the word order of every document and compare the normalized dif- ferences of the word orders [14]. These advanced techniques are outside the scope of this book.

Besides extracting the terms, their morphological features may need to be included. The morpho- logical features specify additional information about the terms, which may include root words, affixes, part-of-speech tags, named entities, or intonation (variations of spoken pitch). The features from this step contribute to the downstream analysis in classification or sentiment analysis.

The set of features that need to be extracted and stored highly depends on the specific task to be per-

formed.lf the task is to label and distinguish the part of speech, for example, the features will include all the words in the text and their corresponding part-of-speech tags. If the task is to annotate the named entities

9.4 Representing Text

like names and organizations, the features highlight such information appearing in the text. Constructing

the featu res is no trivial task; quite often this is done entire ly manual ly, and sometimes it requ ires domain expertise.

Sometimes creating features is a text analysis task all to itself. One such example is topic modeling.

Topic modeling provides a way to quickly analyze large volumes of raw text and identify the latent topics.

Topic modeling may not require the documents to be labeled or annotated. It can discover topics directly

from an analysis of the raw text. A topic consists of a cluster of words that frequently occur together and

that share the same theme. Probabilistic topic modeling, discussed in greater detail later in Section 9.6, is

a suite of algorithms that aim to parse large archives of documents and discover and annotate the topics.

It is important not only to create a representation of a document but also to create a representation

of a corpus. As introduced earlier in the chapter, a corpus is a collection of documents. A corpus could be

so large that it includes all the documents in one or more languages, or it could be smaller or limited to a

specific domain, such as technology, medicine, or law. For a web search engine, the entire World Wide Web

is the relevant corpus. Most corpora are much smaller. The Brown Corpus [15] was the first mi llion-word

electronic corpus of English, created in 1961 at Brown University. It includes text from around 500 sources,

and the source has been categorized into 15 genres, such as news, editorial, fiction, and so on. Table 9-4

lists the genres of the Brown Corpus as an example of how to organize information in a corpus.

TABLE 9-4 Categories of the Brown Corpus

Category Number of Sources Example Source

A. Reportage 44 Chicago Tribune

B. Editoria l 27 Christ ian Science Monitor

C. Reviews 17 Life

D. Religion 17 William Pollard: Physicist and Christian

E. Skills and Hobbies 36 Joseph E. Choate: The American Boating Scene

F. Popular Lore 48 David Boroff: Jewish Teen-Age Culture

G. Belles Lettres, Biography, 75 Selma J. Cohen: Avant-Garde Memoirs, and so on Choreography

H. Miscellaneous 30 U.S. Dep't of Defense: Medicine in National Defense

J. Learned 80 J. F. Vedder: Micrometeorites

K. General Fiction 29 David Stacton: The Judges of the Secret Court

(continues)

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

TABLE 9-4 Categories of the Brown Corpus (Continued)

Category Number of Sources Example Source

L. Mystery and Detective 24 5. L. M. Barlow: Monologue of Fiction Murder

M. Science Fiction 6 Jim Harmon: The Planet with No Nightmare

N. Adventure and Western 29 Paul Brock: Toughest Lawman in Fiction the Old West

P. Romance and Love Story 29 Morley Callaghan: A Passion in Rome

R.Humor 9 Evan Esar: Humorous English

Many corpora focus on specific domains. For example, the BioCreative corpora [16) are from biology,

the Switchboard corpus [17) contains telephone conversations, and the European Parliament Proceedings

Parallel Corpus [18) was extracted from the proceedings of the European Parliament in 21 European

languages. Most corpora come with metadata, such as the size of the corpus and the domains from which the

text is extracted. Some corpora (such as the Brown Corpus) include the information content of every word

appearing in the text. Information content (IC) is a metric to denote the importance of a term in a corpus.

The conventional way [19) of measuring the IC of a term is to combine the knowledge of its hierarchical

structure from an ontology with statistics on its actual usage in text derived from a corpus. Terms with

higher IC values are cons idered more important than terms with lower IC values. For example, the word

necklace generally has a higher IC va lue than the word jewelry in an English corpus because jewelry is

more general and is likely to appear more often than necklace. Research shows that IC can help measure

the semantic similarity of terms [20). In addition, such measures do not require an annotated corpus, and

they generally achieve strong correlations with human judgment [21, 20).

In the brand management example, the team has collected the ACME product reviews and turned them

into the proper representation with the techniques discussed earlier. Next, the reviews and the representa- tion need to be stored in a searchable archive for future reference and research. Th is archive cou ld be a SQL

database, XML or JSON fi les, or plain text fi les from one or more directories.

Corpus statistics such as IC can help identify the importance of a term from the documents being ana-

lyzed. However, IC values included in the metadata of a traditional corpus (such as Brown corpus) sitting

externally as a knowledge base cannot satisfy the need to analyze the dynamically changed, unstructured

data from the web. The problem is twofold. First, both traditional corpora and IC metadata do not change

over time. Any term not existing in the corpus text and any newly invented words would automatically

receive a zero IC value. Second, the corpus represents the entire knowledge base for the algorithm being

used in the downstream analysis. The nature of the unstructu red text determines that the data being

analyzed can contain any topics, many of which may be absent in the given knowledge base. For example,

if the task is to research people's attitudes on musicians, a traditional corpus constructed SO years ago

would not know that the term U2 is a band; therefore, it would receive a zero on IC, which means it's not an

9.5 Term Frequency-Inverse Document Frequency (TFIDF)

important term. A better approach would go through all the fetched documents and find out that most of

them are related to music, with U2 appearing too often to be an unimportant term. Therefore, it is neces- sary to come up with a metric that can easily adapt to the context and nature of the text instead of relying on a traditional corpus. The next section discusses such a metric. It's known as Term Frequency-Inverse

Document Frequency (TFIOF). which is based entirely on all the fetched documents and which keeps track of the importance of terms occurring in each of the documents.

Note that the fetched documents may change constantly over time. Consider the case of a web search engine, in which each fetched document corresponds to a matching web page in a search result. The

documents are added, modified, or removed and, as a result, the metrics and indices must be updated correspondingly. Additional ly, word distributions can change over time, which reduces the effectiveness of class ifiers and filters (such as spam filters) unless they are retrained.

9.5 Term Frequency-Inverse Document Frequency (TFIDF) This section presents TFIOF, a measure widely used in information retrieval and text analysis. Instead of using a traditional corpus as a knowledge base, TFIDF directly works on top of the fetched documents and treats these documents as the "corpus." TFIDF is robust and efficient on dynamic content, because docu- ment changes require only the update of frequency counts.

Given a term t and a document d = {t1, t2,tl' . . . t " } containi ng n terms, the si mplest form of term frequency oft in d can be defined as the number of times t appears in d, as shown in Equation 9-1.

n

T~ (t ,d) = L f(t, t;) j --'"1

where

{

1 if t = t' f(t t ' ) = '

' 0, otherwise

(9-1)

To understand how the term frequency is computed, consider a bag-of-words vector space of 10 words: i, l ove, acme, my, b eb ook, bphone, f an t astic, slotv, terr ible, and terrifi c . Given the text I love LOVE my b Phon e extracted from the RSS feed in Section 9.3, Table 9-5 shows its cor- responding term frequency vector after case folding and tokenization.

TABLE 9-5 A Sample Term Frequency Vector

Term Frequency

love 2

acme 0

(continues)

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

TABLE 9 ·5 A Sample Term Frequency Vector (Continued)

Term Frequency

my

be book 0

bphone

fantastic 0

slow 0

terrible 0

terrific 0

The term frequency function can be logarithmically sca led. Recall that in Figure 3-1 1 and Figure 3-12 of Chapter 3, "Review of Basic Data Analytic Methods Using R," it shows the logari thm can be applied to

distribution with a long tail to enable more data detail. Similarly, the logarithm can be appl ied to word frequencies whose distribution also contains a long tail, as shown in Equation 9-2.

TF2 (t ,d) = log [T~ (t,d)+ 1) (9-2)

Because longer documents contain more terms, they tend to have higher term frequency values. They also tend to contain more distinct terms. These factors can conspi re to raise the term frequency va lues of longer documents and lead to undesirable bias favoring longer documents. To address this problem,

the term frequency can be normalized. For example, the term frequency of term t in document d can be normalized based on the number of terms in d as shown in Equation 9-3.

( ) T~ (t,d)

TF1 t ,d =--n (9-3)

Besides the three common definitions mentioned earl ier, there are other less common variations [22) of term frequency. In practice, one needs to choose the term frequency definition that is the most suitable to the data and the problem to be solved.

A term frequency vector (shown in Table 9-5) can become very high dimensional because the bag-of- words vector space can grow substantially to include all the words in Engl ish. The high dimensionality makes it difficult to store and parse the text and contribute to performance issues related to text analysis.

For the purpose of reducing dimensionality, not all the words from a given language need to be included

in the term frequency vector. In English, for example, it is common to remove words such as the, a, of, and, to, and other articles that are not likely to contribute to semantic understanding. These common words are ca lled stop words. Lists of stop words are avai lable in various languages for automating the identification of stop words. Among them is the Snowball's stop words list [23) that contains stop words in more than ten languages.

9.5 Term Frequency-Inverse Document Frequency (TFIDF)

Another simple yet effective way to reduce dimensionality is to store a term and its frequency on ly

if the term appears at least once in a document. Any term not existing in the term frequency vector by

default wil l have a frequency of 0. Therefore, the previous term frequency vector would be simplified to

what is shown in Tab le 9-6.

TABLE 9-6 A Simpler Form of the Term Frequency Vector

Term Frequency

love 2

my

bphone

Some NLP techniques such as lemmatization and stemming can also reduce high dimensionality.

Lemmatization and stemming are two different techniques that combine various forms of a word. With

these techniques, words such as play, plays, played, and play ing can be mapped to the same term.

It has been shown that the term frequency is based on the raw count of a term occurring in a stand-

alone document. Term frequency by itself suffers a critical problem: It regards that stand-alone document

as the enti re world. The importance of a term is solely based on its presence in this particular document.

Stop words such as the, and, and a could be inappropriately considered the most important because

they have the highest frequencies in every document. For example, the top three most frequent words in

Shakespeare's Hamlet are all stop words {t he, and, and of, as show n in Figure 9-2). Besides stop words,

words that are more general in meaning tend to appear more often, thus having higher term frequencies.

In an art icle about consumer telecommunications, the word phone would be likely to receive a high term

frequency. As a resu lt, the important keywords such as b Phone and bEbook and their related words could

appear to be less important. Consider a search engine that responds to a search query and fetches relevant

documents. Using term frequency alone, the search engine wou ld not properly assess how relevant each

document is in relation to the search query.

A quick fix for the prob lem is to introduce an additional variable that has a broader view of the world-

considering t he importance of a term not only in a single document but in a collection of documents, or

in a corpus. The additional variable should reduce the effect of the term frequency as the term appears in

more documents.

Indeed, that is the intention of the inverted document frequency {IDF). The IDF inversely corresponds

to t he document frequency {OF), wh ich is defined to be the number of documents in the corpus that

contai n a term. Let a corpus D contain N documents. The document frequency of a term t in corpus D = [d1,d2 , •• • d11 } is defined as shown in Equation 9-4.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

N

DF(t)= l:f'(t,d) d;ED;IDI=N i=l

where

f'(t,d') = {~. if tEd' (9-4) otherwise The Inverse document frequency of a term t is obtained by dividing N by the document frequency of

the term and then taking the logarithm of that quotient, as shown in Equation 9-5.

N IDF, ( t) =log DF(t) (9-5)

If the term is not in the corpus, it leads to a division-by-zero. A quick fix is to add 1 to the denominator, as demonstrated in Equation 9-6.

N /D~(t)=log ( )

DF t +1 (9-6)

The precise base of the logarithm is not material to the ranking of a term. Mathematically, the base constitutes a constant multiplicative factor towards the overall result.

Figure 9-3 shows 50 words with (a) the highest corpus-wide term frequencies (TF), (b) the highest docu- ment frequencies (OF), and (c) the highest Inverse document frequencies (IDF) from the news category of the Brown Corpus. Stop words tend to have higher TF and DF because they are likely to appear more often in most documents.

Words with higher IDF tend to be more meaningful over the entire corpus. In other words, the IDF of a rare term would be high, and the IDF of a frequent term would be low. For example, if a corpus contains 1,000 documents, 1,000 of them might contain the word the, and 10 of them might contain the word bPhone. With Equation 9-5, the IDF of the would be 0, and the IDF of bPhone would be log100, which is greater than the IDF of the. If a corpus consists of mostly phone reviews, the word phone would prob- ably have high TF and DF but low IDF.

Despite the fact that IDF encourages words that are more meaningful, it comes with a caveat. Because the total document count of a corpus (N) remains a constant, IDF solely depends on the DF. All words having the same DF value therefore receive the same IDF value.IDF scores words higher that occur less frequently across the documents. Those words that score the lowest DF receive the same highest IDF.In Figure 9-3 (c), for example, sunbonnet and narcotic appeared in an equal number of documents in the Brown corpus; therefore, they received the same IDF values. In many cases, it is useful to distinguish between two words that appear in an equal number of documents. Methods to further weight words should be considered to refine the IDF score.

The TFIDF (or TF-IDF) is a measure that considers both the prevalence of a term within a document (TF) and the scarcity of the term over the entire corpus (IDF). The TFIDF of a term t in a document dis defined as the term frequency of t in d multiplying the document frequency of t in the corpus as shown in Equation 9-7:

TFIDF(t,d) = TF(t,d}x/DF(t) (9-7)

"T1

" c :» m 10 w ~ ~ ==<' 0 3 OJ a ~ 8 -a c "' v,' ;)

~ 8 .§ ~ :§. s- ~ s- 0 11) a. ;)-

-a· ::>-

~ 8 -a s; :;1 0 .:->"!

~ C3 ..,.,

IOF wwwwwwwww~

u,a,a,:....:....ex,ex,<o<oo sunbonnetVl 0 Vl 0 Vl 0 Vl 0 Vl 0

narcotic rai ling

aggression marching

pardon electricity consulate

homemakers sinking

preceeded leisurely

fur wooden

clientele specialties succession

debuting pulse

ruth less ~ boogie

reporter affiliated

confronts doldrums

cyclica l menu

diplomat divide owed

beneficiaries opponents

tardiness explorers

occupying symphony

passport unfortunately

heralded females

brings whirling

menaced smelts midst

locked famed

accomplishment locker

temperatures ~-~...~--'-J........L.....L.....J_J

~ a. "' ::<: ;::;: :::T

I .o· :::T ro ~

0 ..,

ie has for

with an as at to be by

the was that

a is in

have and

on of

from out

which who one not but

been his will

other this

they he

were no all

are than new

more its up

over their

had also two

about would

,..... 0

OF "' w 0 0 ""' 0 lJl 0

~

~ a. Vl

::<: ;::;: :::T

I .o· :::T ro ~ 0 ..,

t he 0

of and

to a

in for

that is

was on he at

with be as by it

his said w ill

from are th is

an has but had

who they have

not were

wou ld which

new their

one been there more

al l i

i ts last

or two

when up

other

Corpus TF .....,NW~ lJ10'\ '-' 0000000 0000000 0000000

I I I I :z:::::aa;za

Q)

~ a. Vl

::<: ;::;: :::T

I .o· :::T ro ~ n 0 -a c Vl

--{ ..,

;;; 3 ~ ~ --t :;::· vr :!:! ro - · 0 a. ::::> , -· ...... V"' ~::;'"' ro ro o ;;; '"'o ;;; ::::> ~ "' - "0 ::<: --i c 0 , "' ~ - . a. Oz"' , 0 ::; V'l ...... -· '"' ro <O 0 ~ ::; m ~ ~ 3· ~ 5- a.~~ - · 0 ~ , {; ~ "' "0 ro "0 ro ::> "0 "' ~ ~ ~3 0 "' '"' - 0 c 0 ~

3 "' ~ f1) - ~ ::> ro - vr 3 ~ cr s· s· Q ~ ~ c "0 0 "' f1) '"' f1) '"' c - ::;; 3 ::; '"' 11) ro a. ::> --i 0 ~ , '"' 0" < c c ~ 3 ~ c ro o ro ::> '"' "' -'"' ' c 3 "' ~ "' 0 -'< ...... ~ c:r:T""' f1) f1) 0

"' ~ a. "' ~ ~ 3 ~ * ~ ~ ::> ro ~ ~ 3 ~

Vi' Q.l

"'a. !!.o '< '"' - c 0 '

10 v. ~ 3 ..., iil .c c: II> :s n '< I :; < !!: "' II> 0 0 n c: 3 II> ;a ~ II> .c c: II> :s n '< -=i ..., a .:!!

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

TFIDF is efficient in that the calculations are simple and straightforward, and it does not require knowl-

edge of the underlying meanings of the text. But this approach also reveals little of the inter-document or intra-document statistical structure. The next section shows how topic models can address this short-

coming ofTFIDF.

9.6 Categorizing Documents by Topics With the reviews collected and represented, the data science team at ACME wants to categorize the reviews by topics. As discussed earlier in the chapter, a topic consists of a cluster of words that frequently occur

together and share the same theme. The topics of a document are not as straightforward as they might initially appear. Consider these two

reviews:

1. The bPhoneSx has coverage everywhere. It's much less flaky than my old bPhone4G.

2 . While I love ACME's bPhone series, I've been quite disappointed by the bEbook. The text is illeg- ible, and it makes even my old NBook look blazingly fast.

Is the first review about bPhone5x or bPhone4G? Is the second review about bPhone, bEbook, or NBook? For machines, these questions can be difficult to answer.

Intuitively, if a review is talking about bPhoneSx, the term bPhoneSx and related terms (such as

phone and ACME) are likely to appear frequently. A document typically consists of multiple themes run- ning through the text in different proportions- for example, 30% on a topic related to phones, 15% on

a topic related to appearance, 10% on a topic rela ted to shipping, 5% on a topic related to ser- vice, and so on.

Document grouping can be achieved with clustering methods such ask-means clustering [24] or clas-

sification methods such as support vector machines [25]. k-nearest neighbors [26]. or na'lve Bayes [27). However, a more feasible and prevalent approach is to use topic modeling. Topic modeling provides tools to automatically organize, search, understand, and summarize from vast amounts of information.

Topic models [28, 29) are statistical models that examine words from a set of documents, determine the themes over the text, and discover how the themes are associated or change over time. The process of topic modeling can be simplified to the following.

1. Uncover the hidden topical patterns within a corpus.

2. Annotate documents according to these topics.

3. Use annotations to organize, search, and summarize texts.

A topic is formally defined as a distribution over a fixed vocabulary of words [29]. Different topics would have different distributions over the same vocabulary. A topic can be viewed as a cluster of words with related meanings, and each word has a corresponding weight inside this topic. Note that a word from the vocabulary can reside in multiple topics with different weights. Topic models do not necessarily require prior knowledge of the texts. The topics can emerge solely based on analyzing the text.

The simplest topic model is latent Dirichle t allocation (LDA) [29]. a generative probabilistic model of a corpus proposed by David M. Blei and two other researchers. In generative probabilistic modeling, data

9.6 Categorizing Documents by Topics

is treated as the resu lt of a generative process that includes hidden variables. LDA assumes that there is a

fixed vocabulary of words, and the number of the latent topics is predefined and remains constant. LDA assumes that each latent topic follows a Dirichlet distribution [30] over the vocabulary, and each document is represented as a random mixture of latent topics.

Figure 9-4 illustrates the intuitions behind LDA. The left side of the figure shows four topics built from a

corpus, where each topic contains a list of the most important words from the vocabulary. The four example topics are related to problem, policy, neural, and report. For each document, a distribution over the topics is chosen, as shown in the histogram on the right. Next, a topic assignment is picked for each word in the

document, and the word from the corresponding topic (colored discs) is chosen. In rea lity, only the docu-

ments (as shown in the middle of the figure) are avai lable. The goal of LDA is to infer the underl ying topics, topic proportions, and topic assignments for every document.

Topics Document

problem technique game play

policy

0.05 0.04 0.02 0.01

0.02

Topic Assignments

Topic Proportions

reinforcement 0.02 state 0.01 model 0.01

neural 0.06 learning 0.05 networks 0.05 system 0.04

report 0.05 technical 0.03 paper 0.02 universi ty 0.02

FIGURE 9-4 The intuitions behind LOA

The reader can refer to the original paper [29] for the mathematical detail of LDA. Basically, LDA can be viewed as a case of hierarchical Bayesian estimation with a posterior distribution to group data such as

documents with similar topics. Many programming tools provide software packages that can perform LDA over datasets. R comes with

an lda package [31] that has built-in functions and sample datasets. The lda package was developed by David M. Blei's research group [32]. Figure 9-5 shows the distributions of ten topics on nine scientific documents randomly drawn from the cora dataset of the lda package. The cora dataset is a collection of 2,410 scientific documents extracted from the Cora search engine [33].

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

0 ·a. g

reinforcement.stato.tcarnlng.optlmal.policy

dccision.multiple .exocution.parallol .lnstruction

genelic.controUitnoss problem population

reasoning.design.knowlodgo systom.case

feature.learning network teatufOS "'sua!

neurat.networks network grant research

neural.learn1ng notwofks system network

repon.bayestan.lechmcal umvcrs•ty.cha1n

learmng.conceplalgonthm examples learner

algonthm.distnbution.bayosian crror.probabJhty

reinforcement.stato.learnlng.oplimal .pollcy

decision.multiple.execution parnllot.lnstruct•on

genetic.controtfitness pro~om populat1on

reasoning.design.knowlodgo.systom.casc

feature.learning.no~ features V~Sual

neural.networks nctwof"k grant r&s.earch

neural.learntng nctwotks system network

report.bayestan lochniC.11 UOIVCfSIIY chatn

learning.concept algorithm examples learner

algonthm.distnbution.baycslan.orror probab1l1ty

reinforcement. state loarmng.ophmal policy

docision.multip!e.execution pnrallollnstruction

gcnetic.control.fitness problem population

reasoning.design knowledgo system case

reature.learmng network features VISual

neural.netwotks netwof'k grant research

neural.learmng.networks system network

report.bayes•an.techmcal .unlvcrsny cha1n

learning.concept.algonlhm.o~tamplcs. loarner

algorilhm.distribution bayesian error proba~llty

1 2 3

I • I -- I -I I 4 5 6 - -• • •

• - --7 8 9 • I

• -I • I - I 0 25 50 75 0 25 50 75 0 25 50 75 proporl ion (%)

topic

ulgor•thm.d•stnbutlon.bayeslan.error.probab•hty

learning.conccpt.algorlthm.cxamples learner

report .baycsian.tochnical.university.chain

nourallearmng.nctworks.system.network

neural networks network grant research

feature &earmng netwcrt.features VISual

reasorung de~n. k.r'IO'-N1edge system.case

genet•c.control .fitness problem.populaiJOn

doclslon.mui!Jplo.execution.parallel.instruction

• rolnforccment.stato.learning.optlmal.pollcy

FIGURE 9-5 Distributions of ten topics over nine scientific documents from the Cora dataset

The code that follows shows how to generate a graph similar to Figure 9-5 using Rand add-on packages such as lda and ggplot.

require ( "ggplot2")

require ( "reshape2" )

require ( "lda" )

!: ~oad d ~qm ·1Ls 'lnd ·rocabulary

data (cora.documents )

data (cora.vocab)

theme_ set(theme_bw () )

= :~umbt.l K <- 10

!: ~;\) .be" toe unen:s to d1sp~ y

N <- 9

result c- ld!.c~ll3psed.g1bbs.sa~pla. d cu~ents, K, ## Num clusters cora .vocab, 25, ijij Num iterations 0 . 1,

9.7 Determining Sentiments

0 . 1, compute . log . likel:hood=TRUE )

:: :iet the t r \•; ds 1;·, --ht 1~~-~l- top .words c- top . topic .words (resul t$topics, 5, by . score=TRUE)

0 .:d - >P. p != • •- : .. topic .props c- t ( res~lt$document_sums) I co1Sums(result$document_s ums)

document . samples c- sample(1 : dim(topic .props) [1], N) topic .props c- topic .props[document. samples , ]

topic .pr ops[is.na(topic .props ) J c- 1 I K

colnames (t opic .props ) c- apply( t op .words , 2 , paste, collapse=" " )

topic .props .df c- mel t (cbind(data . f r ame(topic .props ) , document=factor( 1:N)) ,

variable .name="topic", i d .vars = "document " )

qplot (topic , va lue *100 , fill= t opic , stat ="identi t y", ylab="proportion (%) ", data= t opic .props .d f , geom="histogram" ) +

t heme(axis . text. x = element_text( angle=O, hjust=1 , size=12 )) + coord_fl ip () + face t_wrap(- document , ncol =3)

Topic models can be used in document modeling, document classification, and collaborative filtering

[29). Topic models not only can be applied to textual data, they can also help annotate images. Just as a

document can be considered a collection of topics, images can be considered a collection of image features.

9.7 Determining Sentiments In addition to the TFIDF and topic models, the Data Science team may want to identify the sentiments in user

comments and reviews of the ACME products. Sentiment analysis refers to a group of tasks that use statistics and natural language processing to mine opinions to identify and extract subjective information from texts.

Early work on sentiment analysis focused on detecting the polarity of product reviews from Epinions [34)

and movie reviews from the Internet Movie Database (IMDb) [35) at the document level. Later work handles

sentiment analysis at the sentence level [36). More recently, the focus has shifted to phrase-level [37) and

short-text forms in response to the popularity of micro-blogging services such as Twitter [38, 39, 40, 41 , 42).

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

Intuitively, to conduct sentiment analysis, one can manually construct lists of words with positive senti- ments (such as br i 11 ian t, awesome, and spectacular) and negative sentiments (such as awful, stupid, and hideous). Related work has pointed out that such an approach can be expected to achieve accuracy around 60% [35], and it is likely to be outperformed by examination of corpus statistics [43].

Classification methods such as na"ive Bayes as introduced in Chapter 7, maximum entropy (MaxEnt), and support vector machines (SVM) are often used to extract corpus statistics for sentiment analysis. Related research has found out that these classifiers can score around 80% accuracy [35, 41, 42] on sentiment analysis over unstructured data. One or more of such classifiers can be applied to unstructured data, such as movie reviews or even tweets.

The movie review corpus by Pang et al. [35] includes 2,000 movie reviews collected from an IMDb archive of the rec.arts.movies.reviews newsgroup [43]. These movie reviews have been manually tagged into 1,000 positive reviews and 1,000 negative reviews.

Depending on the classifier, the data may need to be split into training and testing sets. As seen previ- ously in Chapter 7, a useful rule of the thumb for splitting data is to produce a training set much bigger than the testing set. For example, an 80/20 split would produce 80% of the data as the training set and 20% as the testing set.

Next, one or more classifiers are trained over the training set to learn the characteristics or patterns residing in the data. The sentiment tags in the testing data are hidden away from the classifiers. After the training, classifiers are tested over the testing set to infer the sentiment tags. Finally, the result is compared against the original sentiment tags to evaluate the overall performance of the classifier.

The code that follows is written in Python using the Natural Language Processing Toolkit (NLTK) library (http: I /nltk. org/).lt shows how to perform sentiment analysis using the na'ive Bayes classifier over the movie review corpus.

The code splits the 2,000 reviews into 1,600 reviews as the training set and 400 reviews as the testing set. The na'ive Bayes classifier learns from the training set. The sentiments in the testing set are hidden away from the classifier. For each review in the training set, the classifier learns how each feature impacts the outcome sentiment. Next, the classifier is given the testing set. For each review in the set, it predicts what the corresponding sentiment should be, given the features in the current review.

import nltk.classify.util from nltk.classify import NaiveBayesClassifier from nltk.corpus import movie_reviews from collections import defaultdict import numpy as np

# define an 80/20 split for train/test SPLIT= 0.8

def word_feats(words): feats ; defaultdict(lambda: False) for word in words:

feats[word] ; True return feats

posids ; movie_reviews.fileids('pos')

9.7 Determining Sentiments

negids = movie_reviews.fileids(•neg'}

posfeats

negfeats

[(word_feats(movie_reviews.words(fileids=[f)}}, 'pos'} for f in posids]

[(word_feats(movie_reviews.words(fileids=[f]}}, •neg'} for f in negids)

cutoff = int(len(posfeats} * SPLIT}

trainfeats = negfeats[:cutoff] + posfeats[:cutoff] testfeats = negfeats[cutoff:] + posfeats[cutoff:)

print 'Train on %d instances\nTest on %d instances' % (len(trainfeats}, len(testfeats))

classifier = NaiveBayesClassifier.train(trainfeats} print 'Accuracy: •, nltk.classify.util.accuracy(classifier, testfeats)

classifier.show_most_informative_features(}

# prepare confusion matrix

pos [classifier.classify(fs} for (fs,l) in posfeats[cutoff:]] pos np.array(pos} neg [classifier.classify(fs} for (fs,l) in negfeats[cutoff:)] neg np.array(neg}

print 'Confusion matrix:' print '\t'*2, 'Predicted class' print '-'*40 print 'l\t %d (TP} \tl\t %d (FN} \tl Actual class' %

(pos == 'pos•} .sum(}, (pos 'neg'} .sum(} print '-'*40 print 'l\t %d (FP} \tl\t %d (TN) \tl' %

(neg == 'pos') . sum(), (neg == 'neg'} . sum()) print '-'*40

The output that follows shows that the na"ive Bayes classifier is trained on 1,600 instances and tested on 400 instances from the movie corpus. The classifier achieves an accuracy of 73.5%. Most information features for positive reviews from the corpus include words such as outs tanding, vulnerable, and astounding; and words such as insul ting,ludicrous, and uninvol vingare the most informative features for negative reviews. At the end, the output also shows the confusion matrix corre- sponding to the classifier to further evaluate the performance.

Tra~n en 1600 ~nstances

~est Infor~ati~e Fea:~res

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

As discussed ea rlier in Chapter 7, a confusion matrix is a specific table layout that allows visualization of the performance of a model over the testing set. Every row and column corresponds to a possible class in

the dataset. Each cell in the matrix shows the number of test examples for which the actual class is the row and the predicted class is the column. Good results correspond to large numbers down the main diagonal (TP and TN) and small, ideally zero, off-diagonal elements (FP and FN). Table 9-7 shows the confusion matrix

from the previous program output for the testing set of 400 reviews. Because a well-performed classifier should have a confusion matrix with large numbers forTP and TN and ideally near zero numbers for FP and

FN, it can be concluded that the na"ive Bayes classifier has many false negatives, and it does not perform very well on th is testing set.

TABLE 9 -1 Confusion Matrix for the Example Test ing Set

Chapter 7 has introduced a few measures to evaluate the performance of a classifier beyond the confu- sion matrix. Precision and recall are two measures commonly used to evaluate tasks related to text analysis. Definitions of precision and recall are given in Equations 9-8 and 9-9.

P . . TP

reCISIOn=--- TP + FP

TP Recall =

TP + FN

(9-8)

(9-9)

9.7 Determining Sentiments

Precision is defined as the percentage of documents in the results that are relevant. If by entering keyword bPhone, the search engine returns 100 documents, and 70 of them are relevant, the precision of the search engine result is 0.7o/o.

Recall is the percentage of returned documents among all relevant documents in the corpus. If by entering keyword bPhone, the search engine returns 100 documents, only 70 of which are relevant while failing to return 10 additional, relevant documents, the recall is 70/ (70+ 10) = 0.875.

Therefore, the na'ive Bayes classifier from Table 9-7 receives a recall of 195 I (195 + 5) = 0.975 and a precision of195/{195+ 101):::::: 0.659.

Precision and recall are important concepts, whether the task is about information retrieval of a search engine or text analysis over a finite corpus. A good classifier ideally should achieve both precision and recall close to l.O.In information retrieval, a perfect precision score of 1.0 means that every result retrieved by a search was relevant (but says nothing about whether all relevant documents were retrieved), whereas a perfect recall score of 1.0 means that all relevant documents were retrieved by the search (but says nothing about how many irrelevant documents were also retrieved). Both precision and recall are therefore based on an understanding and measure of relevance. In reality, it is difficult for a classifier to achieve both high precision and high recall. For the example in Table 9-7, the na'ive Bayes classifier has a high recall but a low precision. Therefore, the Data Science team needs to check the cleanliness of the data, optimize the classifier, and find if there are ways to improve the precision while retaining the high recall.

Classifiers determine sentiments solely based on the datasets on which they are trained. The domain of the data sets and the characteristics of the features determine what the knowledge classifiers can learn. For example, lightweight is a positive feature for reviews on laptops but not necessarily for reviews on wheelbarrows or textbooks. In addition, the training and the testing sets should share similar traits for classifiers to perform well. For example, classifiers trained on movie reviews generally should not be tested on tweets or blog comments.

Note that an absolute sentiment level is not necessarily very informative. Instead, a baseline should be established and then compared against the latest observed values. For example, a ratio of 40o/o posi- tive tweets on a topic versus 60o/o negative might not be considered a sign that a product is unsuccessful if other similar successful products have a similar ratio based on the psychology of when people tweet.

The previous example demonstrates how to use na'ive Bayes to perform sentiment analysis. The example can be applied to tweets on ACME's bPhone and bEbook simply by replacing the movie review corpus with the pretagged tweets. Other classifiers can also be used in place of na'ive Bayes.

The movie review corpus contains only 2,000 reviews; therefore, it is relatively easy to manually tag each review. For sentiment analysis based on larger amounts of streaming data such as millions or billions of tweets, it is less feasible to collect and construct datasets of tweets that are big enough or manually tag each of the tweets to train and test one or more classifiers. There are two popular ways to cope with this problem. The first way to construct pretagged data, as illustrated in recent work by Go et al. [41] and Pak and Paroubek [42], is to apply supervision and use emoticons such as : ) and : ( to indicate if a tweet contains positive or negative sentiments. Words from these tweets can in turn be used as clues to classify the sentiments of future tweets. Go et al. [41] use classification methods including na'ive Bayes, MaxEnt, and SVM over the training and testing datasets to perform sentiment classifications. Their demo is available at http: I /www. sentiment140. com. Figure 9-6 shows the sentiments resulting from a query against the term "Boston weather" on a set of tweets. Viewers can mark the result as accurate or inaccurate, and such feedback can be incorporated in future training of the algorithm.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

Sentiment140 l=l Boston~a:lle1

S.nUmtnt ~n.1.1ys11 tor Bolton weatl'ltr

TWetu. about: Boston weather

• •

.alMWZl 1 really t>a:e bol!on w .. ther I gona rnoYe OU1 or there ....,.. , ~.

Aar.t.!a~BfW!IQOf @Ain)'Mane!!rlrwnef ThOfougnly <f'40)'ed Ule Be~ Bolton w .. lher on 10 I leW YOI1<0 ooT~ • bostonrock:S •nappywaman ...,.,. ., ...... I '.!TaQ!M5tOQS 1'/e nope our Leop;trdl are-~ lhlS i>OaU'- '\11 Bolton w .. lher1•sum>em!lle<Jiy "mM' ' b)- liP

1llilllO!IZ2Z2 Ellf0\'"'!1 some nu bolton we other 11 cmne ISianel• !II Ule tan111)'• uam IOIIH goong SIWDeSS? notp t < p gOnuYf!!Q\tA"' "wW ·:.r, ... lll!IW..1Ull @nnllllal<at36 0v"~~~e'z ~LJCIOOJS2t.le oT....-"-"' ocweur~ Gl.l Bl.fssrlGS TOO ALL BOSTON WEATHER ISAI'IESOI.IEIII EIIJOY ....,..:.., .... ~ Bl;ilii!D @Ca»>eFreunG GlaO Bolton wuther c~~e<l see you later tooay Cas..ell AnO umcresas rrom IUVe$? WN1 c~creatUfesl ..... : .. , ....... l1ll!t.uxl RT @smccraclong SUnsn.ne and rresn saQ •~ nope anenr The resuiiS IO< INS·· Inaccurate

FIGURE 9 6 Sentiment 140 [41], an online tool for Twitter sentiment analysis

Emoticons make it easy and fast to detect sentiments of mi llions or bill ions of tweets. However, using

emoticons as the sole indicator of sentiments sometimes can be misleading, as emoticons may not neces- sarily correspond to the sentiments in the accompanied text. For example, the sample tweet shown in Figure 9-7 contains the : ) emoticon, but the text does not express a positive sentiment.

n LMack ~ J 1 have an awful reeling I'm gotng to ra tl my eYams )

FIGURE 9-7 Tweet with the:) emoticon does not necessarily correspond to a positive sentiment

To address this problem, related research usually uses Amazon Mechanical Turk (MTurk) [44) to col- lect human-tagged reviews. MTurk is a crowdsourcing Internet marketplace that enables individuals or businesses to coordinate the use of human intelligence to perform tasks that are difficult for computers to do. In many cases, MTurk has been shown to collect human input much faster compared to t raditional channels such as door-to-door surveys. For the example sentiment analysis task, the Data Science team

can publish the tweets collected from Section 9.3 to MTurk as Human Intelligence Tasks (HITs). The team can then ask human workers to tag each tweet as positive, neutral, or negative. The result can be used to train one or more classifiers or test the performances of classifiers. Figure 9-8 shows a sample task on MTurk related to sentiment analysis.

9.8 Gaining Insights

amazon mechanical turk Quolofatlons

284174 tllh • ~a l• !:•e. , ::,... -- HITs

All HITs 1 HITs Available To You I HITs Anlgned To You

111Ts .. Timer: OC.:OO:OO of 10 mmutes Total [arncd: SO.l ...

Total fli Ts Submitted: 1

Rt!qU~II cr: Cro...,cifllewtr Reward: SO.OS per HIT Ul ls Avnll.,ble: t2 Duration: 30 m•nutes Qualifications Rt!QUircd: HIT apprc ... al r.ue (•• ) IS ore.uer th.ln 96

&r~sks llelp • t ogm torrcwards

Task preview

Judge the Relevance and Sentiment of content about PayPal (206511)

POST RT @pesoexchanger Exchange your Paypal funds to CASH NOW• No more v.aoung for da)~' r-oo more dela)~'

Get money even on Holidays or http/ t CO/OJJqe3YatW

Plea<e pay close auentton to the post

Wh11t Is tho author's senti mont (fcelln&:) throu&:hout the post (outlined In rod) 115 It relates to PayPal'?

Very Posun.e Slightly POS!tl\e

Neutral

Slightly Negatove

Very Negatl\e

F.=oQ I Cer·,~ ' I '-!!'~"'~" at "'"'•:::I'! I ce~- :~~ I :: :oo s·:~t l ~.ma:en ccm, Inc cr 1:.S :.If, • •:u

FIGURE 9 8 Amazon Mechanical Turk

9.8 Gaining Insights

•s I elc ; An ama>oru:an company

So far this chapter has discussed several text analysis tasks including text collection, text representation, TFIDF, topic models, and sentiment analysis. This section shows how ACME uses these techniques to gain insights into customer opinions about its products. To keep the example simple, this section only uses

bPhone to illustrate the steps.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

Corresponding to the data collection phase, the Data Science team has used bPhone as the keyword to collect more than 300 reviews from a popular technical review website.

The 300 reviews are visualized as a word cloud after removing stop words. A word cloud (or tag

cloud) is a visual representation of textual data. Tags are generally single words, and the importance of each word is shown with font size or color. Figure 9-9 shows the word cloud built from the 300 reviews. The reviews have been previously case folded and tokenized into lowe rca sed words, and stop words have

been removed from the text. A more frequently appearing word in Figure 9-9 is shown with a larger font size. The orientation of each word is on ly for the aesthetical purpose. Most of the graph is taken up by the words phone and bphone, which occur frequently but are not very informative. Overall, the graph reveals

little information. The team needs to conduct further analyses on the data.

o ne .. 2::

. § d"~ """' ~ ~ II b button tfl ... -.· ~ ~- i ' -got ~new ~Oiklng-•• ~ • Pone

r - ••"" d d (.Uf' f I also •. love :~.:!'; ·=-~-~t pro .. ~~~ g 0 0 ,.,;·11 . - t c -o- tt(t~d

use used condition(SI Ike oneg re-at JUSt & a c me ~0 l N~•'Y • I • w•"~~ ~ • - WOrkS ~ phOneS - -t; ~ ~~me

• ~ first ...... bought ..., b get c t -· • .., ' r ., amazon- ..... back ':"" .. screen uy f,.~~ •. "' .. --.

Lf«~ !t ..... ,.. I- (' 1: P<Obl•m ·-.. . • - f I ' ~ br.IJ~d -

FiGURE 9-9 Word cloud on a/1300 reviews on bPhone

Fortunately, the popular technical review website allows users to provide ratings on a scale from one to five when they post reviews. The team can divide the reviews into subgroups using those ratings.

To reveal more information, the team can remove words such as phon e, b Phon e, and ACME, which are

not very useful for the study. Related research often refers to these words as domain-specific stop words.

Figure 9-10 shows the word cloud corresponding to SO five-star reviews extracted from the data. Note that the shades of gray are only for the aesthetical purpose. The result suggests that customers are satisfied with

the s elle r , the brand, and the product, and they recommend bPhone to their friends and families. Figure 9·11 shows the word cloud of 70 one-star reviews. The words s i m and b ut t o n occur fre-

quently enough that it would be advisable to sample the reviews that contain these terms and determine what is being said about buttons and SIM cards. Word clouds can reveal useful information beyond the most prominent terms. For example, the graph in Figure 9-11 oddly contains words likes t ol en and

Ven ezuela. As the Data Science team investigates the stories behind these words, it fi nds that these words appear in 1-star reviews because there are a few unauthorized sellers from Venezuela that sell stolen

9.8 Gaining Insights

bPhones. ACME can take further actions from this point. This is an example of how text analysis and even

simple visualizations can help gain insights.

never payhclp u~~~ b ..md "" day older Yet ~·u1•9 decldod utisllad any 0 y ~~apl t Way ateclkm rete better going Is~~!,.. ...

happy ...... ove go ~-~ ~..:cPfaSt give U~ed WBIIsysteD1 ,:: bought se erthank "gld recented;;;~ be·~ ,.,. - " ,,: •'•= -pleasedWDUid ... '"'""'"' kyscre:_ g 1:.0 a aw:c,h I( e J!!!l'!itely"!.W.Q_ .. ~s=.,

evet - able ~--u gooil=llrand Rrolluct ex;ct:d recommen ,..,. ......... firsts':etaJ..=eve~ing ~ordered condition makeneedCame~ "l service bevervone -anyo~e Sbll

'"' • ~ ~ llllnnMI \\'o-'·nd particular l"lttle ......... wanted uy-r also nlfurb•shed - case '"" • -- -··• - ree ...... ~ ..... ......... c. ...s_ l•• ·~~ perfect ustng ..,... · .. contrac1

11.-. ... nwtr -

FIGURE 9·1 0 Word cloud on five-star reviews

away days ·~n..t ,.91a.,.

:e~t slot looking d.lsappaiDIM I elou ~;::t_.. walusold hate withOUt screen unfortunately

aerv!ce tuna rt!devod brand de ~ ~ dd • • WTong blue g!usscUcrsellwaygive JCYDC,_d 0rt~ned pcu I~ Oftgot

• prodnc:tl c:oaapa.ay cant day all• many home a ve IS . to e lee VClnC%110 k

II;;Jlke t retumedlel thought~.~0.bolleve • r useCI t re urn'-lldmonthsSim first II L someone C ' make

.oo .. !':,robc,~WOU g ..... ""'e'·ttimeproductuougnt broke refurbished lrJ • - want activate~opleu-store purchasereceaved new tti case run could buying WOrk"angrrtiUdescrfption go ng com letel - • · olfor<ld

ltu.ld!d4llar.' • know brok(!n thlngs expenence work seem .tpenlbra~•ndUnlocked ca11sorderedca.U t problemspart!; bt;;:; Uyfreeablecard evensen . lostuse mall told purch~SM money devtce ~workswent took right

a.oythi.Dg d ont mac must bul101lll tum

dolw

FtGURE 9·11 Word cloud on one-star reviews

TFIDF can be used to highlight the informative words in the reviews. Figure 9-12 shows a subset of

the reviews in which each word with a larger font size corresponds to a higherTFIDF value. Each review is

considered a document. With TFIDF, data analysts can quick ly go through the reviews and identify what

aspects are perceived to make bPhone a good product or a bad product.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

**** m inor bugs septombor 11, 2011 this was for my sister who loves "· she says 1t has minor bugs but nothing sho cant deal .-.oth. sh•,. overall satisfied with 1t

.,.r,rw m int condition 1 1 3 SOpt•mt>er 13, 2013 great price. not a scratch or bump on th~ bphone ' 1t came • lot speedier than expected so thats always • plus 1 Its just wonderful . only had 1t for a couple of days and could n't ask for anything more 1 1 1 1

w buttons d id not work september os. 20t3 when 1 went to have my contacts transferred 1t was found that the two buttons need to switch did not work consistantly

~ it's a bphone. August 12, 2013

1 hate acme and acme products. base both on princip le and on functiona lity c or lack thereof l . that being said 1 guess this phone 1s great for old people that aren't tech SaWy, I bOUght thiS for my aunt ,

just like new 1 love this phone August to, 2013 my phone,. great 1t came on time with everything '"the box and new. nothing was use. 1t was all '" Its orig ina l packag ing

ri g reat product August 10. 2013 1 lost my phone on halloween and needed • quick and easy replacement . the phone was'" very good cond it ion . and had met my expectation .

ot * bphone My 26, 2013 the phone was clean . unscratched and on good condlt1on. 1 just wi sh the battery lasted a little longer. otherwise a great purchase 1

_.,..,... bphone July 2s. 2011 love my bphone 1 have not had any problems with 11. 1t 's easy to use and holds so much more than my last phone .

FIGURE 9-12 Reviews highlighted by TFIOF values

Topic models such as LOA can categorize the reviews into topics. Figures 9-13 and 9-14 show circular

graphs of top ics as results of the LOA. These figures are produced w ith tools and technologies such as

Python, NoSQL, and 03.js. Figure 9-13 visualizes ten topics buil t from the five-star reviews. Each topic focuses on a d i fferent aspect that can characterize the reviews. The disc size represents the weight o f a

word. In an interactive envi ro nment, hovering t he mouse over a topic d isplays the full words and their

corresponding weights.

Figure 9-14 visua lizes ten topics f rom one-star reviews. For example, the bottom-right topic contains

words such as but ton, power, and broken, w hich may indicate that bPhone has problems related to button and power supply. The Data Sc ience team can t rack down these reviews and fin d ou t if that 's

rea lly the case.

9.8 Gaining Insights

FIGURE 9· .s Ten topics on five-star reviews

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

FIGURE 9-14 Ten topics on one-star reviews

Figure 9-15 provides a different way to visualize the topics. Five topics are extracted from five-star

reviews and one-star reviews, respectively. In an interactive environment, hovering the mouse on a

topic highlights the corresponding words in this topic. The screenshots in Figure 9-15 were taken when

Top ic 4 is highlighted for both groups. The weight of a word in a topic is indicated by the disc size.

9.8 Gaining Insights

wou'd 0 0 would 0 0 t wort.s 0 0 0 wor~119 week Cl work 0 way 0 went 0 warehouse 0 used I usng 0 use

tme 0 two I 0 thank 0 slot 0 system 0 sm 0 • sweet C!) screen 0 l 1-urpnsed 0 return 0 seler 0 0 recerved 0 see 0 product 0

recoi'M'I!nd 0 0 people • receroed 0 0 one 0 0 0 p.rOduct 0 new 0 0 pleased 0 never 0 perfed 0 mac 0 one 0 know a

okSer 0 got 0 nice 0 get 0 love 0 0 free 0 like 8 fD< 0 9reat 0 g 0 frst 0 got disappoi1ted 0

good 0 0 device 0 gl'le 0 de-sct'1)tion 0 frst 0 coukl 0 day El case 0

came 0 cant • buyer 0 buy 0 0 I 0 brand 0 0 button • 0 bOught 0 0 broken 0 better 0 bought 0 0 0

able 0 back 0 0 Topic 1 Topic 2 Topic 3 Tope ~ TopicS Toptc 1 Topic 2 Topic 3 Topic.: Topic S

FIGURE 9-15 Five topics on five-star reviews (left) and 1-star reviews (right)

The Data Science team has also conducted sentiment analysis over 100 tweets from the popular micro-

blogging site Twitter. The result is shown in Figure 9-16. The left side represents negative sentiments, and

the right side represents positive sentiments. Vertica lly, the tweets have been randomly placed for aesthetic

purposes. Each tweet is shown as a disc, where the size represents the number of followers of the user who made the original tweet. The color shade of a disc represents how frequently this tweet has been retweeted.

The figure indicates that most customers are satisfied with ACME's bPhone.

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

• unpleasant • • •• • • • pleasant • • • • • •

fiGURE 9·16 Sentiment analysis on Tweets related to bPhone

Summary This chapter has discussed several subtasks of text analysis, including parsing, search and retrieval, and

text mining. With a brand management example, the chapter talks about a typical text analysis process:

(1) collecting raw text, (2) representing text, (3) using TFIDF to compute the usefulness of each word in the

texts, (4) categorizing documents by topics using topic modeling, (5) sentiment analysis, and (6) gaining

greater insights.

Overall text analysis is no trivia l task. Corresponding to the Data Analytic Lifecycle, the most time-

consuming parts of a text analysis project often are not performing the statistics or implementing algo-

rithms. Chances are the team would spend most of the time formulating the problem, getting the data,

and preparing the data.

Exercises 1. What are the main challenges of text analysis?

2. What is a corpus?

3. What are common words (such as a, and, of) cal led?

4. Why can't we use TF alone to measure the usefulness of the words?

5. What is a caveat of I OF? How does TFIDF address the problem?

6 . Name three benefits of using the TFIDF.

7. What methods can be used for sentiment analysis?

8. What is the defin ition of topic in topic models?

9 . Explain the trade-offs for precision and recal l.

1 0. Perform LOA topic modeling on the Reuters-2 1578 corpus using Python and LOA. The NLTK has

already come with the Reuters-21 578 corpus. To import this corpus, enter the following comment in the Python prompt:

from nltk .corpus import reut ers

Bibliography

The LOA has already been implemented by several Python libraries such as gensim [45]. Either use one such library or implement your own LOA to perform topic modeling on the Reuters-21578 corpus.

11 . Choose a topic of your interest, such as a movie, a celebrity, or any buzz word. Then collect 100 tweets related to this topic. Hand-tag them as positive, neutral, or negative. Next, split them into 80 tweets

as the training set and the remaining 20 as the testing set. Run one or more classifiers over these tweets to perform sentiment analysis. What are the precision and recall of these classifiers? Which

classifier performs better than the others?

Bibliography [1] Dr. Seuss, "Green Eggs and Ham," New York, NY, USA, Random House, 1960. [2] M. Steinbach, G. Karypis, and V. Kumar, "A Comparison of Document Clustering Techniques," KDD

Workshop on Text Mining, 2000. [3] "The Penn Treebank Project," University of Pennsylvania [Online]. Available: http: I /www. cis

. upenn . edu/ -treebank/home . html. [Accessed 26 March 2014]. [4] Wikipedia, "List of Open A Pis" [Onl ine]. Available: http: I I e n. wikipedia. org/wiki/

Li st_of_open_APis. [Accessed 27 March 2014]. [51 ProgrammableWeb, "API Directory" [Online]. Available: http: I / wwvl. programmableweb.

com/apis/directory. [Accessed 27 March 2014]. [6] Twitter, "Twitter Developers Site" [Online]. Available: ht tps : I /dev . twitter . com/ .

[Accessed 27 March 2014]. [7] "Curl and libcurl Tools" [Online]. Available: http : I I curl. haxx. se/. [Accessed 27 March

2014]. [8] "XML Path Language (X Path) 2.0," World Wide Web Consortium, 14 December 2010. [Onl ine].

Avai lable: http: I /www. w3. org/TR/xpath20 / . [Accessed 27 March 2014]. [9] "Gnip: The Source for Social Data," GNIP [Online]. Available: http : I /gnip. com/ . [Accessed 12

June 2014]. [10] "DataSift: Power Decisions with Social Data." DataSift [Online]. Available: http: I I datasi ft .

com/. [Accessed 12 June 2014]. [11] G. Salton and C. Buckley, "Term-Weighting Approaches in Automatic Text Retrieval," in Information

Processing and Management, 1988, pp. 513-523. [12] G. K. Zipf, Human Behavior and the Principle of Least Effort, Reading, MA: Addison-Wesley, 1949. [13] M. E. Newman, "Power Laws, Pareto Distributions, and Zipf's Law," Contemporary Physics, vol. 46,

no.5,pp.323-351, 2005. [1 4] Y. Li, D. Mclean, Z. A. Bandar, J.D. O'Shea, and K. Crockett, "Sentence Similarity Based on Semantic

Nets and Corpus Statistics," IEEE Transactions on Knowledge and Data Engineering, vol. 18, no. 8, pp. 1138- 1150, 2006.

[15] W. N. Francis and H. Kucera, "Brown Corpus Manual," 1979. [Online]. Available: ht tp : I /i came . uib . no/brown/bcm . html.

[16] "Cri tica l Assessment of Information Extraction in Biology (BioCreative)" [Online]. Ava ilable: http: I /www . biocreati ve . org/. [Accessed 2 April2014].

[17] J. J. Godfrey and E. Holliman, "Switchboard-1 Release 2," Linguistic Data Consortium, Philadelphia, 1997. [Online]. Available: http: I /catalog . ldc . upenn. edu/LDC97S62. [Accessed 2 April 2014].

ADVANCED ANALYTICAL THEORY AND METHODS: TEXT ANALYSIS

[18) P. Koehn, "Europarl: A Parallel Corpus for Statistical Machine Translation," MT Summit, 2005. (19) N. Seco, T. Veale, and J. Hayes, "An Intrinsic Information Content Metric for Semantic Similarity in

WordNet," ECAI, vol. 16, pp. 1089-1090,2004. [20] P. Resnik, "Using Information Content to Evaluate Semantic Similarity in a Taxonomy," In

Proceedings of the 14th International Joint Conference on Artificial intelligence (IJCA/'95), vol. 1, pp. 448-453, 1995.

[21) T. Pedersen, "Information Content Measures of Semantic Similarity Perform Better Without Sense-Tagged Text," Human Language Technologies: The 2010 Annual Conference of the North American Chapter of the Association for Computational Linguistics, pp. 329-332, June 2010.

[22] C. D. Manning, P. Raghavan, and H. Schutze, "Document and Query Weighting Schemes," in Introduction to Information Retrieval, Cambridge, United Kingdom, Cambridge University Press, 2008, p. 128.

[231 M. Porter, "Porter's English Stop Word List," 12 February 2007. [Online]. Available: http://snowball. tartarus.org/algorithms/english/stop.txt. [Accessed 2 April2014].

[24] M. Steinbach, G. Karypis, and V. Kumar, "A Comparison of Document Clustering Techniques," KDD workshop on text mining, vol. 400, no. 1, 2000.

[25] T. Joachims, "Transductive Inference for Text Classification Using Support Vector Machines," ICML, vol. 99, pp. 200-209, 1999.

[26] P. Soucy and G. W. Mineau, "A Simple KNN Algorithm for Text Categorization," /COM, pp. 647-648, 2001.

[27) B. Liu, X. Li, W. S. Lee, and P. S. Yu, "Text Classification by Labeling Words," AAAI, vol. 4, pp. 425-430, 2004.

[28) D. M. Blei, "Probabilistic Topic Models," Communications of the ACM, vol. 55, no. 4, pp. 77-84, 2012.

[29) D. M. Blei, A. Y. Ng, and M. I. Jordan, "Latent Dirichlet Allocation," Journal of Machine Learning Research, vol. 3, pp. 993-1022,2003.

[30) T. Minka, "Estimating a Dirichlet Distribution," 2000. [31) J. Chang, "Ida: Collapsed Gibbs Sampling Methods for Topic Models," CRAN, 14 October 2012.

[Online]. Available: http: I I cran . r-proj ect. org l webl packagesl ldal . [Accessed 3 April 2014].

[32) D. M. Blei, "Topic Modeling Software" [Online). Available: http://www.cs.princeton.edu/-blei/ topicmodeling.html. [Accessed 11 June 2014].

[33) A. McCallum, K. Nigam, J. Rennie, and K. Seymore, "A Machine Learning Approach to Building Domain-Specific Search Engines," /JCA/, vol. 99, 1999.

[34) P. D. Turney, "Thumbs Up or Thumbs Down? Semantic Orientation Applied to Unsupervised Classification of Reviews," Proceedings of the Association for Computational Linguistics, pp. 417-424, 2002.

[35) B. Pang, L. Lee, and S. Vaithyanathan, "Thumbs Up? Sentiment Classification Using Machine Learning Techniques," Proceedings ofEMNLP, pp. 79- 86,2002.

[36) M. Hu and B. Liu, "Mining and Summarizing Customer Reviews," Proceedings of the Tenth ACM S/GKDD International Conference on Knowledge Discovery and Data Mining, pp. 168-177, 2004.

[37) A. Agarwal, F. Biadsy, and K. R. Mckeown, "Contextual Phrase-Level Polarity Analysis Using Lexical Affect Scoring and Syntactic N-Grams," Proceedings of the 12th Conference of the European Chapter of the Association for Computational Linguistics, pp. 24-32, 2009.

Bibliography

[38] B. O'Connor, R. Balasubramanyan, B. R. Routledge, and N. A. Smith, "From Tweets to Polls: Linking Text Sentiment to Public Opinion Time Series," Proceedings of the Fourth International Conference on Weblogs and Social Media, ICWSM '70, pp. 122- 129,2010.

(39] A. Agarwal, B. Xie, I. Vovsha, 0. Rambow and R. Passonneau, "Sentiment Analysis of Twitter Data," In Proceedings of the Workshop on Languages in Social Media, pp. 30-38, 2011 .

(40] H. Sa if, Y. He, and H. Alani, "Semantic Sentiment Ana lysis ofT witter," Proceedings of the 11th International Conference on The Semantic Web (ISWC12), pp. 508-524,2012.

[41] A. Go, R. Bhayani, and L. Huang, "Twitter Sentiment Classification Using Distant Supervision," CS224N Project Report, Stanford, pp. 1- 12, 2009.

(42] A. Pak and P. Paroubek, "Twitter as a Corpus for Sentiment Analysis and Opinion Mining," Proceedings of the Seventh International Conference on Language Resources and Evaluation (LREC70), pp. 19-21, 2010.

[43] B. Pang and L. Lee, "Opinion Mining and Sentiment Analysis," Foundations and Trends in Information Retrieval, vol. 2, no. 1-2, pp. 1- 135,2008.

[44] "Amazon Mechanical Turk" [Online]. Available: http://www.mturk.com/. [Accessed 7 April2014]. [45] R. Rehurek, "Python Gensim Library" [Onl ine]. Avai lable: http://radimrehurek.com/gensim/.

[Accessed 8 April 2014].

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

Chapter 4, "Advanced Analytical Theory and Methods: Clustering," through Chapter 9, "Advanced Analytical Theory and Methods: Text Analysis," covered several useful analytical methods to classify, predict, and examine relationships within the data. This chapter and Chapter 11, "Advanced Analytics- Technology and

Tools: In-Database Analytics," address several aspects of collecting, storing, and processing unstructured

and structured data, respective ly. This chapter presents some key technologies and tools related to the Apache Hadoop software library, "a framework that allows for the distributed processing of large datasets across clusters of computers using simple programming models" [1] .

This chapter focuses on how Hadoop stores data in a distributed system and how Hadoop implements a

simple programming paradigm known as MapReduce. Although this chapter makes some Java-specific ref-

erences, the only intended prerequisite knowledge is a basic understanding of programming. Furthermore, the Java-specific details of writing a MapReduce program for Apache Hadoop are beyond the scope of

th is text. This omission may appear troublesome, but tools in the Hadoop ecosystem, such as Apache Pig and Apache Hive, can often eliminate the need to explicitly code a MapReduce program. Along with

other Hadoop-related tools, Pig and Hive are covered in a portion of this chapter deal ing with the Hadoop ecosystem.

To illustrate the power of Hadoop in handling unstructured data, the following discussion provides several Hadoop use cases.

10.1 Analytics for Unstructured Data Prior to conducting data analysis, the requ ired data must be collected and processed to extract the useful information. The degree of initia l processing and data preparation depends on the volume of data, as well as how straightforward it is to understand the structure of the data.

Recall the four types of data structures discussed in Chapter 1, "Introduction to Big Data Analytics":

• Structured: A specific and consistent format (for example, a data table)

• Semi-structured: A self-describing format (for example, an XML fi le)

• Quasi-structured: A somewhat inconsistent format (for example, a hyperlink)

• Unstructured: An inconsistent format (for example, text or video)

Structured data, such as relational database management system (RDBMS) tables, is typically the easiest data format to interpret. However, in practice it is still necessary to understand the various values that may appear in a certain column and what these values represent in different situations (based, for example, on the contents of the other columns for the same record). Also, some columns may contain unstructured text or stored objects, such as pictures or videos. Although the tools presented in th is chapter focus on unstructured data, these tools can also be utilized for more structured datasets.

10.1.1 Use Cases The following material provides several use cases for MapReduce. The MapReduce paradigm offers the

means to break a large task into smaller tasks, run tasks in parallel, and consolidate the outputs of the individual tasks into the final output. Apache Hadoop includes a software implementation of MapReduce. More details on MapReduce and Hadoop are provided later in this chapter.

10.1 Analytics for Unstructured Data

IBM Watson

In 2011, IBM's computer system Watson participated in the U.S. television game show Jeopardy against two of the best Jeopardy champions in the show's history. In the game, the contestants are provided a clue such as "He likes his martinis shaken, not stirred" and the correct response, phrased in the form of a question, would be, "Who is James Bond?" Over the three-day tournament, Watson was able to defeat the two human contestants.

To educate Watson, Hadoop was utilized to process various data sources such as encyclopedias, diction- aries, news wire feeds, literature, and the entire contents of Wikipedia [2]. For each clue provided during the game, Watson had to perform the following tasks in less than three seconds [3]:

o Deconstruct the provided clue into words and phrases

o Establish the grammatical relationship between the words and the phrases

o Create a set of similar terms to use in Watson's search for a response

o Use Hadoop to coordinate the search for a response across terabytes of data

o Determine possible responses and assign their likelihood of being correct

o Actuate the buzzer

o Provide a syntactically correct response in English

Among other applications, Watson is being used in the medical profession to diagnose patients and provide treatment recommendations [4].

Linkedln

Linked In is an online professional network of 250 million users in 200 countries as of early 2014 [5]. Linkedln provides several free and subscription-based services, such as company information pages, job postings, talent searches, social graphs of one's contacts, personally tailored news feeds, and access to discussion groups, including a Hadoop users group. Linkedln utilizes Hadoop for the following purposes [6]:

o Process daily production database transaction logs

o Examine the users' activities such as views and clicks

o Feed the extracted data back to the production systems

o Restructure the data to add to an analytical database

o Develop and test analytical models

Yahoo!

As of 2012, Yahoo! has one of the largest publicly announced Hadoop deployments at 42,000 nodes across several clusters utilizing 350 petabytes of raw storage [7]. Yahoo!'s Hadoop applications include the following [8]:

o Search index creation and maintenance

o Web page content optimization

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

• Web ad placement optimization

• Spam fi lters

• Ad-hoc analysis and analytic model development

Prior to deploying Hadoop, it took 26 days to process three years' worth of log data. With Hadoop, the

processing time was reduced to 20 minutes.

10.1.2 MapReduce As mentioned earlier, the MapReduce paradigm provides the means to break a large task into smaller tasks,

run the tasks in parallel, and consolidate the outputs of the individual tasks into the final output. As its name implies, MapReduce consists of two basic parts-a map step and a reduce step- detailed as follows:

Map:

• Applies an operation to a piece of data

• Provides some intermediate output

Reduce:

• Consolidates the intermediate outputs from the map steps

• Provides the final output

Each step uses key/value pairs, denoted as <key, value>, as input and output. It is useful to think of

the key/va lue pairs as a simple ordered pair. However, the pairs can take fairly complex forms. For example, the key could be a fi lename, and the value could be the entire contents of the fi le.

The simplest illustration of MapReduce is a word count example in which the task is to simply count

the number of times each word appears in a collection of documents. In practice, the objective of such an exercise is to establish a list of words and their frequency for purposes of search or establishing the relative importance of certa in words. Chapter 9 provides more details on text analytics. Figure 10-1 illustrates the

MapReduce processing for a single input- in this case, a line of text.

<1234, "For each word in each string">

• Map

<For, 1> <each, 1> <word, 1> <in, 1> <each, 1 > <string, 1>

• Reduce

<For, 1> <each, 2> <word, 1 >

<in, 1> <string, 1>

FIGURE 10-1 Example of how MapReduce works

10.1 Analytics for Unstructured Data

In this example, the map step parses the provided text string into individual words and emits a set of key/value pairs of the form <word, 1 >. For each unique key-in this example, word-the reduce step sums the 1 values and outputs the <word, count> key/value pairs. Because the word each appeared twice in the given line of text, the reduce step provides a corresponding key/value pair of <each, 2>.

It should be noted that, in this example, the original key, 12 34, is ignored in the processing. In a typical word count application, the map step may be applied to millions of lines of text, and the reduce step will summarize the key/value pairs generated by all the map steps.

Expanding on the word count example, the final output of a MapReduce process applied to a set of documents might have the key as an ordered pair and the value as an ordered tuple of length 2n. A possible representation of such a key/value pair follows:

<(filename, datetime), (word1,5, word2,7, ••• , wordn,6)>

In this construction, the key is the ordered pair f i 1 ename and date time. The value consists of the n pairs of the words and their individual counts in the corresponding file.

Of course, a word count problem could be addressed in many ways other than MapReduce. However, Map Reduce has the advantage of being able to distribute the workload over a cluster of computers and run the tasks in parallel. In a word count, the documents, or even pieces of the documents, could be pro- cessed simultaneously during the map step. A key characteristic of Map Reduce is that the processing of one portion of the input can be carried out independently of the processing of the other inputs. Thus, the workload can be easily distributed over a cluster of machines.

U.S. Navy rear admiral Grace Hopper (1906-1992), who was a pioneer in the field of computers, provided one of the best explanations of the need for using a group of computers. She commented that during pre- industrial times, oxen were used for heavy pulling, but when one ox couldn't budge a log, people didn't try to raise a larger ox; they added more oxen. Her point was that as computational problems grow, instead of building a bigger, more powerful, and more expensive computer, a better alternative is to build a system of computers to share the workload. Thus, in the Map Reduce context, a large processing task would be distributed across many computers.

Although the concept of Map Reduce has existed for decades, Google led the resurgence in its interest and adoption starting in 2004 with the published work by Dean and Ghemawat [9]. This paper described Google's approach for crawling the web and building Google's search engine. As the paper describes, MapReduce has been used in functional programming languages such as Lisp, which obtained its name from being readily able to process lists (llit Qrocessing).

In 2007, a well-publicized Map Reduce use case was the conversion of 11 million New York Times news- paper articles from 1851 to 1980 into PDF files. The intent was to make the PDF files openly available to users on the Internet. After some development and testing of the MapReduce code on a local machine, the 11 million PDF files were generated on a 100-node cluster in about 24 hours [10].

What allowed the development of the MapReduce code and its execution to proceed easily was that the Map Reduce paradigm had already been implemented in Apache Hadoop.

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

1 0.1.3 Apache Hadoop Although MapReduce is a simple paradigm to understand, it is not as easy to implement, especially in a distributed system. Executing a MapReduce job (the MapReduce code run against some specified data) requires the management and coordination of several activities:

o MapReduce jobs need to be scheduled based on the system's workload.

o Jobs need to be monitored and managed to ensure that any encountered errors are properly handled so that the job continues to execute if the system partially fails.

o Input data needs to be spread across the cluster.

o Map step processing of the input needs to be conducted across the distributed system, preferably on the same machines where the data resides.

o Intermediate outputs from the numerous map steps need to be collected and provided to the proper machines for the reduce step execution.

o Final output needs to be made available for use by another user, another application, or perhaps another MapReduce job.

Fortunately, Apache Hadoop handles these activities and more. Furthermore, many of these activities are transparent to the developer/user. The following material examines the implementation of Map Reduce in Hadoop, an open source project managed and licensed by the Apache Software Foundation [11].

The origins of Hadoop began as a search engine called Nutch, developed by Doug Cutting and Mike Cafarella. Based on two Google papers [9] [12], versions of Map Reduce and the Google File System were added to Nutch in 2004.1n 2006, Yahoo! hired Cutting, who helped to develop Hadoop based on the code in Nutch [13]. The name "Hadoop" came from the name of Cutting's child's stuffed toy elephant that also inspired the well-recognized symbol for the Hadoop project.

Next, an overview of how data is stored in a Hadoop environment is presented.

Hodoop Distributed File System (HDFS)

Based on the Google File System [12], the Hadoop Distributed File System (HDFS) is a file system that provides the capability to distribute data across a cluster to take advantage of the parallel processing of MapReduce. HDFS is not an alternative to common file systems, such as ext3, ext4, and XFS. In fact, HDFS depends on each disk drive's file system to manage the data being stored to the drive media. The Hadoop Wiki [14] provides more details on disk configuration options and considerations.

For a given file, HDFS breaks the file, say, into 64MB blocks and stores the blocks across the cluster. So, if a file size is 300MB, the file is stored in five blocks: four 64MB blocks and one 44MB block. If a file size is smaller than 64 MB, the block is assigned the size of the file.

Whenever possible, HDFS attempts to store the blocks for a file on different machines so the map step can operate on each block of a file in parallel. Also, by default, HDFS creates three copies of each block across the cluster to provide the necessary redundancy in case of a failure. If a machine fails, HDFS replicates an accessible copy of the relevant data blocks to another available machine. HDFS is also rack aware, which means that it distributes the blocks across several equipment racks to prevent an entire rack failure from causing a data unavailable event. Additionally, the three copies of each block allow Hadoop some flexibility in determining which machine to use for the map step on a particular block. For example,

1 0.1 Analytics for Unstructured Data

an idle or underutilized machine that contains a data block to be processed can be scheduled to process that data block.

To manage the data access, HDFS utilizes three Java daemons (background processes): NameNode, Data Node, and Secondary NameNode. Running on a single machine, the NameNode daemon determines and tracks where the various blocks of a data file are stored. The DataNode daemon manages the data stored on each machine. If a client application wants to access a particular file stored in HDFS, the applica- tion contacts the NameNode, and the NameNode provides the application with the locations of the various blocks for that file. The application then communicates with the appropriate Data Nodes to access the file.

Each DataNode periodically builds a report about the blocks stored on the DataNode and sends the report to the NameNode. If one or more blocks are not accessible on a Data Node, the NameNode ensures that an accessible copy of an inaccessible data block is replicated to another machine. For performance reasons, the Name Node resides in a machine's memory. Because the NameNode is critical to the opera- tion of HDFS, any unavailability or corruption of the NameNode results in a data unavailability event on the cluster. Thus, the Name Node is viewed as a single point of failure in the Hadoop environment [15]. To minimize the chance of a NameNode failure and to improve performance, the NameNode is typically run on a dedicated machine.

A third daemon, the Secondary NameNode, provides the capability to perform some of the NameNode tasks to reduce the load on the NameNode. Such tasks include updating the file system image with the contents of the file system edit logs. It is important to note that the Secondary NameNode is not a backup or redundant Name Node. In the event of a NameNode outage, the Name Node must be restarted and ini- tialized with the last file system image file and the contents of the edits logs. The latest versions of Hadoop provide an HDFS High Availability (HA) feature. This feature enables the use of two NameNodes: one in an active state, and the other in a standby state. If an active NameNode fails, the standby Name Node takes over. When using the HDFS HA feature, a Secondary NameNode is unnecessary [16].

Figure 10-2 illustrates a Hadoop cluster with ten machines and the storage of one large file requiring three HDFS data blocks. Furthermore, this file is stored using triple replication. The machines running the NameNode and the Secondary Name Node are considered master nodes. Because the Data Nodes take their instructions from the master nodes, the machines running the Data Nodes are referred to as worker nodes.

Structuring a MapReduce Job in Hadoop

Hadoop provides the ability to run MapReduce jobs as described, at a high level, in Section 10.1.2. This section offers specific details on how a Map Reduce job is run in Hadoop. A typical MapReduce program in Java consists of three classes: the driver, the mapper, and the reducer.

The driver provides details such as input file locations, the provisions for adding the input file to the map task, the names of the mapper and reducer Java classes, and the location of the reduce task output. Various job configuration options can also be specified in the driver. For example, the number of reducers can be manually specified in the driver. Such options are useful depending on how the MapReduce job output will be used in later downstream processing.

The mapper provides the logic to be processed on each data block corresponding to the specified input files in the driver code. For example, in the word count Map Reduce example provided earlier, a map task is instantiated on a worker node where a data block resides. Each map task processes a fragment of the text, line by line, parses a line into words, and emits <word, 1 > for each word, regardless of how many

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

times word appea rs in the line of text. The key/value pairs are stored temporarily in the worker node's

memory (or cached to the node's disk).

Master Nodes

Name Node

lnput_file.txt .. Block 1,2,3

Secondary Name Node

f iGURE 10-2 A file stored in HDFS

8 Worker Nodes across 2 Racks

r----------., r----------., Data Node

I

Block 1 Block 2

Data Node

Block 3

Data Node

Block 1

Data Node

Block 2 Block 3

Data Node

Block 1

Data Node

Block 2

Data Node

Block 3

Data Node

I I

L---------...1 L---------...1

Next, the key/value pairs are processed by the built-in shuffle and sort functionality based on the number of reducers to be executed.ln this simple example, there is only one reducer. So, all the intermedi- ate data is passed to it. From the various map task outputs, for each unique key, arrays (lists in Java) of the

associated values in the key/va lue pairs are constructed. Also, Hadoop ensures that the keys are passed to each reducer in sorted order. In Figure 10-3, <each, ( 1, 1 ) > is the first key/value pair processed, followed

alphabetical ly by < For, ( 1 ) > and the rest of the key/value pairs until the last key/value pair is passed to the reducer. The ( ) denotes a list of values which, in this case, is just an array of ones.

In general, each reducer processes the values for each key and emits a key/va lue pair as defined by the reduce logic. The output is then stored in HDFS like any other file in, say, 64 MB blocks replicated three times across the nodes.

Additional Considerations in Structuring a MapReduce Job

The preceding discussion presented the basics of structuring and running a MapReduce job on a Hadoop

cluster. Several Hadoop features provide additional functionality to a MapReduce job. First, a combiner is a useful option to apply, when possible, between the map task and the shuffle and

sort. Typically, the combiner applies the same logic used in the reducer, but it also applies this logic on the output of each map task. In the word count example, a combiner sums up the number of occurrences of

10.1 Analytics for Unstructured Data

each word from a mapper's output. Figure 10-4 illustrates how a combiner processes a single string in the

simple word count example.

<1234, "For each word in each string">

• Map

<For, 1> <each, 1> <word, 1> <in, 1> <each, 1 > <string, 1>

Shuffle and Sort

<each, (1, 1)> <For, (1)> <in, (1)> <string, (1)> <word, (1)>

• Reduce

<each, 2> <For, 1> <in, 1>

<string, 1> <word, 1>

FIGURE 1C .) Shuffle and sort

<1234, "For each word in each string">

• Map

<For, 1> <each, 1> <word, 1> <in, 1> <each, 1> <string, 1>

• Combine

<For, 1> <each, 2> <word, 1> <in, 1> <string, 1>

• Shuffle and Sort

FIGURE 1 C Using a combiner

Thus, in a production setting, instead of ten thousand possible < the , 1 > key/ value pai rs being emit-

ted from the map task to the Shuffle and Sort, the combiner emits one <the , 1 o 00 0 > key/ value pair.

The reduce step still obtains a list of values for each word, but instead of receiving a list of up to a million

oneslist(1,1, ... ,1 ) forakey,thereduce stepobtainsalist,suchaslist ( 10000 , 964, .

. . , 834 5 ) , which might be as long as the number of map tasks that were run. The use of a combiner

minimizes the amount of intermediate map output that the reducer must store, transfer over the network,

and process.

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

Another useful option is the partitioner. It determines the reducers that receive keys and the cor- responding list of values. Using the simple word count example, Figure 10-5 shows that a partitioner can

send every word that begins with a vowel to one reducer and the other words that begin with a consonant

to another reducer.

<1234, "For each word in each string">

.. Map

<For, 1 > <each, 1> <word, 1> <in, 1> <each, 1> <string, 1>

.. Partition (Shuffle)

<each, (1, 1) <in, (1)>

.. Reduce

fiGURE 10 5 Using a custom partitioner

<For, (1)> <string, (1)> <word, (1)>

.. Reduce

As a more practical example, a user cou ld use a partitioner to separate the output into separate fi les for each calendar year for subsequent analysis. Also, a partitioner could be used to ensure that the work-

load is evenly distributed across the reducers. For example, if a few keys are known to be associated with a large majority of the data, it may be useful to ensure that these keys go to separate reducers to achieve

better overall performance. Otherwise, one reducer might be assigned the majority of the data, and the MapReduce job wi ll not complete until that one long-running reduce task completes.

Developing and Executing a Hadoop MapReduce Program

A common approach to develop a Hadoop MapReduce program is to write Java code using an Interactive Development Environment (IDE) tool such as Eclipse [17]. Compared to a plaintext editor or a command- line interface (CLI), IDE tools offer a better experience to write, compile, test, and debug code. A typical

MapReduce program consists of three Java files: one each for the driver code, map code, and reduce code. Additional, Java files can be written for the combiner or the custom partitioner, if applicable. The Java code is compiled and stored as a Java Archive (JAR) file. This JAR file is then executed against the specified

HDFS input files. Beyond learning the mechanics of submitting a MapReduce job, three key challenges to a new Hadoop

developer are defining the logic of the code to use the Map Reduce paradigm; learning the Apache Hadoop Java classes, methods, and interfaces; and implementing the driver, map, and reduce functionality in Java. Some prior experience with Java makes it easier for a new Hadoop developer to focus on learning Hadoop

and writing the Map Reduce job. For users who prefer to use a programming language other than Java, there are some other options.

One option is to use the Hadoop Streaming API, which allows the user to write and run Hadoop jobs with no direct knowledge of Java [18]. However, knowledge of some other programming language, such as Python, C, or Ruby, is necessary. Apache Hadoop provides the Hadoop - streaming. jar fi le that

10.1 Analytics for Unstructured Data

accepts the HDFS paths for the input/output files and the paths for the files that implement the map and reduce functionality.

Here are some important considerations when preparing and running a Hadoop streaming job:

o Although the shuffle and sort output are provided to the reducer in key sorted order, the reducer does not receive the corresponding values as a list; rather, it receives individual key/value pairs. The reduce code has to monitor for changes in the value of the key and appropriately handle the new key.

o The map and reduce code must already be in an executable form, or the necessary interpreter must already be installed on each worker node.

o The map and reduce code must already reside on each worker node, or the location of the code must be provided when the job is submitted. In the latter case, the code is copied to each worker node.

o Some functionality, such as a partitioner, still needs to be written in Java.

o The inputs and outputs are handled through stdin and stdout. Stderr is also available to track the status of the tasks, implement counter functionality, and report execution issues to the display [18].

o The streaming API may not perform as well as similar functionality written in Java.

A second alternative is to use Hadoop pipes, a mechanism that uses compiled C++ code for the map and reduced functionality. An advantage of using C++ is the extensive numerical libraries available to include in the code [19].

To work directly with data in HDFS, one option is to use the C API (libhdfs) or the Java API provided with Apache Hadoop. These APis allow reads and writes to H DFS data files outside the typical MapReduce paradigm [20]. Such an approach may be useful when attempting to debug a MapReduce job by examin- ing the input data or when the objective is to transform the HDFS data prior to running a MapReduce job.

Yet Another Resource Negotiator (YARN)

Apache Hadoop continues to undergo further development and frequent updates. An important change was to separate the Map Reduce functionality from the functionality that manages the running of the jobs and the associated responsibilities in a distributed environment. This rewrite is sometimes called Map Reduce 2.0, or Yet Another Resource Negotiator (YARN). YARN separates the resource management of the cluster from the scheduling and monitoring of jobs running on the cluster. The YARN implementation makes it possible for paradigms other than MapReduce to be utilized in Hadoop environments. For example, a Bulk Synchronous Parallel (BSP) [21] model may be more appropriate for graph processing than MapReduce [22] is. Apache Hama, which implements the BSP model, is one of several applications being modified to utilize the power of YARN [23].

YARN replaces the functionality previously provided by the Job Tracker and TaskTracker daemons. In earlier releases of Hadoop, a Map Reduce job is submitted to the Job Tracker daemon. The Job Tracker communicates with the NameNode to determine which worker nodes store the required data blocks for the MapReduce job. The Job Tracker then assigns individual map and reduce tasks to the Task Tracker running on worker nodes. To optimize performance, each task is preferably assigned to a worker node that is storing an input data block. The TaskTracker periodically communicates with the Job Tracker on the status of its executing tasks. If a task appears to have failed, the Job Tracker can assign the task to a different TaskTracker.

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

10.2 The Hadoop Ecosystem So far, this chapter has provided an overview of Apache Hadoop relative to its implementation of HDFS and the Map Reduce paradigm. Hadoop's popularity has spawned proprietary and open source tools to

make Apache Hadoop easier to use and provide additional functionality and features. This portion of the chapter examines the following Hadoop-related Apache projects:

• Pig: Provides a high-level data-flow programming language

• Hive: Provides SOL-like access

• Mahout: Provides analytical tools

• HBase: Provides real-time reads and writes

By masking the details necessary to develop a MapReduce program, Pig and Hive each enable a devel-

oper to write high-level code that is later translated into one or more MapReduce programs. Because Map Reduce is intended for batch processing, Pig and Hive are also intended for batch processing use cases.

Once Hadoop processes a dataset, Mahout provides severa l tools that can analyze the data in a Hadoop environment. For example, a k-means clusteri ng analysis, as described in Chapter 4, can be conducted

using Mahout. Differentiating itself from Pig and Hive batch processing, HBase provides the ability to perform real-t ime

reads and writes of data stored in a Hadoop environment. This real-time access is accomplished partly by

storing data in memory as well as in HDFS. Also, HBase does not rely on MapReduce to access the HBase

data. Because the design and operation of HBase are significantly different from relational databases and the other Hadoop tools examined, a detai led description of HBase wi ll be presented.

10.2.1 Pig Apache Pig consists of a data flow language, Pig Latin, and an environment to execute the Pig code. The

main benefit of using Pig is to utilize the power of Map Reduce in a distributed system, while simplifying the tasks of developing and executing a MapReduce job. In most cases, it is transparent to the user that a MapReduce job is running in the background when Pig commands are executed. This abstraction layer

on top of Hadoop simplifies the development of code against data in HDFS and makes Map Reduce more accessible to a larger audience.

Like Hadoop, Pig's origin began at Yahoo! in 2006. Pig was transferred to the Apache Software

Foundation in 2007 and had its first release as an Apache Hadoop subproject in 2008. As Pig evolves over time, three main characteristics persist: ease of programming, behind-the-scenes code optimization, and extensibil ity of capabilities [24].

With Apache Hadoop and Pig already installed, the basics of using Pig include entering the Pig execu- tion environment by typing pig at the command prompt and then entering a sequence of Pig instruction Jines at the grunt prompt.

An example of Pig-specific commands is shown here:

$ pig gr unt> records = LOAD ' / user/ customer.txt' AS

(cust_id:INT, first_name : CHARARRAY,

l as t_name :CHARARRAY, emai l _address :CHARARRAY) ;

gr unt > f i lter ed_records = FILTER r ecords

10.2 The Hadoop Ecosystem

BY email_address mat ches ' . *@isp. com '; grunt > STORE filter ed r ecords I NTO ' / user/ isp_customers ' ; grunt> qui t $

At the first grun t prompt, a text file is designated by the Pig variable recor ds with four defined

fields: cust id, f irst_ name, l ast_ name, and ema il_ address. Next, the variable f il- te r ed_ r ecor d s is assigned those records where the email_ add r ess ends with ®i s p . com to extract the customers whose e-mail address is from a particular Internet service provider (ISP). Using the

STORE command, the filtered records are written to an HDFS folder, i sp _ cus tamer s. Finally, to exit the interactive Pig envi ronment, execute the QUIT command. Alternatively, these individual Pig commands

could be written to the fi le f i l t er _script. pig and submit them at the command prompt as follows:

$ p i g fil ter_script .pig

Such Pig instructions are translated, behind the scenes, into one or more MapReduce jobs. Thus, Pig simplifies the coding of a MapReduce job and enables the user to quickly develop, test, and debug the Pig code. In this particular example, the MapReduce job would be initiated after the STORE command

is processed. Prior to the STORE command, Pig had begun to build an execution plan but had not yet

initiated MapReduce processing. Pig provides for the execution of several common data manipulations, such as inner and outer joins

between two or more files (tables). as would be expected in a typical relational database. Writ ing these joins explicitly in MapReduce using Hadoop would be quite involved and complex. Pig also provides a

GROUP BY functionality that is similar to the Group By functionality offered in SOL. Chapter 11 has more details on using Gr oup By and other SOL statements.

An additional feature of Pig is that it provides many built-in functions that are easily utilized in Pig code. Table 10-1 includes several useful functions by category.

TABLE 10 1 Built- In Pig Functions

Eval Load/Store Math String DateTime

AVG BinS t or age ( ) ABS INDEXOF AddDurat i on

CONCAT JsonLoader CEIL LAST Current Time

I NDEX_OF

COUNT JsonStorage cos, ACOS LCFORST DaysBetween

COUNT STAR Pig Dump EXP LOWER Get Day

DIFF Pi g Storage FLOOR REG EX - GetHour EXTRACT

(continues)

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

To • r , 0-1 Built-In Pig Functions (Continued)

Eval Load/Store Math String DateTime

Is Empty Text Loader LOG, LOGlO REPLACE GetMinute

MAX HBaseStorage RANDOM STRSPLIT GetMonth

MIN ROUND SUBSTRING Get Week

SIZE SIN, ASIN TRIM GetWeekYear

SUM SQRT UCFIRST Get Year

TOKENIZE TAN, ATAN UPPER MinutesBetween

SubtractDuration

ToDate

Other functions and the details of these built-in functions can be found at the pig. apache. org website 125].

In terms of extensibility, Pig allows the execution of user-defined functions (UDFs) in its environment.

Thus, some complex operations can be coded in the user's language of choice and executed in the Pig

environment. Users can share their UDFs in a repository called the Piggybank hosted on the Apache site [26]. Over time, the most useful UDFs may be included as bui lt-in functions in Pig.

10.2.2 Hive Similar to Pig, Apache Hive enables users to process data without explicitly writing MapReduce code. One

key difference to Pig is that the Hive language, HiveQL (Hive Query Language), resembles Structured Query Language (SQL) rather than a scripting language.

A Hive table structure consists of rows and columns. The rows typically correspond to some record,

transaction, or particular entity (for example, customer) detail. The values of the corresponding columns represent the various attributes or characteristics for each row. Hadoop and its ecosystem are used to apply some structure to unstructured data. Therefore, if a table structure is an appropriate way to view the restructured data, Hive may be a good tool to use.

Additionally, a user may consider using Hive if the user has experience with SQL and the data is already

in HDFS. Another consideration in using Hive may be how data will be updated or added to the Hive tables. If data will simply be added to a table periodically, Hive works well, but if there is a need to update data in place, it may be beneficial to consider another tool, such as HBase, which will be discussed in the next section.

Although Hive's performance may be better in certain applications than a conventional SQL database, Hive is not intended for rea l-time querying. A Hive query is first translated into a MapReduce job, which is then submitted to the Hadoop cluster. Thus, the execution of the query has to compete for resources with any other submitted job. Like Pig, Hive is intended for batch processing. Again, HBase may be a better choice for real-time query needs.

10.2 The Hadoop Ecosystem

To summarize the preceding discussion, consider using Hive when the following conditions exist:

o Data easily fits into a table structure.

o Data is already in HDFS. (Note: Non-HDFS files can be loaded into a Hive table.)

o Developers are comfortable with SQL programming and queries.

o There is a desire to partition datasets based on time. (For example, daily updates are added to the Hive table.)

o Batch processing is acceptable.

The remainder of the Hive discussion covers some HiveQL basics. From the command prompt, a user enters the interactive Hive environment by simply entering hive: $ hive hive>

From this environment, a user can define new tables, query them, or summarize their contents. To illustrate how to use HiveQL, the following example defines a new Hive table to hold customer data, load existing HDFS data into the Hive table, and query the table.

The first step is to create a table called customer to store customer details. Because the table will be populated from an existing tab ('\t')-delimited HDFS file, this format is specified in the table creation query.

hive> create table customer ( cust_id bigint, first_name string, last_name string, email_address string) row format delimited fields terminated by '\t';

The following HiveQL query is executed to count the number of records in the newly created table, customer. Because the table is currently empty, the query returns a result of zero, the last line of the provided output. The query is converted and run as a Map Reduce job, which results in one map task and one reduce task being executed.

hive> select count(*) from customer; Total MapReduce jobs =

Launching Job l out o~ Number of reduce tasks determined at compile time: 1 Starting Job= job_1394125045·nr,~o001, Trading URL =

http://pivhdsne:BOBB/proxy/application 1394125045435 0001/ Kill Command = /usr lib/gphd!hadoop bin/hadocp jcb

-k:ll JOb :194:25C45435 Hadoop job ir:fcrn1atior: :o1· Stage-:: r:urr.i)er cf :~tat=:,pe:!.-s: --,

number of reducer·s: 1 2014-03-06 12:30:23,542 Stage-1 map 2014-03-06 12:30:36,586 Stagc-1 map

Cumulative CPU 1.71 sec 2014-03-06 12:30:48,500 Stage-1 ~ap

Cumulative CP~ 3.76 sec

0 '", n·,duce = 0 ~" 100'~. recbce o~.

!-~d··_:~e

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

HilpR•~duce ':'<::-t '" ,'''l:J;ulat:·.,ce C'?U t~:ne: F. n ci e d _:; 2 c : ' ~· .; l -~ 5 C .; "4 c "'

,:c~b :: :-:al:: ; :-·c·_L: :•'·: .:. :iDF'S ;-:~i:.,: " s;_;.~·,:;::.s::;

Tu:al 1•lapRi:dUc•· ··p;r '1'ime S!>c:r:t: • :';eccmds

When querying large tables, Hive outperforms and scales better than most conventional database queries. As stated earlier, Hive translates HiveQL queries into MapReduce jobs that process pieces of large datasets in parallel.

To load the customer table with the contents of HDFS file, customer. txt, it is only necessary to provide the HDFS directory path to the file.

hive> load data inpath '/user/customer.txt' into table customer;

The following query displays three rows from the customer table.

hive> select * from customer limit 3;

.-~ c 576

It is often necessary to join one or more Hive tables based on one or more columns. The following example provides the mechanism to join the customer table with another table, orders, which stores the details about the customer's orders. Instead of placing all the customer details in the order table, only the corresponding cust _ id appears in the orders table.

hive> select o.order_number, o.order_date, c.* from orders o inner join customer c on o.cust_id = c.cust_id where c.email_address = 'mary.jones®isp.com';

Tuta 1 Hap?.eclu .,,

f: i l 1 Command

-;·.iE j ub

H~Hhop J cb : n i ::ur:Lte.!:· :__·:_

;-. -~ -. -

10.2 The Hadoop Ecosystem

:.:::j.c,:l J·~c

:.:cl p ==~.c. j '-~ :::~ .::2 r: '~ :-.•. r .- ;:.,,-, j:

lS!-::.

The use of joins and SQL in general will be covered in Chapter 11. To exit the Hive interactive environ- ment, use quit.

hive> quit; $

An alternative to running in the interactive environment is to collect the HiveQL statements in a script {for example, my _script. sql) and then execute the file as follows:

$ hive -f my_script.sql

This introduction to Hive provided some of the basic HiveQL commands and statements. The reader is encouraged to research and utilize, when appropriate, other Hive functionality such as external tables, explain plans, partitions, and the INSERT INTO command to append data to the existing content of a Hive table.

Following are some Hive use cases:

o Exploratory or ad-hoc analysis of HDFS data: Data can be queried, transformed, and exported to analytical tools, such as R.

o Extracts or data feeds to reporting systems, dashboards, or data repositories such as HBase: Hive queries can be scheduled to provide such periodic feeds.

o Combining external structured data to data already residing in HDFS: Hadoop is excellent for processing unstructured data, but often there is structured data residing in an RDBMS, such as Oracle or SQL Server, that needs to be joined with the data residing in HDFS. The data from an RDBMS can be periodically added to Hive tables for querying with existing data in HDFS.

10.2.3 HBase Unlike Pig and Hive, which are intended for batch applications, Apache HBase is capable of providing real-time read and write access to data sets with billions of rows and millions of columns. To illustrate the differences between HBase and a relational database, this section presents considerable details about the implementation and use of HBase.

The HBase design is based on Google's 2006 paper on Bigtable. This paper described Bigtable as a "distributed storage system for managing structured data." Google used Bigtable to store Google product-specific data for sites such as Go ogle Earth, which provides satellite images of the world. Big table was also used to store web crawler results, data for personalized search optimization, and website click- stream data. Bigtable was built on top of the Google File System. MapReduce was also utilized to process

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: MAP REDUCE AND HADOOP

data into or out of a Bigtable. For example, the raw clickstream data was stored in a Bigtable. Periodically,

a scheduled MapReduce job would run that would process and summarize the newly added clickstream data and append the results to a second Big table [27].

The development of HBase began in 2006. HBase was included as part of a Hadoop distribution at the

end of 2007. In May 2010, HBase became an Apache Top Level Project. Later in 2010, Facebook began to use HBase for its user messaging infrastructure, which accommodated 350 million users sending 15 billion messages per month [28].

HBase Architecture and Data Model

HBase is a data store that is intended to be distributed across a cluster of nodes. Like Hadoop and many of

its related Apache projects, HBase is built upon HDFS and achieves its real-time access speeds by sharing

the workload over a large number of nodes in a distributed cluster. An HBase table consists of rows and columns. However, an HBase table also has a third dimension, version, to maintain the different values of a row and column intersection over time.

To illustrate this third dimension, a simple example would be that for any given online customer, several shipping addresses could be stored. So, the row would be indicated by a customer number. One column

would provide the shipping address. The value of the shipping address would be added at the intersection of the customer number and the shipping address column, along with a timestamp corresponding to when

the customer last used this shipping address. During a customer's checkout process from an online retailer, a website might use such a table to retrieve

and display the customer's previous shipping addresses. As shown in Figure 10-6, the customer can then

select the appropriate address, add a new address, or delete any addresses that are no longer relevant.

Checkout (Step 2 of 4)

Choose a shipping address:

U 1600 Pennsylvania Avenue NW Washington DC, 20500 USA

U London SW1A 1AA, United Kingdom

U 3111TU, ~ m w 282001, India ~ '

Add a new address I

FIGURE 10-6 Choosing a shipping address at checkout

Last Used

~ Delete I 15-Apr-2014

~ Delete I 15-Mar-2014

~ Delete I 14-Feb-2014

Of course, in addition to a customer's shipping address, other customer information, such as billing

address, preferences, billing credits/debits, and customer benefits (for example, free shipping) must be stored. For this type of application, real-time access is required. Thus, the use of the batch processing of Pig, Hive, or Hadoop's MapReduce is not a reasonable implementation approach. The following discussion examines how HBase stores the data and provides real-time read and write access.

10.2 The Hadoop Ecosystem

As mentioned, HBase is built on top of HDFS. HBase uses a key/value structure to store the contents of an HBase table. Each value is the data to be stored at the intersection of the row, column, and version. Each key consists of the following elements [29]:

• Row length

• Row (sometimes called the row key)

• Column family length

• Column family

• Column qualifier

• Version

• Key type

The row is used as the primary attribute to access the contents of an HBase table. The row is the basis

for how the data is distributed across the cluster and allows a query of an HBase table to quickly retrieve

the desired elements. Thus, the structure or layout of the row has to be specifically designed based on how the data will be accessed. In this respect, an HBase table is purpose built and is not intended for general ad-hoc querying and analysis. In other words, it is important to know how the HBase table will be used;

this understanding of the table's usage helps to optimally define the construction of the row and the table. For example, if an HBase table is to store the content of e-mails, the row may be constructed as the

concatenation of an e-mail address and the date sent. Because the HBase table will be stored based on

the row, the retrieval of thee-mails by a given e-mail address will be fairly efficient, but the retrieval of all e-mails in a certain date range will take much longer. The later discussion on regions provides more details

on how data is stored in HBase. A column in an HBase table is designated by the combination of the column family and the col-

umn qualifier. The column family provides a high-level grouping for the column qualifiers. In the earlier shipping address example, the row could contain the order_ number, and the order details could be stored under the column family orders, using the column qualifiers such as s h ipping_ a ddress, bi 11 ing_ address, order_ date. In HBase, a column is specified as column family:column quali- fier. In the example, the column orders : shipping_ address refers to an order's shipping address.

A cell is the intersection of a row and a column in a table. The version, sometimes called the time- stamp, provides the abi lity to maintain different values for a cell's contents in HBase. Although the user can define a custom value for the version when writing an entry to the table, a typical HBase implemen-

tation uses HBase's default, the current system time. In Java, this timestamp is obtained with Sys tern . g etCu r r e n t TimeMil lis () ,the number of milliseconds since January 1, 1970. Because it is likely

that only the most recent version of a cell may be required, the cells are stored in descending order of the version. If the application requires the cells to be stored and retrieved in ascending order of their creation

time, the approach is to use Long . MAX_ VALUE - System. getCur ren tTimeMillis ( l in Java as the version number. Long. MAX_ VALUE corresponds to the maximum va lue that a long integer can be in Java. In this case, the storing and sorting is still in descending order of the version values.

Key type is used to identify whether a particular key corresponds to a write operation to the HBase table or a delete operation from the table. Technically, a delete from an HBase table is accomplished with

a write to the table. The key type indicates the purpose of the write. For deletes, a tombstone marker is

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

written to the table to indicate that all cell versions equal to or older than the specified timestamp should be deleted for the corresponding row and column f ami 1 y: column qualifier.

Once an HBase environment is installed, the user can enter the HBase shell environment by entering hbase shell at the command prompt. An HBase table, my_ table, can then be created as follows:

$ hbase shell hbase> create 'my_table', 'cfl', 'cf2',

{SPLITS =>['250000', '500000', '750000']}

Two column families, c f 1 and cf 2, are defined in the table. The SPLITS option specifies how the table will be divided based on the row portion of the key. In this example, the table is split into four parts, called regions. Rows less than 2 so o o 0 are added to the first region; rows from 2 5o o o o to less than 50 0 0 0 o are added to the second region, and likewise for the remaining splits. These splits provide the primary mechanism for achieving the real-time read and write access. In this example, my_ table is split into four regions, each on its own worker node in the Hadoop cluster. Thus, as the table size increases or the user load increases, additional worker nodes and region splits can be added to scale the cluster appropriately. The reads and writes are based on the contents of the row. HBase can quickly determine the appropriate region to direct a read or write command. More about regions and their implementation will be discussed later.

Only column families, not column qualifiers, need to be defined during HBase table creation. New column qualifiers can be defined whenever data is written to the HBase table. Unlike most relational data- bases, in which a database administrator needs to add a column and define the data type, columns can be added to an HBase table as the need arises. Such flexibility is one of the strengths of HBase and is certainly desirable when dealing with unstructured data. Over time, the unstructured data will likely change. Thus, the new content with new column qualifiers must be extracted and added to the HBase table.

Column families help to define how the table will be physically stored. An HBase table is split into regions, but each region is split into column families that are stored separately in HDFS. From the Linux command prompt, running hadoop f s -1 s - R /hbase shows how the HBase table, my_ table, is stored in HBase.

$ hadoop fs -ls -R /hbase

0 2014-02-28 16:40 /hbase/my_table/028ed22e02ad07d2d73344cd53a1lfb4

243 2014-02-28 16:40 /hbase/my_table/028ed22e02ad07d2d73344cd53allfb4/

. leg ioninfo

0 2014-02-28 16:4C hbase/~y_table,028ed22e02ad07d2d73344cd53allfb4 1 cfl

0 2014-02-28 16:40 hbase/my_table/028ed22e02ad07d2d73344cd53a1lfb4/ cf2

0 2014-02-28 16:40 1hbase/my_table/2327b09784889e6198909d8b8f342289

255 2014-02 28 16:40 1hbase/my_table/2327b09784889e6:98909d8b8f342289/

. ~-e~ioninfc 2014-02-28 16:40 hbase/m·.: table./2327b09784889eG:.989D9d8b8f342:289i

cfl 0 2014-02-28 16:40 /hbase/my_table/2327b09784889e6198909d8b8f342289/

cf2

0 2014-02-:28 16:40 /hbase/my_table/4b4fc9ad951297efe2b9b386~0f7a5fd

267 2014-02-28 16:40 hb~se/my_table 1 4b4fc9ad951297e!e:b9b38640f7a5fd• . !_·~g i oninf c

10.2 The Hadoop Ecosystem

0 2014-02-28 16:40 /hbase my_table, 4b4fc9ad951297efe2b9b38640f7a5fd/

cf1

0 201~-02-28 16:40 /hbase my table.4b4fc9ad951297e~e2b9b38E40~7a5fd, cf2

0 2014-02-28 16:40 /hbase/my_table/e40beOJ71f43135e36ea67edec6e31e3

267 2014-02-28 16:40 /hbase/mytable/e40be03'11f43135e36ea67edec6e31e3/

. regior:infc

2014-02-28 16:40 :1base.1m;.· table. e40beD37lf.;3::.35e36eaG7edec6e3le3

cfl 0 2014-02-28 16:40 1hbase;rny table;e40beD37:f4Jl35e36ea67edec6e3le3•

cf2

As can be seen, four subdirectories have been created under /hbase/mytable. Each subdirectory is named by taking the hash of its respective region name, which includes the start and end rows. Under each of these directories are the directories for the column families, cfl and c£2 in the example, and the . regioninfo file, which contains several options and attributes for how the regions will be maintained. The column family directories store keys and values for the corresponding column qualifiers. The column qualifiers from one column family should seldom be read with the column qualifiers from another column family. The reason for the separate column families is to minimize the amount of unnecessary data that HBase has to sift through within a region to find the requested data. Requesting data from two column families means that multiple directories have to be scanned to pull all the desired columns, which defeats the purpose of creating the column families in the first place.ln such cases, the table design may be better off with just one column family. In practice, the number of column families should be no more than two or three. Otherwise, performance issues may arise [30].

The following operations add data to the table using the put command. From these three put opera- tions, datal and da ta2 are entered into column qualifiers, cql and cq2, respectively, in column family c f 1. The value da ta3 is entered into column qualifier cq3 in column family c f 2. The row is designated by row key 0 0 0 7 0 0 in each operation.

hbase> put •my_table', '000700', 'cfl:cql', 'datal'

0 rm·: i. s: in 0. C C! 3 0 secor.ds

hbase> put •my_table', '000700', 'cfl:cq2', 'data2'

0 row(s) in 0.0030 seconds

hbase> put •my_table', '000700', 'cf2:cq3', 'data3'

0 row(s) in 0.0040 seconds

Data can be retrieved from the HBase table by using the get command. As mentioned earlier, the timestamp defaults to the milliseconds since January 1, 1970.

hbase> get 'my_table', '000700', 'cf2:cq3'

COLUMN CELL cf2: cq3 timestarnp=l3 93 866 lJ 37U, value~dctta3

1 ro·"· (s 1 in 0. 0350 seconds

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

By default, the get command returns the most recent version. To illustrate, after executing a second put operation in the same row and column, a subsequent get provides the most recently added value ofdata4.

hbase> put 'my_table', '000700', •cf2:cq3', 'data4'

0 row(s) in 0.0040 seconds

hbase> get •my_table', '000700', 'cf2:cq3'

COLU1·1N CELL

cf2:cq3

1 row(sl

timestamp=139386643l669,

in 0.0080 seconds

val;_:e=data4

The get operation can provide multiple versions by specifying the number of versions to retrieve. This example illustrates that the cells are presented in descending version order.

hbase> get 'my_table', '000700', {COLUMN;> 'cf2:cq3', VERSIONS;> 2}

COLU1·1N CELL

cf2:cq3 timestamp=139386643l669, 'ialue=data4

cf2:cq3 timestamp=l393866138714, value=data3

2 row(s) in 1.0200 seconds

A similar operation to the get command is scan. A scan retrieves all the rows between a specified STARTROW and a STOPROW, but excluding the STOPROW. Note: ifthe STOPROW was setto 000700, only row 000600 would have been returned.

hbase> scan 'my_table', {STARTROW => '000600', STOPROW =>'000800'}

R0\'1

000600

0007CO

0007CO

0007CO

COLut•IN+CELL

column=cfl:cq2, timestamp=l393866792008, value=data5

column=cfl:cql, timestamp=l393866105687, value=datal

column=cf1:cq2, timestamp=l393866122073, value=data2

col~mn=cf2:cq3, timestamp=139386643l6E9, value=data4

in 0.0400 seconds

The next operation deletes the oldest entry for column c f 2 : cq3 for row o o o 7 o o by specifying the timestamp.

hbase> delete •my_table', '000700', 'cf2:cq3', 1393866138714 0 row(s) irl 0.0110 seconds

Repeating the earlier get operation to obtain both versions only provides the last version for that cell. After all, the older version was deleted.

hbase> get 'my_table', '000700', {COLUMN=> 'cf2:cq3', VERSIONS=> 2}

COLUf.1N CELL

cf2:cq3 timestamp~l39386E431669, value,data4

1 rovlis) in O.Ol3J seconds

10.2 The Hadoop Ecosystem

However, running a scan operation, with the RAW option set to true, reveals that the deleted entry actually remains. The highlighted line illustrates the creation of a tombstone marker, which informs the

default get and scan operations to ignore all older cell versions of the particular row and column.

When will the deleted entries be permanently removed? To understand this process, it is necessary to

understand how HBase processes operations and achieves the real-time read and write access. As men-

tioned earlier, an HBase table is split into regions based on the row. Each region is maintained by a worker

node. During a put or delete operation against a particular reg ion, the worker node first writes the command to a Write Ahead Log (WAL) fi le for the region. The WAL ensures that the operations are not lost

if a system fails. Next, the results of the operation are stored within the worker node's RAM in a repository

called MemStore [31).

Writing the entry to the MemStore provides the real-time access required. Any client can access the

entries in the MemStore as soon as they are written. As the MemStore increases in size or at predetermined

time intervals, the sorted MemStore is then written (flushed) to a file, known as an HFi le, in HDFS on the

same worker node. A typical HBase implementation flushes the MemStore when its contents are slightly

less than the HDFS block size. Over time, these flushed files accumulate, and the worker node performs a

minor compaction that performs a sorted merge of the various flushed files.

Meanwhile, any get or scan requests that the worker node receives examine these possible storage locations:

• MemStore

• HFiles resulting from MemStore flushes

• HFiles from minor compactions

Thus. in the case of a delete operation followed relatively quickly by a get operation on the same row, the tombstone marker is found in the MemStore and the corresponding previous versions in the smaller

HFiles or previously merged HFiles. The get command is instantaneously processed and the appropriate

data returned to the client. Overtime, as the smaller HFiles accumulate, the worker node runs a majorcompaction that merges the

smaller HFiles into one large HFile. During the major compaction, the deleted entries and the tombstone

markers are permanently removed from the files.

Use Cases for HBase

As described in Google's Big table paper, a common use case for a data store such as HBase is to store the results from a web crawler. Using this paper's example, the row com . cnn . www, for example, corresponds

ADVANCED ANALYTICS-TECHNOLOGV AND TOOLS: MAPREDUCE AND HADOOP

to a website URl, www. cnn. com. A column family, called anchor, is defined to capture the website URLs that provide links to the row's website. What may not be an obvious implementation is that those anchoring website URLs are used as the column qualifiers. For example, if sportsillustrated . cnn. com provides a link to www. cnn. com, the column qualifier is sportsillustrated. cnn . com. Additional websites that provide links to www. cnn. com appear as additional column qualifiers. The value stored in the cell is simply the text on the website that provides the link. Here is how the CNN example may look in HBase following a get operation.

hbase> get 'web_table', 'com.cnn.www', {VERSIONS=> 2}

Additional results are returned for each corresponding website that provides a link to www. cnn . com. Finally, an explanation is required for using com. cnn. www for the row instead of www. cnn . com. By reversing the URLs, the various suffixes(. com, . gov, or . net) that correspond to the Internet's top-level domains are stored in order. Also, the next part of the domain name (cnn) is stored in order. So, all of the cnn. com websites could be retrieved by a scan with the STAR TROW of com. cnn and the appropriate STOPROW.

This simple use case illustrates several important points. First, it is possible to get to a billion rows and millions of columns in an HBase table. As of February 2014, more than 920 million websites have been identified [32]. Second, the row needs to be defined based on how the data will be accessed. An HBase table needs to be designed with a specific purpose in mind and a well-reasoned plan for how data will be read and written. Finally, it may be advantageous to use the column qualifiers to actually store the data of interest, rather than simply storing it in a cell. In the example, as new hosting websites are established, they become new column qualifiers.

A second use case is the storage and search access of messages. In 2010, Face book implemented such a system using HBase. At the time, Facebook's system was handling more than 15 billion user-to-user messages per month and 120 billion chat messages per month [33]. The following describes Facebook's approach to building a search index for user in boxes. Using each word in each user's message, an HBase table was designed as follows:

o The row was defined to be the user I D.

o The column qualifier was set to a word that appears in the message.

o The version was the message I D.

o The cell's content was the offset of the word in the message.

This implementation allowed Facebook to provide auto-complete capability in the search box and to return the results of the query quickly, with the most recent messages at the top. As long as the message IDs increase over time, the versions, stored in descending order, ensure that the most recent e-mails are returned first to the user [34].

These two use cases help illustrate the importance of the upfront design of the HBase table based on how the data will be accessed. Also, these examples illustrate the power of being able to add new columns

10.2 The Hadoop Ecosystem

by adding new column qualifiers, on demand. In a typical RDBMS implementation, new columns require the involvement of a DBA to alter the structure of the table.

Other HBase Usage Considerations

In addition to the HBase design aspects presented in the use case discussions, the following considerations are important for a successful implementation.

o Java API: Previously, several HBase shell commands and operations were presented. The shell com- mands are useful for exploring the data in an HBase environment and illustrating their use. However, in a production environment, the HBase Java API could be used to program the desired operations and the conditions in which to execute the operations.

o Column family and column qualifier names: It is important to keep the name lengths of the column families and column qualifiers as short as possible. Although short names tend to go against conventional wisdom about using meaningful, descriptive names, the names of column family name and the column qualifier are stored as part of the key of each key/value pair. Thus, every additional byte added to a name over each row can quickly add up. Also, by default, three copies of each HDFS block are replicated across the Hadoop cluster, which triples the storage requirement.

o Defining rows: The definition of the row is one of the most important aspects of the HBase table design. In general, this is the main mechanism to perform read/write operations on an HBase table. The row needs to be constructed in such a way that the requested columns can be easily and quickly retrieved.

o Avoid creating sequential rows: A natural tendency is to create rows sequentially. For example, if the row key is to have the customer identification number, and the customer identification num- bers are created sequentially, HBase may run into a situation in which all the new users and their data are being written to just one region, which is not distributing the workload across the cluster as intended [35]. An approach to resolve such a problem is to randomly assign a prefix to the sequential number.

o Versioning control: HBase table options that can be defined during table creation or altered later control how long a version of a cell's contents will exist. There are options forTimeTolive (TTL) after which any older versions will be deleted. Also, there are options for the minimum and maximum number of versions to maintain.

o Zookeeper: HBase uses Apache Zookeeper to coordinate and manage the various regions running on the distributed cluster. In general, Zookeeper is "a centralized service for maintaining configura- tion information, naming, providing distributed synchronization, and providing group services. All of these kinds of services are used in some form or another by distributed applications." [36] Instead of building its own coordination service, HBase uses Zookeeper. Relative to HBase, there are some Zookeeper configuration considerations [37].

1 0.2.4 Mahout The majority of this chapter has focused on processing, structuring, and storing large datasets using Apache Hadoop and various parts of its ecosystem. After a dataset is available in HDFS, the next step may be to apply an analytical technique presented in Chapters 4 through 9. Tools such as Rare useful for analyzing relatively small datasets, but they may suffer from performance issues with the large datasets stored in Hadoop. To apply the analytical techniques within the Hadoop environment, an option is to use Apache

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

Mahout. This Apache project provides executable Java libraries to apply analytical techniques in a scalable manner to Big Data. In general, a mahout is a person who controls an elephant. Apache Mahout is the toolset

that directs Hadoop, the elephant in this case, to yield meaningful analytic results. Mahout provides Java code that implements the algorithms for several techniques in the fol lowing

three categories [38]:

Classification:

• Logistic regression

• Na"lve Bayes

• Random forests

• Hidden Markov models

Clustering:

• Canopy clustering

• K-means clustering

• Fuzzy k-means

• Expectation maximization (EM)

Recommenders/collaborative filtering:

• Nondistributed recommenders

• Distributed item-based collaborative filtering

Pivotal HD Enterprise with HAWQ

Users can download and install Apache Hadoop and the described ecosystem tools directly from the www. apache . org website. Another installation option is downloading commercially packaged distributions of the various Apache Hadoop projects. These distributions often include additional user functionality as well as cluster management utilities. Pivotal is a company that provides a distribution called Pivotal HD Enterprise, as illustrated in Figure 10-7.

Pivotal HD Enterprise includes several Apache software components that have been presented in this chapter. Additional Apache software includes the following:

• Oozie: Manages Apache Hadoop jobs by acting as a workflow scheduler system

• Sqoop: Efficiently moves data between Hadoop and relational databases

• Flume: Collects and aggregates streaming data (for example, log data)

Additional functionality provided by Pivotal includes [39] the following:

• Command Center is a robust cluster management tool that allows users to install, con- figure, monitor, and manage Hadoop components and services through a web graphi- cal interface. It simplifies Hadoop cluster installation, upgrades, and expansion using a comprehensive dashboard with instant views of the health of the cluster and key perfor- mance metrics. Users can view live and historical information about the host, application,

1 0.2 The Hadoop Ecosystem

and job-level metrics across the entire Pivotal HD cluster. Command Center also provides CLI and web services APis for integration into enterprise monitoring services.

Pivotal HD Enterprise

HAWQ ' -'dv.n:cd Data !me S.Mcc•

I HDFS

- •ww·• • Aj>acho FIGURE 10·7 Components of Pivotal HD Enterprise

• PMXal - • Graphlab on Open MPI (Message Passing Interface) is a highly used and mature

graph-based, high-performing, distributed computation framework that easily scales to graphs with bil lions of vertices and edges. It is now able to run natively within an existing Hadoop cluster, eliminating costly data movement. This allows data scientists and analysts to leverage popular algorithms such as page rank, collaborative fi ltering, and computer vision natively in Hadoop rather than copying the data somewhere else to run the analytics, which would lengthen data science cycles. Combined with MADiib's machine learning algorithms for relational data, Pivotal HD becomes the leading advanced analytical platform for machine learning in the world.

• Hadoop Virtualizat ion Extensions (HVE) plug-ins make Hadoop aware of the virtual topology and sca le Hadoop nodes dynamically in a virtual environment. Pivotal HD is the first Hadoop distribution to include HVE plug-ins, enabling easy deployment of Hadoop in an enterprise environment. With HVE, Pivotal HD can deliver truly elastic sca lability in the cloud, augmenting on-premises deployment options.

• HAWQ (HAdoop With Query) adds SQL's expressive power to Hadoop to accelerate data analytics projects, simplify development while increasing productivity, expand Hadoop's capabilities, and cut costs. HAWQ can help render Hadoop queries faster than any Hadoop-based query interface on the market by adding rich, proven, parallel SQL processing facilities. HAWQ leverages existing business intelligence and analytics products and a workforce's existing SQL skills to bring more than 100 times perfor- mance improvement to a wide range of query types and workload s.

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAP REDUCE AND HADOOP

10.3 NoSQL NoSQL (Not only Structured Query Language) is a term used to describe those data stores that are applied to unstructured data. As described earlier, HBase is such a tool that is ideal for storing key/values in column

families. In general, the power of NoSQL data stores is that as the size of the data grows, the implemented solution can scale by simply adding additional machines to the distributed system. Four major categories of NoSQL tools and a few examples are provided next [40).

Key/value stores contain data (the value) that can be simply accessed by a given identifier (the key). As described in the MapReduce discussion, the values can be complex. In a key/va lue store, there is no stored

structure of how to use the data; the client that reads and writes to a key/value store needs to maintain and utilize the logic of how to meaningfully extract the useful elements from the key and the value. Here

are some uses for key/va lue stores:

• Using a customer's login ID as the key, the va lue contains the customer's preferences.

• Using a web session ID as the key, the value contains everything that was captured during the session.

Document stores are useful when the value of the key/value pair is a file and the file itself is self-

describing (for example, JSON or XML). The underlying structure of the documents can be used to query and customize the display of the documents' content. Because the document is self-describing, the docu- ment store can provide additional functionality over a key/value store. For example, a document store may

provide the ability to create indexes to speed the searching of the documents. Otherwise, every document

in the data store would have to be examined. Document stores may be useful for the following:

• Content management of web pages

• Web analytics of stored log data

Column family stores are useful for sparse datasets, records with thousands of columns but only

a few columns have entries. The key/value concept still applies, but in this case a key is associated with a collection of columns. In this collection, related columns are grouped into column families. For example, columns for age, gender, income, and education may be grouped into a demographic family. Column family

data stores are useful in the following instances:

• To store and render blog entries, tags, and viewers' feedback

• To store and update various web page metrics and counters

Graph databases are intended for use cases such as networks, where there are items (people or web page links) and relationships between these items. While it is possible to store graphs such as trees in a relational database, it often becomes cumbersome to navigate, scale, and add new relationships. Graph databases help to overcome these possible obstacles and can be optimized to quickly traverse a graph (move from one item in the network to another item in the network). Following are examples of graph database implementations:

• Socia l networks such as Facebook and Linkedln

• Geospatial applications such as delivery and traffic systems to optimize the time to reach one or more dest inations

Summary

Table 10-2 provides a few examples of NoSQL data stores. As is often the case, the choice of a specific data store should be made based on the functional and performance requirements. A particular data store

may provide exceptional functionality in one aspect, but that functionality may come at a loss of other functionality or performance.

TABLE 10 2 Examples of NoSQL Data Stores

Category Data Store Website

Key/Value Red is redis.io

Voldemort www.project-voldemort .com/voldemort

Document Couch DB couchdb.apache . org

Mongo DB www.mongodb.org

Column family Cassandra cassandra.apache.org

HBase hbase.apache.org/

Graph FlockDB github.com/twitter/flockdb

Neo4j www.neo4 j . org

Summary This chapter examined the MapReduce paradigm and its application in Big Data analytics. Specifically, it examined the implementation of MapReduce in Apache Hadoop. The power of MapReduce is realized with the use of the Hadoop Distributed File System (HDFS) to store data in a distributed system. The abil ity

to run a MapReduce job on the data stored across a cluster of machines enables the parallel processing of petabytes or exabytes of data. Furthermore, by adding additional machines to the cluster, Hadoop can scale as the data volumes grow.

This chapter examined several Apache projects within the Hadoop ecosystem. By providing a higher- level programming language, Apache Pig and Hive simplify the code development by masking the under-

lying MapReduce logic to perform common data processing tasks such as fi ltering, joining data sets, and restructuring data. Once the data is properly conditioned within the Hadoop cluster, Apache Mahout can be used to conduct data analyses such as clustering, classification, and collaborative filtering.

The strength of MapReduce in Apache Hadoop and the so far mentioned projects in the Hadoop eco- system are in batch processing environments. When real-time processing, including read and writes, are required, Apache HBase is an option. HBase uses HDFS to store large volumes of data across the cluster, but it also maintains recent changes within memory to ensure the real-time avai labil ity of the latest data.

Whereas MapReduce in Hadoop, Pig, and Hive are more general-purpose tools that can address a wide range of tasks, HBase is a somewhat more purpose-specific tool. Data will be retrieved from and written to the HBase in a well-understood manner.

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

HBase is one example of the NoSQL (Not only Structured Query Language) data stores that are being developed to address specific Big Data use cases. Maintaining and traversing social network graphs are

examples of relational databases not being the best choice as a data store. However, relational databases and SQL remain powerful and common tools and will be examined in more detail in Chapter 11 .

Exercises 1. Research and document additional use cases and actual implementations for Hadoop.

2. Compare and contrast Hadoop, Pig, Hive, and HBase. List strengths and weaknesses of each tool set. Research and summarize three published use cases for each tool set.

Exercises 3 through 5 require some programming background and a working Hadoop environment. The text of the novel War and Peace can be downloaded from http: I I o n l i nebooks . 1 ibrary . upe nn . edu/ and used as the dataset for these exercises. However, other data sets

can easily be substituted. Document all processing steps applied to the data.

3. Use MapReduce in Hadoop to perform a word count on the specified dataset.

4. Use Pig to perform a word count on the specified dataset.

5. Use Hive to perform a word count on the specified dataset.

Bibliography [1) Apache, "Apache Hadoop," [Online]. Avai lable: http: I / ha doop. apache. org/ . [Accessed 8

May 2014).

[2) Wikipedia, "IBM Watson," [Online). Ava ilable: h ttp : I I en . wikipedia . org / wik i I IBM_ Watson. [Accessed 11 Februry 2014).

[3] D. Davidian, "IBM.com," 14 February 2011. [Online]. Available: https : I / www-304 . ibm. com/ connect i o n s / b l og s / davidian/ tag s / hadoop?lang=en_u s. (Accessed 11 February 2014].

(4] IBM, "IBM.com," [Online). Available: http: I / www- 03. i bm. com/ inno vation/ u s / wa t son / wa t son_in_heal thcare . s h t ml. [Accessed 11 February 2014].

[5] Linked in, "Linkedln," [Onl ine]. Available: http : I / www . linkedin. c om/ about -us. [Accessed 11 February 2014].

(6] Linked In, "Hadoop," [Online]. Avai lable: ht t p : I I data . linkedi n . c om/ projects/ ha d oop. [Accessed 11 February 2014].

(7] S. Singh, "http://developer.yahoo.com/," [Online). Available: h ttp: I / developer . yahoo. com/ blogs / ha doop/apache-hbase- y a hoo-multi-tena n cy- h elm- a gain - 1717104 22 . html. [Accessed 11 February 2014].

Bibliography

[8] E. Baldeschwieler, "http://www.slideshare.net," [Online). Available: h ttp : I /www . slideshare . net/ydn / hadoop-yahoo-internet-scale-data-processing. [Accessed 11 February 2014).

[9) J. Dean and S. Ghemawat, "MapReduce: Simplified Data Processing on Large Clusters," [Online]. Avai lable: http : I /research. google . com/arc hi ve/mapreduce . html. [Accessed 11 February 2014).

[10] D. Gottfrid, "Self-Service, Prorated Supercomputing Fun!," 01 November 2007. [Online]. Available: http: //open.blogs .nytimes . com/2007/11/0l/self- service- prorated-super-computing- fun/ . [Accessed 11 February 2014).

[11] "apache.org," [Online). Available: http: I /www . apache . org/. [Accessed 11 February 2014).

[12] S. Ghemawat, H. Gobioff, and S.-T. Leung, "The Google File System," [Online). Available: ht tp: I I static . googleusercontent . com/media/research . google . com/en / us / archi ve / gf s- sosp2003 . pdf. [Accessed 11 February 2014).

[13) D. Cutting, "Free Search: Rambilings About Lucene, Nutch, Hadoop and Other Stuff," [Online). Available: http : I I cutting . wordpress . com. [Accessed 11 February 2014).

[14] "Hadoop Wiki Disk Setup," [Online]. Available: http : I / wiki. apache . org/ hadoop/ DiskSetup. [Accessed 20 February 2014].

[15] "wiki.apache.org/hadoop," [Online]. Available: http: I / wiki. apache . o r g/hadoop/ NameNode. [Accessed 11 February 2014].

[16] "HDFS High Availability," [Online]. Available: http : I /hadoop. apache . org/ docs / current/hadoop-yarn/ hadoop-yarn-site/ HDFSHighAvailabil ityWi thNFS . html. [Accessed 8 May 2014].

[17] Eclipse. [Online]. Available: https: I / www . ecl ipse. erg/downloads / . [Accessed 27 February 2014].

[18] Apache, "Hadoop Streaming," [Online]. Available: ht tps : I / wiki. apache . org/hadoop/ HadoopStreaming. [Accessed 8 May 2014).

[19] "Hadoop Pipes," [Online]. Available: http: I / hadoop . apache . org/docs / rl . 2 . 1 / a pi / org/ apache/hadoop/mapred/pipes/package- summary. html. [Accessed 19 February 2014].

[20] "HDFS Design," [Online]. Available: http: I / hadoop . apach e . erg/docs/ stablel / hdf s _design . html. [Accessed 19 February 2014].

[21] "BSP Tutorial," [Online]. Available: http : I /hama . apache . org/hama _ bsp _tutorial . h tml. [Accessed 20 February 2014).

[22] "Hama," [Online]. Available: h ttp : I / hama . apache . org/ . [Accessed 20 February 2014].

[23] "PoweredByYarn," [Online]. Available: http : I / wiki . apache . org /hadoop/ PoweredByYarn. [Accessed 20 February 2014).

[24] "pig.apache.org," [Online]. Available: http: I / pig . apache. org/ .

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: MAPREDUCE AND HADOOP

[25] "Pig," [Online). Available: http : I /pig . apache. org/ . [Accessed 11 Feb 2014).

[26] "Piggybank," [Online]. Available: https: I / cwiki . apache . erg/ confluence/ display / PIG/ PiggyBank. [Accessed 28 February 2014].

[27] F. Chang, J. Dean, S. Ghemawat, W.C. Hsieh, D.A. Wallach, M. Burrows, T. Chandra, A. Fikes, and R.E. Gruber Fay Chang, "Big table: A Distributed Storage System for Structured Data," [Online). Available: http : I / research . google . com/archi ve/bigtable . html. [Accessed 11 February 2014).

[28] K. Muthukkaruppan, "The Underlying Technology of Messages," 15 November 2010. [Online). Available: http : I / www. facebook. com/notes/ facebook-engineering / the-underlying-technology-of -me ssages / 4 54991608919. [Accessed 11 February 2014).

[29] "HBase Key Value," [Online]. Available: http : I / hbase. apache. erg/ book/ regions . arch . html. [Accessed 28 February 2014].

[30] "Number of Column Families," [Online]. Ava ilable: http : I /hbase . apache . org / book/ number . o f . cfs .html.

[31] "HBase Regionserver," [Online]. Available: http: I / hbase . apache . org/ book/ regionserver . arch . html. [Accessed 3 March 2014].

[32] "Netcraft," [Online]. Available: http : I /news . netcraft . com/archives / 2014 /0 2/ 03/ february- 2014 -web- server- survey . html. [Accessed 21 February 2014].

[33] K. Muthukkaruppan, "The Underlying Technology of Messages," 15 November 2010. [Online]. Avai lable: http : I /www . facebook . com/notes/facebook-engineering/ the-underlying - technology-of -messages/ 454 991608919. [Accessed 201 1 February 2014].

[34] N. Spiegelberg. [Online]. Available: http : I / www. slide share . net / brizzzdotcom/ facebook-messages - hbase. [Accessed 11 February 2014].

[35] "HBase Rowkey," [Online]. Available: http : I / hbase . apache . org/ book/ rowkey . design . html. [Accessed 4 March 2014].

[36] "Zookeeper," [Online]. Available: http : I / zookeeper . apache . org/ . [Accessed 11 Feb 2014].

[37] "Zookeeper," [Online]. Available: http : I / hbase . apache. org/ book/ zookeeper . html. [Accessed 21 February 2014].

[38] "Mahout," [Online]. Available: http : I / mahout . apache . org / users / basics/ algorithms . html. [Accessed 19 February 2014].

[39] "Pivotal HD," [Online]. Available: http : I / www . gopi votal . com/ big-data / pivotal- hd. [Accessed 8 May 2014].

[40] P. J. Sadalage and M. Fowler, NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot, Upper Saddle River, NJ: Addison Wesley, 2013.

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

In-database analytics is a broad term that describes the processing of data within its repository. In many of the earlier R examples, data was extracted from a data source and loaded into R. One advantage of in-database analytics is that the need for movement of the data into an analytic tool is eliminated. Also, by

performing the analysis within the database, it is possible to obtain almost real-time results. Applications of in-database analytics include credit card transaction fraud detection, product recommendations, and web advertisement selection tailored for a particular user.

A popular open-source database is PostgreSQL. This name references an important in-database analytic

language known as Structured Query Language (SQL). This chapter examines basic as well as advanced topics in SQL. The provided examples of SQL code were tested against Green plum database 4.1.1.1, which is based on PostgreSQL 8.2.15. However, the presented concepts are applicable to other SQL environments.

11.1 SQL Essentials A relational database, part of a Relational Database Management System (RDBMS}, organizes data in tables with established relationships between the tables. Figure 11-1 shows the relationships between five tables

used to store details about orders placed at an e-commerce retailer.

orders oorder_id 0 product_id 0 customer _id 0 item_shipment_status_code 0 order _datetime 0 ship_datetime 0 payment_method_code 0 tax_amount 0 item_quantity 0 item _price 0 ordering_session_id owebsite uri

FIGURE 11-1 Relationship diagram

oro duct cat e or ~-II 0 product_id

0 category _id ~-II o ca o ca

tegory _id tegory _name -- Oprice 0 product name

l= \_.customer

0 customer _id

= 0 first_name o last_name 0 email address

customer demoaraohics 4 0 customer _id

Deity 0 state_code ocountry 0 customer _gender 0 customer _age 0 frequent_shopper _class 0 tenure_with_company _in_years O parent 0 multiple_kids 0 student 0 innovation_adapter _category 0 fashion buyino cateoory

11.1 SQL Essentials

The table orders contains records for each order transaction. Each record contains data elements such as the product_id ordered, the customer_id for the customer who placed the order, the order_ da tetime, and so on. The other four tables provide additional details about the ordered items and the customer. The lines between the tables in Figure 11-1 illustrate the relationships between the tables. For example, a customer's first name, last name, and gender from the customer table can be associated with an orders record based on equality of the customer_id in these two tables.

Although it is possible to build one large table to hold all the order and customer details, the use of five tables has its advantages. The first advantage is disk storage savings. Instead of storing the product name, which can be several hundred characters in length, in the orders table, a much shorter product_ id, of perhaps a few bytes, can be used and stored in place of the product's name.

Another advantage is that changes and corrections are easily made. In this example, the table cat egoryis used to categorize each product. If it is discovered that an incorrect category was assigned to a particular product item, only the category_idin the product table needs to be updated. Without the product and category tables, it may be necessary to update hundreds of thousands of records in the orders table.

A third advantage is that products can be added to the database prior to any orders being placed. Similarly, new categories can be created in anticipation of entirely new product lines being added to the online retailer's offerings later.

In a relational database design, the preference is not to duplicate pieces of data such as the customer's name across multiple records. The process of reducing such duplication is known as normalization. It is important to recognize that a database that is designed to process transactions may not necessarily be optimally designed for analytical purposes. Transactional databases are often optimized to handle the insertion of new records or updates to existing records, but not optimally tuned to perform ad-hoc query- ing. Therefore, in designing analytical data warehouses, it is common to combine several of the tables and create one larger table, even though some pieces of data may be duplicated.

Regardless of a database's purpose, SQL is typically used to query the contents of the relational data- base tables as well as to insert, update, and delete data. A basic SQL query against the customer table may look like this.

SELECT first_name, last_name

FROM customer WHERE customer_id = 666730

first name last name Mason Hu

This query returns the customer information for the customer with a customer_ i d of 666730. This SQL query consists of three key parts:

o SELECT: Specifies the table columns to be displayed

o FROM: Specifies the name of the table to be queried

o WHERE: Specifies the criterion or filter to be applied

ADVANCED ANALYTICS-TECHNOLOGV AND TOOLS: IN-DATABASE ANALYTICS

In a relational database, it is often necessary to access related data from multiple tables at once. To accomplish this task, the SQL query uses JOIN statements to specify the relationships between the mul- tiple tables.

11.1.1 Joins Joins enable a database user to appropriately select columns from two or more tables. Based on the rela- tionship diagram in Figure 11-1, the following SQL query provides an example of the most common type of join: an inner join.

SELECT c.customer_id, o.order_id, o.product_id, o.item_quantity AS qty

FROM orders o INNER JOIN customer c

ON o.customer_id ; c.customer_id WHERE c.first_name = 'Mason'

AND c.last_name = 'Hu'

customer id order id product_ id 666730 51965-1172-6384-6923 33611

666730 79487-2349-4233-6891 34098

666730 39489-4031-0789-6076 33928

666730 29892-1218-2722-3191 33625

666730 07751-7728-7969-3140 34140

666730 85394-8022-6681-4716 33571

qty 5

4

1

This query returns details of the orders placed by customer Mason Hu. The SQL query joins the two tables in the FROM clause based on the equality of the customer_id values. In this query, the specific customer_ i d value for Mason Hu does not need to be known by the programmer; only the customer's full name needs to be known.

Some additional functionality beyond the use of the INNER JOIN is introduced in this SQL query. Aliases o and care assigned to tables orders and customer, respectively. Aliases are used in place of the full table names to improve the readability of the query. By design, the column names specified in the SELECT clause are also provided in the output. However, the outputted column name can be modified with the AS keyword.ln the SQL query, the values of it em_ quantity are displayed, butthis outputted column is now called qty.

The INNER JOIN returns those rows from the two tables where the ON criterion is met. From the earlier query on the customer table, there is only one row in the table for customer Mason Hu. Because the corresponding customer_id for Mason Hu appears six times in the orders table, the INNER JOIN query returns six records. If the WHERE clause was not included, the query would have returned millions of rows for all the orders that had a matching customer.

Suppose an analyst wants to know which customers have created an online account but have not yet placed an order. The next query uses a RIGHT OUTER JOIN to identify the first five

11.1 SQL Essentials

customers, alphabetically, who have not placed an order. The sorting of the records is accomplished with the ORDER BY clause.

SELECT c.customer_id, c.first_name, c.last_name, o.order_id

FROM orders o RIGHT OUTER JOIN customer c

ON o.customer_id c.customer_id WHERE o.order_id IS NULL ORDER BY c.last_name,

c.first name LIMIT 5

customer id first nane last name order id - - -

143915 Abigail Aaron 965886 Audrey· Aaron 9820~2 Cartel· Aaro::

125302 Daniel .::..aror: 103964 Emily .::..arcr:

In the SQL query, a RIGHT OUTER JOIN is used to specify that all rows from the table customer, on the right-hand side {RHS) of the join, should be returned, regardless of whether there is a matching customer_id in the orders table. In this query, the WHERE clause restricts the results to only those joined customer records where there is no matching order_ i d. NULL is a special SQL keyword that denotes an unknown value. Without the WHERE clause, the output also would have included all the records that had a matching customer_id in the orders table, as seen in the following SQL query.

SELECT c.customer_id, c.first_name, c.last_narne, o.order_id

FROM orders o RIGHT OUTER JOIN customer c

ON o.customer_id c.customer_id ORDER BY c.last_name,

c.first name LIMIT 5

customer id firs: name :L43915

222599

222599

222599

222599

.=..b:gail

.i:>.cidison

.::..ddison

Addison

P1ddison

las: Eame

SOJ:~-7~76-3355-6960

2:C07-75~l-l255-353l

Aaro:1 Aaron 69225-1638-2944-0264

ADVANCED ANALYTIC$-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTIC$

In the query results, the first customer, Abigail Aaron, had not placed an order, but the next customer, Addison Aaron, has placed at least four orders.

There are several other types of join statements. The LEFT OUTER JOIN performs the same functionality as the RIGHT OUTER JOIN except that all records from the table on the left-hand side (LHS) of the join are considered. A FULL OUTER JOIN includes all records from both tables regardless of whether there is a matching record in the other table. A CROSS JOIN combines two tables by matching every row of the first table with every row of the second table. If the two tables have 100 and 1,000 rows, respectively, then the resulting CROSS JOIN of these tables will have 100,000 rows.

The actual records returned from any join operation depend on the criteria stated in the WHERE clause. Thus, careful consideration needs to be taken in using a WHERE clause, especially with outer joins. Otherwise, the intended use of the outer join may be undone.

11.1.2 Set Operations SQL provides the ability to perform set operations, such as unions and intersections, on rows of data. For example, suppose all the records in the orders table are split into two tables. The orders_ arch table, short for orders archived, contains the orders entered prior to January 2013. The orders transacted in or after January 2013 are stored in the orders_recent table. However, all the orders for product_id 33611 are required for an analysis. One approach would be to write and run two separate queries against the two tables. The results from the two queries could then be merged later into a separate file or table. Alternatively, one query could be written using the UNION ALL operator as follows:

SELECT customer_id, order_id, order_datetime, product_id, item_quantity AS qty

FROM orders_arch WHERE product_id = 33611 UNION ALL SELECT customer_id,

order_id, order_datetirne, product_id, itern_quantity AS qty

FROM orders_recent WHERE product_id ~ 33611 ORDER BY order_datetime

customer id order id - - 643126 13501-6446-6326-0182

725940 70733-4014-1618-2531

7-!2448 03107-1712-8668-9967

order - datetime product_ id qty

2005-01-02 19:28:08 33611 1

2005-01-08 06:16:31 33611

2005-Dl-08 16:11:39 33611

6408..;7

660446

647335

736:9-Cl27-0657-7~16 2013-01-05 14:53:27 33611

55160-7129 2408-9181 2013-01-07 83:59:36 33Gl1

75014-7339-1214-6447 2013-Cl-27 13:02:10 33611

11.1 SQL Essentials

l

The first three records from each table are shown in the output. Because the resulting records from both tables are appended together in the output, it is important that the columns are specified in the same order and that the data types of the columns are compatible. UNION ALL merges the results of the two SELECT statements regardless of any duplicate records appearing in both SELECT statements. If only UNION was used, any duplicate records, based on all the specified columns, would be eliminated.

The INTERSECT operator determines any identical records that are returned by two SELECT state- ments. For example, if one wanted to know what items were purchased prior to 2013 as well as later, the SQL query using the INTERSECT operator would be this.

SELECT product_id FROM orders_arch INTERSECT SELECT product_id FROM orders_recent

prcduct_id

30

31

It is important to note that the intersection only returnsaproduct_id if it appears in both tables and returns exactly one instance of such a product_id. Thus, only a list of distinct product IDs is returned by the query.

To count the number of products that were ordered prior to 2013 but not after that point in time, the EXCEPT operator can be used to exclude the product IDs in the orders_ recent table from the product IDs in the orders_ arch table, as shown in the following SQL query.

SELECT COUNT(e.*) FROM (SELECT product_id

FROM orders_arch EXCEPT SELECT product_id FROM orders_recent) e

13569

The preceding query uses the COUNT aggregate function to determine the number of returned rows from a second SQL query that includes the EXCEPT operator. This SQL query within a query is sometimes

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

called a subquery or a nested query. Subqueries enable the construction of fairly complex queries without having to first execute the pieces, dump the rows to temporary tables, and then execute another SQL query to process those temporary tables. Subqueries can be used in place of a table within the FROM clause or can be used in the WHERE clause.

11.1.3 Grouping Extensions Previously, the COUNT ( ) aggregate function was used to count the number of returned rows from a query. Such aggregate functions often summarize a dataset after applying some grouping operation to it. For example, it may be desired to know the revenue by year or shipments per week. The following SQL query uses the SUM ( ) aggregate function along with the GROUP BY operator to provide the top three ordered items based on i t em_ quantity.

SELECT i.product_id, SUM(i.item_quantity) AS total

FROM orders_recent i GROUP BY i.product_id ORDER BY SUM(i.item_quantity) DESC LIMIT 3

1506~

15060

GROUP BY can use the ROLL UP () operator to calculate subtotals and grand totals. The following SQL query employs the previous query as a subquery in the WHERE clause to supply the number of items ordered by year for the top three items ordered overall. The ROLLUP operator provides the subtotals, which match the previous output for each product_ i d, as well as the grand total.

SELECT r.product_id,

FROM WHERE

GROUP ORDER

DATE_PART('year', r.order_datetime) AS year, SUM(r.item_quantity) AS total orders_recent r r.product_id IN (SELECT o.product_id

FROM orders_recent o GROUP BY o.product_id ORDER BY SUM(o.item_quantity) DESC LIMIT 3)

BY ROLLUP( r.product_id, DATE_PART('year', r.order_datetime) BY r.product_id,

DATE_PART('year', r.order_datetime)

product_ id year total

15060 2013 5996

15060 2014 57

15060 6053

15066 2013 6030

15066

15066

15072

15072

15072

2014

2013

2014

11.1 SQL Essentials

52

6082

6023

66

6089

18224

The CUBE operator expands on the functionality of the ROLL UP operator by providing subtotals for each column specified in the CUBE statement. Modifying the prior query by replacing the ROLL UP opera- tor with the CUBE operator results in the same output with the addition of the subtotals for each year.

SELECT r.product_id, DATE_PART( 1year 1 , r.order_datetime) AS year, SUM(r.item_quantity) AS total

FROM orders_recent r WHERE r.product_id IN (SELECT o.product_id

FROM orders_recent o GROUP BY o.product_id ORDER BY SUM(o.item_quantity) DESC LIMIT 3)

GROUP BY CUBE( r.product_id, DATE_ PART ( 1 year 1 , r.order_datetime) ORDER BY r.product_id,

DATE_ PART ( 'year 1 , r.order_datetime

product_id year total 15060 2013 5996

15060 2014 57

15060 6053

15066 2013 6030

15066 2014 52

15066 6082

15072 2013 6023

15072 2014 66

15072 6089

2013 :8049 .... additional row 2014 :75 .,... additional row

:8224

Because null values in the output indicate the subtotal and grand total rows, care must be taken when null values appear in the columns being grouped. For example, null values may be part of the dataset being analyzed. The GROUPING ( ) function can identify which rows with null values are used for the subtotals or grand totals.

SELECT r.product_id, DATE_PART( 1year 1 , r.order_datetime) SUM(r.item_quantity)

AS year, AS total,

GROUPING(r.product_id) AS group_id, GROUPING(DATE_PART( 1 year 1 , r.order_datetime)) AS group_year

FROM orders_recent r

ADVANCED ANALVTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

WHERE r.product_id IN (SELECT o.product_id FROM orders_recent o GROUP BY o.product_id ORDER BY SUM(o.item_quantity) DESC LIMIT 3)

GROUP BY CUBE( r.product_id, DATE_PART('year', r.order_datetime) ORDER BY r.product_id,

DATE_PART('year', r.order_datetime)

product id year total group_id group_year 15060 2013 5996 0 0

15060 2014 57 0 0

15060 6053 0 1

15066 2013 6030 0 0

15066 2014 52 0 0

15066 6082 0 1

15072 2013 6023 0 0

15072 2014 66 0 0

15072 6089 0 1

2013 1804 9 1 0

2014 175 1 0

18224 1 1

In the preceding query, group _year is set to 1 when a total is calculated across the values of year. Similarly, group_id is set to 1 when a total is calculated across the values of product_id.

The functionality of ROLL UP and CUBE can be customized via GROUPING SETS. The SQL query using the CUBE operator can be replaced with the following query that employs GROUPING SETS to provide the same results.

SELECT r.product_id, DATE_PART('year', r.order_datetime) AS year, SUM(r.item_quantity) AS total

FROM orders_recent r WHERE r.product_id IN (SELECT o.product_id

FROM orders_recent o GROUP BY o.product_id ORDER BY SUM(o.item_quantity) DESC LIMIT 3)

GROUP BY GROUPING SETS( ( r.product_id,

ORDER BY r.product_id,

DATE_PART('year', r.order_datetime) ), r .product_id ) , DATE_PART('year•, r.order_datetime) ),

( ) )

DATE_PART('year', r.order_datetime)

11.1 SQL Essentials

The listed grouping sets define the columns for which subtotals will be provided. The last grouping set, } , specifies that the overall total is supplied in the query results. For example, if only the grand total was

desired, the following SQL query using GROUPING SETS could be used.

SELECT r.product_id, DATE_PART('year', r.order_datetime) AS year, SUM(r.item_quantity) AS total

FROM orders_recent r WHERE r.product_id IN (SELECT o.product_id

FROM orders_recent o GROUP BY o.product_id ORDER BY SUM(o.item_quantity) DESC LIMIT 3)

GROUP BY GROUPING SETS( ( r.product_id, DATE_PART('year•, r.order_datetime) ) ,

( ) )

ORDER BY r.product_id, DATE_PART('year', r.order_datetime)

product_id year total 15060 2013 5996

15060 2014 57

15066 2013 6030

15066 2014 52

15072 2013 6023

15072 2014 66

18224

Because the GROUP BY clause can contain multiple CUBE, ROLL UP, or column specifications, dupli- cate grouping sets might occur. The GROUP_ ID ( ) function identifies the unique rows with a 0 and the redundant rows with a 1, 2, .... To illustrate the function GROUP_ ID (}, both ROLLUP and CUBE are used when only one specific product_id is being examined.

SELECT r.product_id, DATE_PART('year', r.order_datetime) AS year, SUM(r.item_quantity) AS total, GROUP_ID() AS group_id

FROM orders_recent r WHERE r.product_id IN ( 15060 ) GROUP BY ROLLUP( r.product_id, DATE_PART('year', r.order_datetime) ),

CUBE( r.product_id, DATE_PART('year', r.order_datetime) ) ORDER BY r.product_id,

DATE_PART('year', r.order_datetime), GROUP_ID()

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

prod~1cc 1d year tot.al group_ ict 15060 2013 5996 0

15060 2013 5996 1

15060 :!OU 5996 3

15060 2011 5996 ~

15060 2013 5996 ')

15060 ~013 5996 6

!5060 201·l 57 0

1'>060 ~01·; 57

15060 201<1 57 2

15060 2014 57

15060 201·1 57 ·l

15060 2014 57 5

15060 .. 014 57 6

15060 6053

:5060 6053 1

15060 6053 ~

-01 · 5996

2014 57 0

6053 n

Filtering on the group_ i d values equal to zero yields unique records. This filtering can be accom- pl ished with the HAVING clause, as illustrated in the next SQL query.

SELECT r .product_id, DATE_PART('year ' , r .order_datetime) AS year, SUM(r . item_quantity) AS total, GROUP_ ID() AS group_id

FROM orders_recent r WHERE r.product_id IN ( 15060 ) GROUP BY ROLLUP( r.product_id , DATE_PART( ' year ' , r.order_datetime) ) ,

CUBE( r .product_id, DATE_PART('year', r .order_datetime) ) HAVING GROUP_ID() = 0 ORDER BY r.product_id,

produc-: ld 15060

15060

15060

DATE_PART ( ' year', r .order_datetime) , GROUP_ID()

i'E:"t."ll total 91:"0U! ld 2013 5996 0

201-l 57 0

6053 0

::ou 5996 0 201-l 57 0

6053 0

11.2 In-Database Text Analysis SQL offers several basic text string functions as well as wildcard search functionality. Related S ELECT

statements and their results enclosed in the SQL comment delimiters, I ** 1. include the following:

1 1 .2 1n-Database Text Analysis

SELECT SUBSTRING( ' 1234567890', 3 ' 2) /* r·etm:ns I 34 I ' / SELECT ' 12345678 90 ' LIKE ' %7% ' / * returns Tnlf> • ! SELECT ' 1234567890' LIKE ' 7%' / * returns False • f SELECT '1234567890 ' LIKE ' - 2% ' / • re::urns True SELECT '1234567890 ' LIKE ' 3\ ' . re:.t:rr:s Fal.:·~ . SELECT '1234567890 ' LIKE I 3\ ' . re:.:.::r:;;,::- .,.. ... .J. -

This section examines more dynamic and flexible tools for text analysis, called regular expressions, and

their use in SQL queries to perform pattern matching. Table 11 -1 includes several forms of the comparison

operator used with regular expressions and related SQL examples that produce a True result.

TABLE 11 • 1 Regular Expression Operators

Operator Description Example

Contains the regular expression (case '123a567 ' - 'a ' sensitive)

-* Contains the regular expression (case '123a567' - * 'A' insensitive)

!- Does not contain the regular expression ' 1 23a567 ' ! - ' A '

(case sensitive)

!-* Does not contain the regular expression ' 123a567' ! - * 'b '

(case insensitive)

More complex forms of the patterns that are specifi ed at the RHS of the comparison operator can be

constructed by using the elements in Table 11 -2.

TABLE 11 ·2 Regular Expression Elements

Element Description

Matches item a orb (alb)

Looks for matches at the beginning of the string

$ Looks for matches at the end ofthe string

Matches any sing le character

* Matches preceding item zero or more times

+ Matches preceding item one or more times

? Makes the preceding item optional

{n } Matches the preceding item exactly n times

(continues)

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

TABLE 11 2 Regular Expression Elements (Continued)

Elem ent Description

( ) Matches the contents exactly

f I Matches any of the characters in the content, such as [0- 9]

\\x Matches a nonalphanumeric character named x

\\y Matches an escape string \y

To illustrate the use of these elements, the following S ELECT statements include examples in which

the comparisons are Tr ue or False.

• m :t ~ h( .,. ..... ,.- , . ':·: :·' •

SELECT SELECT

' 123a567' ' 23 lb'

'123a567' - ' 32 lb'

• re~u:ns Tru • r-eturns FAJ.!ie •

• mat hF thE> beginn~:1g SELECT '123a567' - ' A12 3a' SELECT '123a567' - ' Al 23a7'

tho string * /

. . I'" .. ::d o: :.~· "" r1ng SELECT ' 123a567 ' - ' a 56 7$ ' SELECT ' 123a567 ' - ' 27$'

! • matches a ny sing le chal~CLPl SELECT ' 123a 567 ' - I 2 • a I SELECT ' 123a567 ' '2 .. 5 ' SELECT ' 123a567 ' '2 .. . 5 '

SELECT ' 123a567' - ' 2 * ' SELECT '123a567' - ' 2 *a' SELECT '123a 567' - ' 7 *a ' SELECT '123a567' - ' 37* ' SELECT ' 123a567' ' 87*'

ed:.::g c .. ~ ... H:: ..

SELECT '123a567' - ' 2+ ' SELECT ' 123a567 ' '2+a' SELECT ' 123a567' - '7+a ' SELECT ' 123a567 ' - '37+ ' SELECT ' 123a56 7 ' - ' 87 +'

• m 1kF- Lh< !- .·<eced~ :1g ~t.at ac ~ t SELECT ' 123a567 ' - ' 2? '

• re~urr..s True * :-ettn!'ls F' 1l~e

. returns True . returns False * I ! • rt:!tu r ns Tnltc

re:.."1rns True re~t:r::s Ftt:~e

~ re::urr.s True t • re~urns True

• !

• I

/ ' returns T1ue • / • returns T1ue • / • re::u::ns Fals

nc or mere ·:mes

ret:.urns Fnlr-e ! • returns False • f f • returns Fal~e • / ! • returns Falne •/

!Jtlonal • • rett4::::s Tru.e.

11.21n-Database Text Analysis

SELECT 1123a567 1 - 12?a 1 I* returns True *I SELECT 1123a567 1 - 17?a 1 I* returns True *I SELECT 1123a567 1 - 137? 1 /* returns True */ SELECT 1123a567 1 - 187? 1 /* returns False *I

I* Matches the preceding item exactly {n} times */

SELECT 1123a567 1 - I 5 { 0} I I* returns True *I SELECT 1123a567 1 - 15{1} 1 /* returns True *I SELECT 1123a567 1 - I 5 {2} I /* returns False *I SELECT 11235567 1 - I 5 {2} I /* returns True */ SELECT 1l23a567 1 - 18{0} 1 /* returns True *I SELECT 1l23a567 1 - 18{1} 1 /* retut·ns False *I

I* Matches the contents exactly *I SELECT 1123a567 1 - I (23a5) I I* returns True *I SELECT 1123a567 1 - I (1Ja5) I I* returns False *I SELECT 1l23a567 1 - 1 (23a5)7* 1 /* returns True *I SELECT 1l23a567 1 - I (2Ja5) 7+ I /* returns False *I

I* Matches any of the contents *I SELECT 1123a567 1 - I [2Ja8] I /* returns True *I SELECT 1123a567 1 - I [8aJ2] I /* returns True *I SELECT 1123a567 1 - I [ (13a5)] I I* returns True */ SELECT 1123a567 1 - 1 [xyz9] 1 /* returns False *I SELECT 1l23a567 1 - I [a-z] I I* returns True *I SELECT 1l23a567 1 - I [b-z] I /* returns False */

I* Matches a nonalphanumeric *I SELECT 1$50K+ 1 - 1\\$1 I* returns True *I SELECT 1$50K+ 1 - 1\\+1 /* returns True *I SELECT 1$50K+ 1 - 1\\$\\+1 /* returns False *I

/* Use of the backslash for escape clauses *I I* \\w denotes the characters 0-9, a-z, A-Z, or the underscore( ) *I - SELECT 1l23a567 1 - 1\\wl I* returns True *I SELECT 1l23a567+ 1 - 1\\wl I* returns True *I SELECT 1++++++++1 - 1\ \wl /* returns False *I SELECT - 1\\wl /* returns True *I SELECT 1+1 - 1\\wl I* returns False *I

Regular expressions can be developed to identify mailing addresses, e-mail addresses, phone numbers, or currency amounts. I* use of more complex regular expressions */ SELECT 1$50K+ 1 - 1\\$[0-9]*K\\+ 1 I* returns True *I SELECT 1$50K+ 1 - 1\\$[0-9]K\\+ 1 /* returns False *I SELECT 1$50M+ 1 - 1\\$[0-9]*K\\+ 1 I* returns False *I

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

SELECT 1 $50M+ 1 - 1 \\$[0-9]*(KIM)\\+ 1 /* returns True *I

/* check for ZIP code of form #####-#### */

SELECT 1 02038-2531 1 - I [0-9] {5}- [0-9] {4} I /* returns True */ SELECT 1 02038-253 1 - I [0-9] {5}- [0-9] {4} I /* returns False */ SELECT 1 02038 1 - 1 [0-9] {s}- [0-9] {4} I /* returns False */

So far, the application of regular expressions has been illustrated by including the Boolean comparison in a SELECT statement as if the result of the comparison was to be returned as a column. In practice, these comparisons are used in a SELECT statement's WHERE clause against a table column to identify specific records of interest. For example, the following SQL query identifies those ZIP codes in a table of customer addresses that do not match the form#####-####. Once the invalid ZIP codes are identified, corrections can be made by manual or automated means.

SELECT address_id, customer_id,

city, state, zip, country

FROM customer_addresses WHERE zip!- '~[0-9] {5}-[0-9] {4}$ 1

address id customer id city 7 13 SINAI 18 27 SHELL ROCK

24 37 NASHVILLE

state SD

IA TN

zip 57061-0236

S0670-0480 37228-219

country USA USA USA

SQL functions enable the use of regular expressions to extract the matching text, such as SUBSTRING ( ) , as well as update the text, such as REGEXP _REPL ().

/* extract ZIP code from text string */ SELECT SUBSTRING( 1 4321A Main Street Franklin, MA 02038-2531 1

FROM I [ 0 - 9 1 { 5 } - [ 0- 9) { 4 } I )

02038-2531

/* replace long format zip code with short format ZIP code */ SELECT REGEXP_REPLACE( 1 4321A Main Street Franklin, MA 02038-2531 1 ,

I [0-9) {5}- [0-9) {4} 1 , SUBSTRING(SUBSTRING( 1 4321A Main Street Franklin, MA 02038-2531 1

FROM I [ 0 - 9] { 5 } - [ 0 - 9] { 4 } I ) I 1, 5 ) )

4321A Main Street Franklin, MA 02038

11.3 Advanced SQL

Regular expressions provide considerable fiexibility in searching and modifying text string s. However, it

is quite easy to build a regular expression that does not work entirely as intended. For example, a particu lar

operation may work properly with a given dataset, but future data sets may contain new cases to be handled.

Thus, it is important to thoroughly test any SQL code using regular expressions.

11.3 Advanced SQL Building upon the foundat ion provided in the earlier parts of this chapter, this section presents advanced

SQL techniques that can simplify in-database analytics.

11.3.1 Window Functions In Section 11.1.3, several SQL examples using aggregate functions and grouping options to summarize

a dataset were provided. A window function enables aggregation to occur but still provides the entire

dataset with the summary results. For example, the RANK ( ) function can be used to order a set of rows

based on some attribute. Based on the SQL table, orders_ rec e n t , introduced in Section 11.1.2, the following SQL query provides a ranking of customers based on their total expenditures.

SELECT s .customer_id, s .sales , RANK ()

OVER ( ORDER BY s. sales DESC ) AS sales _rank

FROM (SELECT r .custome r_ id,

cus~cmer

683377

238107

661519

628278

619660

SUM (r.item_quant i t y * r . item_pr i ce) AS sales

FROM orders recent r GROUP BY r .customer_id) s

10 sales Sct ... eS ra:c~-:

:ne~o. )0

19983 . 65 :?

18134 . 11

17965 . 44 4

1.7944 . 20 5

The subquery in the FROM clause computes the total sa les for each customer. In the outermost SELECT clause, the sa les are ranked in descending order. Window functions, such as RANK () ,are followed by an

OVER clause that specifies how the function should be applied. Additionally, the window function can

be applied to groupings of a given dataset using the PARTITI ON BY clause. The following SQL query

provides the customer rankings based on sales within product categories.

SELECT s . category_name, s . custome r _id.

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

s.sales, RANK()

OVER ( PARTITION BY s.category_name ORDER BY s.sales DESC ) AS sales_rank

FROM (SELECT c.category_name, r.customer_id, SUM(r.item_quantity * r.item_price) AS sales

FROM orders_recent r LEFT OUTER JOIN product p

ON r.product_id = p.product_id LEFT OUTER JOIN category c

ON p.category_id = c.category_id GROUP BY c.category_name,

r.customer_id) s ORDER BY s.category_name,

sales_rank

category_name Apparel Apparel Apparel Apparel Apparel

Apparel Automotive Parts Automotive Parts Automotive Parts Automotive Parts Automotive Parts

and Accessories and Accessories and Accessories and Accessories and Accessories

customer id sales sales 596396 4899.93

319036 2799.96 2

455683 2799.96 2

468209 2700.00 4

456107 2118.00 5

430126 2.20 78731

362572 5706.48

587564 5109.12 2

377616 4279.86

443618 4279.86

590658 3668.55

rank -

In this case, the subquery determines each customer's sales in the respective product category. The outer SELECT clause then ranks the customer's sales within each category. The provided portions of the SQl query output illustrate that the ranking begins at 1 for each category and demonstrate how the rank- ings are affected by ties in the amount of sales.

A second use of windowing functions is to perform calculations over a sliding window in time. For example, moving averages can be used to smooth weekly sales figures that may exhibit large week-to-week variation, as shown in the plot in Figure 11-2.

C) C) C) C) C) <D

C) C) C) C) <D II)

C) C) C) C) N II)

0 5

FIGURE 11-2 Weekly sales for an online retailer

10

1 1 .3 Advanced SQL

15 20 25

Week

The following SQL query illustrates how moving averages can be implemented using window functions:

SELECT year, week, sales , AVG {sales )

OVER { ORDER BY year, week ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING ) AS moving_avg

FROM sal es_by_week WHERE year = 2014

AND week <= 26 ORDER BY year,

week

year \·:eet: 201·; 1

:!014 2

2014 3

2014 4

201•1 5

2014 6

2014 7

2014 8

2014 9

sales :sG-1539

1572128

!582~ 11

1600769

1580146

1588798

15631 42

1563043

1524749

rno' .. :i::.g_a·.-g

157-999 . 333

15791-ll . 75

157998~ . 6

158-;s3.; . 4

1583037 . :!

1579179 . 6

1563975 . 6

1553665

154753 4. 8

-a··-=r::i:J<.::: .,. ~.' . ' (-a·;erag_:. A ' ...... k· 1' 3, ~a··erag.=> vf ·.·: . \:!"' ...

-t--a·/erag of ·,:f-·•_l:·:n 3, .,, ,._a·Jeraae [ \'.'r~ t-' f..~· l, ·1, s'

~. 5

5, 6 6, 7

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

201 4 10 1528593 15 ~8051 . 6

2014 11 1558147 1545714 . 2

2014 12 1565726 15 49404

201 4 13 1551356 15 ·:881:! . 6

2014 1·· 1543198 :5.; 39:'0. :-

201 4 15 15-5636 1~36767.6

201~ 16 153 3185 :53166-.~

20 14 17 1530463 1527313 . 6

2014 18 1525829 :529787.9

20 14 19 15-1455 1~32649

20 14 20 1513007 1533370

2014 21 1552491 1512116

2014 22 1534069 1539713.6

2014 2l 1519559 1538199.6

2014 24 1559442 1539086.2 •-il':· rage of .... ·ee::s 2:!,23,24,25,2€ :!01-i 25 1525.;17 l540340.75 -average of .,..·eef:s 2J,2-i,25,26 2- 1.; :' 1 ~ fO_:?.; : ~ . R • '':e1·age of wee~:s :! ·1, :c:, .~G

The windowing function uses the built-in aggregate function AVG ( ) , which computes the arithmetic average of a set of values. The ORDER BY clause sorts the records in chronological order and specifies

which rows should be included in the averaging process with the current row. In this SQL query, the mov- ing average is based on the current row, the preceding two rows, and the following two rows. Because

the dataset does not include the last two weeks of 2013, the first moving average value of 1,572,999.333 is the average of the first three weeks of 2014: the current week and the two subsequent weeks. The moving average value for the second week, 1,579,941.75, is the sales value for week 2 averaged with the prior week

and the two subsequent weeks. For weeks 3 through 24, the moving average is based on the sa les from 5-week periods, centered on the current week. At week 25, the window begins to include fewer weeks because the following weeks are unavailable. Figure 11-3 illustrates the applied smoothing process against

the weekly sales figures.

0 0 0 0 0 <0

8 8 <0 I()

0

8 0 N I()

0 5

FIGURE 11-3 Weekly sales with moving averages

10 15 20 25

Week

11.3 Advanced SQL

Built-in window functions may vary by SQL implementation. Table 11-3 [1] from the PostgreSQL docu- mentation includes the list of general-purpose window functions.

TABLE 11-3 Window Functions

Function Description

row_number ()

rank()

dense_ rank ()

percent_ rank ()

cume_dist ()

ntile(num_buckets integer}

lag (value any [, offset integer [, default any ] ] )

lead(value any [, offset integer [, default any ] ] )

first_value(value any)

last_value(value any)

nth_value(value any, nth integer)

Number ofthe current row within its partition, counting from 1.

Rank ofthe current row with gaps; same as row _number of its first peer.

Rank of the current row without gaps; this function counts peer groups.

Relative rank of the current row: (rank- 1) I (total rows -1).

Relative rank of the current row: (number of rows preceding or peer with current row) I (total rows).

Integer ranging from 1 to the argument value, dividing the partition as equally as possible.

Returns the value evaluated at the row that is offset rows before the current row within the partition; if there is no such row, instead return default. Both offset and default are evaluated with respect to the current row.lf omitted, offset defaults to 1 and default to null.

Returns the value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead return default. Both offset and default are evaluated with respect to the cur- rent row.lf omitted, the offset defaults to 1 and the default to null.

Returns the value evaluated at the first row of the window frame.

Returns the value evaluated at the last row of the window frame.

Returns the value evaluated at the nth row of the window frame (counting from l);null if no such row.

http://www.postgresql.org/docs/9.3/static/functions-window.html

11.3.2 User-Defined Functions and Aggregates When the built-in SQL functions are insufficient for a particular task or analysis, SQL enables the user to create user-defined functions and aggregates. This custom functionality can be incorporated into SQL queries in the same ways that the built-in functions and aggregates are used. User-defined functions can also be created to simplify processing tasks that a user may commonly encounter.

ADVANCED ANAL YTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

For example, a user-defined function can be written to translate text strings for female (F) and male (M} to 0 and 1, respectively. Such a function may be helpful when formatting data for use in a regression analysis. Such a function, fm _convert () , could be implemented as follows:

CREATE FUNCTION fm_convert(text) RETURNS integer AS 'SELECT CASE

WHEN $1 D I 'F' I THEN 0 WHEN $1 "' I'M' I THEN 1 ELSE NULL

END' LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT

In declaring the function, the SOL query is placed within single quotes. The first and only passed value is referenced by $1. The SOL query is followed by a LANGUAGE statement that explicitly states that the preceding statement is written in SOL Another option is to write the code in C. IMMUTABLE indi- cates that the function does not update the database and does not use the database for lookups. The IMMUTABLE declaration informs the database's query optimizer how best to implement the function. The RETURNS NULL ON NULL INPUT statement specifies how the function addresses the case when any of the inputs are null values.

In the online retail example, the fm_ convert () function can be applied to the customer_ gender column in the customer_ demographics table as follows.

SELECT customer_gender, fm_convert(customer_genderl as male

FROM customer_demographics LIMIT 5

customer_gender male M 1

F 0

F 0

M 1

M 1

Built-in and user-defined functions can be incorporated into user-defined aggregates, which can then be used as a window function. In Section 11.3.1, a window function is used to calculate moving averages to smooth a data series. In this section, a user-defined aggregate is created to calculate an Exponentially Weighted Moving Average (EWMA). For a given time series, the EWMA series is defined as shown in Equation 11-1.

EWMA =I Y, 1 o.y 1 +(1-o).fWMA

1 _

1

whereO ~a~ 1

for t = 11 for t~2

(11-1)

The smoothing factor, determines how much weight to place on the latest point in a given time series. By repeatedly substituting into Equation 11-1 for the prior value of the EWMA series, it can be shown that the weights against the original series are exponentially decaying backward in time.

11.3 Advanced SQL

To implement EWMA smoothing as a user-defined aggregate in SQL, the functionality in Equation 11-1 needs to be implemented first as a user-defined function.

CREATE FUNCTION ewma_calc(numeric, numeric, numeric) RETURNS numeric as /* $1 prior value of EW~~ */ /* $2 = current value of series */ /* $3 = alpha, the smoothing factor */ 'SELECT CASE

WHEN $3 IS NULL OR $3 < 0 OR $3 > 1 THEN NULL WHEN $1 IS NULL THEN $2 WHEN $2 IS NULL THEN $1 ELSE ($3 * $2) + (1-$3) *$1

END' LANGUAGE SQL IMMUTABLE

/* bad alpha */

/* t = 1 */ /* y is unkno\"m *I /* t >= 2 */

Accepting three numeric inputs as defined in the comments, the ewma _calc ( ) function addresses possible bad values of the smoothing factor as well as the special case in which the other inputs are null. The ELSE statement performs the usual EWMA calculation. Once this function is created, it can be refer- enced in the user-defined aggregate, ewma ( ) .

CREATE AGGREGATE ewma(numeric, numeric) (SFUNC = ewma_calc, STYPE = numeric, PREFUNC = dummy_function)

In the CREATE AGGREGATE statement for ewma (), SFUNC assigns the state transition function (ewma _calc in this example) and STYPE assigns the data type of the variable to store the current state of the aggregate. The variable for the current state is made available to the ewma _calc ( ) function as the first variable, $1. In this case, because the ewma _calc () function requires three inputs, the ewma () aggregate requires only two inputs; the state variable is always internally available to the aggregate. The PREFUNC assignment is required in the Greenplum database for use in a massively parallel processing (MPP) environment. For some aggregates, it is necessary to perform some preliminary functionality on the current state variables for a couple of servers in the MPP environment. In this example, the assigned PREFUNC function is added as a placeholder and is not utilized in the proper execution of the ewma ( ) aggregate function.

As a window function, the ewma ( ) aggregate, with a smoothing factor of 0.1, can be applied to the weekly sales data as follows.

SELECT year, week, sales, ewma(sales, .1)

OVER ( ORDER BY year, week)

FROM sales_by_week WHERE year = 2014

ADVANCED ANALYTICS- TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

AND week <= 26

ORDER BY year , week

year 'j,' k sa:es ~· .. :rna 2Q:.; 156~ 5; .. 56~'5'9.00

:; !·i 2 l5~212S 156'297.9J

201·· .3 15S2;;l 156700:.21

201-1 4 1600769 1570.J77 . 99

2014 5 1580146 1571)5•1 . 79

~O!·t 15:955c 1~.;~ -i..: . . ;7

20:4 2-2 1559.;..;3 1 ·i ·78] . .;2

2'Jl4 •• 5 1525437 15·i1':1:8 . 78

2"" , ~"' "'t;~~9:;.; ''' .;~r . 3" -~ - ' Figure 11 -4 includes the EWMA smoothed series to the plot from Figure 11-3.

<n ~ 0 ~ C/) Q)

iii (/)

0 0 0 0 0 (!)

0 0 0 0 (!) 1/)

0 0 0 0 N 1/)

0 5 10

Week

FIGURE 11·4 Weekly sales with moving average and EWMA

15 20 25

11.3 Advanced SQL

Increasing the value of the smoothing factor from 0.1 causes the EWMA to follow the actual data better, but the trade-off is that large fluctuations in the data cause larger fluctuations in the smoothed series. The user-defined aggregate, ewma ( ) , is used in the SQL query in the same manner as any other window function with the specification of the OVER clause.

11.3.3 Ordered Aggregates Sometimes the value of an aggregate may depend on an ordered set of values. For example, to determine the median of a set of values, it is common to first sort the values from smallest to largest and identify the median from the center of the sorted values. The sorting can be accomplished by using the function array _agg ().The following SQL query calculates the median of the weekly sales data.

SELECT (d.ord_sales[ d.n/2 + 1 ] + d.ord_sales[ (d.n + 1)/2 ]) I 2.0 as median

FROM (SELECT ARRAY_AGG(s.sales ORDER BY s.sales) AS ord_sales,

median

COUNT(*) AS n FROM sales_by_week s WHERE s.year = 2014

AND s.week <= 26) d

1551923.5

In general, the function ARRAY_ AGG (} builds an array from a table column. Executing the subquery from the previous SQL query for just the first five weeks illustrates the creation of the array, denoted by the braces, and the sorted weekly sales within the array.

SELECT ARRAY_AGG(s.sales ORDER BY s.sales) AS ord_sales, COUNT(*) AS n

FROM sales_by_week s WHERE s.year = 2014

AND s.week <= 5

ord sales n {1564539,1572128,1580146,1582331,1600769} 5

Besides creating an array, the values can be concatenated together into one text string using the string_agg () function.

SELECT STRING_AGG(s.sales ORDER BY s.sales) AS ord_sales, COUNT(*) AS n

FROM WHERE

sales_by_week s s.year = 2014

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

AND s.week <= 5

ord sales 15645391572128158014615823311600769

n

5

However, in this particular example, it may be useful to separate the values with a delimiter, such as

a comma.

SELECT STRING_AGG(s.sales, 1 , 1 ORDER BY s.sales) AS ord_sales, COUNT(*) AS n

FROM sales_by_week s WHERE s.year = 2014

AND s.week <= 5

ord sales n

1564539,1572128,1580146,1582331,1600769 5

Although the sorted sales appear to be an array, there are no braces around the output. So the displayed ordered sales are a text string.

11.3.4 MADiib SQL implementations include many basic analytical and statistical built-in functions, such as means and variances. As illustrated in this chapter, SQL also enables the development of user-defined functions and aggregates to provide additional functionality. Furthermore, SQL databases can utilize an external library of functions. One such library is known as MADiib. The description file [2] included with the MADiib library download states the following:

MAD/ibis an open-source library for scalable in-database analytics.lt offers data-parallel

implementations of mathematical, statistical, and machine learning methods for struc-

tured and unstructured data.

The concept of Magnetic/Agile/Deep (MAD) analysis skills was introduced in a 2009 paper by Cohen, et al. [3]. This paper describes the components of MAD as follows:

o Magnetic: Traditional Enterprise Data Warehouse (EDW) approaches "repel" new data sources, discouraging their incorporation until they are carefully cleansed and integrated. Given the ubiquity of data in modern organizations, a data warehouse can keep pace today only by being "magnetic": attracting all the data sources that crop up within an organization regardless of data quality niceties.

o Agile: Data Warehousing orthodoxy is based on long-range and careful design and planning. Given growing numbers of data sources and increasingly sophisticated and mission-critical data analyses, a modern warehouse must instead allow analysts to easily ingest, digest, produce, and adapt data rapidly. This requires a database whose physical and logical contents can be in continuous rapid evolution.

o Deep: Modern data analyses involve increasingly sophisticated statistical methods that go well beyond the roll ups and drill downs of traditional business intelligence (BI). Moreover, analysts often need to see both the forest and the trees in running these algorithms; they want to study enormous data sets without resorting to samples and extracts. The modern data warehouse should serve both as a deep data repository and as a sophisticated algorithmic runtime engine.

11.3 Advanced SQL

In response to the inability of a traditional EDW to readi ly accommodate new data sources, the con-

cept of a data lake has emerged. A data lake represents an environment that collects and stores large

volumes of structured and unstructured datasets, typically in their original, unaltered forms. More than a

data depository, the data lake architecture enables the various users and data science teams to conduct

data exploration and related analytical activities. Apache Hadoop is often considered a key component

of building a data lake [4).

Because MADiib is designed and built to accommodate massive para llel processing of data, MADiib is

ideal for Big Data in-database analytics. MADiib supports the open-source database PostgreSQL as well

as the Pivotal Green plum Database and Pivotal HAWQ. HAWQ is a SQL query engine for data stored in the

Hadoop Distributed File System (HDFS). Apache Hadoop and the Pivotal products were described in Chapter

10, "Advanced Analytics-Technology and Tools: MapReduce and Hadoop."

MADiib version 1.6 modules [5) are described in Table 11-4.

TABLE 11 4 MADiib Modules

Module Description

Generalized Linear Models

Cross Validation

Linear Systems

Matrix Factorization

Association Ru les

Clustering

Topic Modeling

Descriptive Statistics

Inferential Statistics

Support Modules

Dimensionality Reduction

Time Series Analysis

Includes linear regression, logistic regression, and multinomial logistic regression

Evaluates the predictive power of a fitted model

Solves dense and sparse linear system problems

Performs low- rank matrix factorization and singular value

decomposition

Implements the A priori algorithm to identify frequent item sets

Implements k-means clustering

Provides a Latent Dirichlet Allocation predictive model for a set of

documents

Simplifies the computation of summary statistics and correlations

Conducts hypothesis tests

Provides general array and probabil ity functions that can also be used by other MADiib modules

Enables principal component analyses and projections

Conducts ARIMA analyses

http : //d oc . madl i b . net/late s t / mod ules . html

In the following example, MAD lib is used to perform a k-means clustering analysis, as described in

Chapter 4, "Advanced Analytical Theory and Methods: Clustering," on the web retailer's customers. Two

ADVANCED ANALYTICS-TECHNOLOGY AND TOOLS: IN-DATABASE ANALYTICS

customer attributes-age and total sales since 2013-have been identified as variables of interest for the purposes of the clustering analysis. The customer's age is available in the customer_ demographics table. The total sales for each customer can be computed from the orders_ recent table. Because it was decided to include customers who had not purchased anything, a LEFT OUTER JOIN is used to include all customers. The customer's age and sales are stored in an array in the cus t _age_ sales table. The MADiib k-means function expects the coordinates to be expressed as an array.

/* create an empty table to store the input for the k-means analysis */ CREATE TABLE cust_age_sales

customer_id integer, coordinates floatS[])

/* prepare the input for the k-means analysis */ INSERT INTO cust_age_sales (customer_id, coordinates[l], coordinates[2])

SELECT d.customer_id, d.customer_age, CASE

WHEN s.sales IS NULL THEN 0.0 ELSE s.sales

END FROM customer_demographics d

LEFT OUTER JOIN (SELECT r.customer_id, SUM(r.item_quantity * r.item_price) AS sales

FROM orders_recent r GROUP BY r.customer_id) s

ON d.customer_id ~ s.customer_id

/* examine the first 10 rows of the input */ SELECT * from cust_age_sales order by customer_id LIMIT 10

customer id coordinates - {32,14.98}

2 {32,51.48} 3 {33,151.89} 4 {27,88.28} 5 {31,4.85} 6 {26,54} 7 {29,63} 8 {25,101.07} 9 {32,41.05} 10 { 321 0}

Using the MAD lib function, kmeans _random ( ) , the following SQL query identifies six clusters within the provided dataset. A description of the key input values is provided with the query.

11.3 Advanced SQL

/*

K-means analysis

cust_age_sales - SQL table containing the input data coordinates the column in the SQL table that contains the data points customer_id - the column in the SQL table that contains the

identifier for each point km_coord - the table to store each point and its assigned cluster km_centers - the SQL table to store the centers of each cluster l2norm - specifies that the Euclidean distance formula is used 25 - the maximum number of iterations 0.001 - a convergence criterion False(twice) - ignore some options 6 - build six clusters

*I

SELECT madlib.kmeans_random('cust_age_sales', 'coordinates', 'customer_id', 'km_coord', 'km_centers', '12norm', 25 ,0.001, False, False, 6)

SELECT * FROM km_coord ORDER BY pid LIMIT 10

pid coords cid 1 {111}:{32114.98} 6

2 {11 1}: {321 51.48} 1

3 {111}:{331151.89} 4

4 {111}:{27188.28} 1

5 {111}:{3114.85} 6

6 {111}:{26154}

7 {111}:{29163}

8 {111}:{251101.07} 1

9 { 11 1} ; { 32 1 41. 05} 1

10 {111}:{3210} 6

The output consists of the km _ coord table. This table contains the coordinates for each point id (pi d), the customer_id, and the assigned cluster ID (cid). The coordinates (coords) are stored as sparse vectors. Sparse vectors are useful when values in an array are repeated many times. For example, {1,200,3}:{1,0,1} represents the following vector containing 204 elements, {1,0,0, ... 0,1,1,1}, where the zeroes are repeated 200 times.

The coordinates for each cluster center or centroid are stored in the SQL table km_ center.

SELECT * FROM km_centers

ADVANCED ANALYTICS-TECHNOLOGY AN D TOOLS: IN-DATABASE ANALYTICS

ORDER BY coords

cid coords 6 {1,1} : {4~ . :131730722.54,6 314878041613021

{1,1} : {39 . 8000~1 0 ~ 4 ,61 . &-1•60328673~/

4 {1,1} : {39.::!578830823738,167. 158<;561:7954\

5 {1,1} : {40 . 94~709-8<;~768,409.8469061450~;

{1,1) : {42 . 352194716 391,11 0.68858851676} .,1(1~10"1 I

Because the age values are similar for each centroid, it appears that the sales values dominated the distance calculations. After visualizing the clusters, it is advisable to repeat the analysis after rescaling, as

discussed in Chapter 4.

Summary This chapter presented several techniques and examples illustrating how SQL can be used to perform in- database analytics. A typical SQL query involves joining several tables, filtering the returned dataset to the

desired records with a WHERE clause, and specifying the particular columns of interest. SQL provides the set operations of UNI ON and UNION ALL to merge the results of two or more SELECT statements or I NTERSECT to find common record elements. Other SQL queries can summarize a dataset using aggregate

functions such as COUNT ( l and SUM ( l and the GROUP BY clause. Grouping extensions such as the CUBE and ROLL UP operators enable the computation of subtotals and grand totals.

Although SQL is most commonly associated with structured data, SQL tables often contain unstructured data such as comments, descriptions, and other freeform text content. Regular expressions and related

functions can be used in SQL to examine and restructure such unstructured data for further analysis. More complex SQL queries can utilize window functions to supply computed values such as ranks and

rolling averages along with an original dataset. In addition to built-in functions, SQL offers the ability to

create user-defined functions. Although it is possible to process the data within a database and extract the results into an analytical tool such as R, external libraries such as MADiib can be utilized by SQL to conduct statistical analyses within a database.

Exercises 1. Show that EWMA smoothing is equivalent to an ARIMA{O, 1,1 ) model with no constant, as described in

Chapter 8, "Advanced Analytica l Theory and Methods: Time Series Analysis."

2. Referring to Equation {1 1-1 ), demonstrate that the assigned weights decay exponentially in time.

3. Develop and test a user-defined aggregate to calculate n factorial {n!), where n is an integer.

4. From a SQL table or query, randomly select 10% of the rows. Hint: Most SQL implementations have a random ( ) function that provides a uniform random number between 0 and 1. Discuss possible reasons to randomly sample records from a SQL table.

Bibliography

Bibliography [1) PostgreSQI.org, "Window Functions" [Online]. Available: http: I / www. postgresql . org/

docs /9 . 3 I static/ functions-window . html. [Accessed 10 April 2014).

[2) MADiib, "MADiib" [Online). Available: http : I / madlib. net / download/ . [Accessed 10 April 2014).

(3] J. Cohen, B. Dolan, M. Dunlap, J. Hellerstein, and C. Welton, "MAD Skills: New Analysis Practices for Big Data," in Proceedings of the VLDB Endowment Volume 2/ssue 2, August 2009.

[4) E. Dumbill, "The Data Lake Dream," Forbes, 14 January 2014. [Online]. Available: http : I /www . forbes . com/ sites/edddumbill / 2014 / 01 / 14 / the-data-lake-dream/ . (Accessed 4 June 2014].

[5) MADiib, "MADiib Modules" (Online]. Available: http: I / doc. madlib. net /latest / modules. html. (Accessed 10 April2014].

THE ENDGAM E, OR PUTTING IT ALL TOGETHER

This chapter focuses on the final phase of the Data Analytics Lifecycle: operationalize. In this phase, the project team delivers final reports, code, and technical documentation. At the conclusion of this phase, the team generally attempts to set up a pilot project and implement the developed models from Phase

4 in a production environment. As stated in Chapter 2, "Data Analytics Lifecycle," teams can perform a technically accurate analysis, but if they cannot translate the results into a language that resonates with their audience, others will not see the value, and significant effort and resources will have been wasted.

This chapter focuses on showing how to construct a clear narrative summary of the work and a framework for conveying the narrative to key stakeholders.

12.1 Communicating and Operationalizing an Analytics Project As shown in Figure 12-1, the final phase in the Data Ana lytics Lifecycle focuses on operationalizing the project. In this phase, teams need to assess the benefits of the project work and set up a pilot to deploy the

models in a controlled way before broadening the work and sharing it with a full enterprise or ecosystem of users. In this context, a pilot project can refer to a project prior to a full-sca le rollout of the new algorithms

or functionality. This pilot can be a project with a more limited scope and rollout to the lines of business, products, or services affected by these new models.

Data Analytics Lifecycle -

FIGURE 12-1 Data Analytics Lifecycle, Phase 6: operationalize

The team's ability to quantify the benefits and share them in a compelling way with the stakeholders will determine if the work will move forward into a pilot project and ultimately be run in a production environ-

ment. Therefore, it is critical to identify the benefits and state them in a clear way in the final presentations.

12.1 Communicating and Operationalizing an Analytics Project

As the team scopes the effort involved to deploy the analytical model as a pilot project, it also needs

to consider running the model in a production environment for a discrete set of products or a single line

of business, which tests the model in a live setting. Th is allows the team to Jearn from the deployment

and make adjustments before deploying the appl ication or code more broadly across the enterprise. This

phase can bring in a new set of team members- namely, those engineers responsible for the production

environment who have a new set of issues and concerns. This group is interested in ensuring that running

the model fits smoothly into the production environment and the model can be integrated into downstream

processes. While executing the model in the production environment, the team should aim to detect input

anomalies before they are fed to the model, assess run times, and gauge competition for resources with

other processes in the production environment.

Chapter 2 included an in-depth discussion of the Data Analytics Lifecycle, including an overview of the

del iverables provided in its final phase, at which time it is advisable for the team to consider the needs of

each of its main stakeholders and the deliverables, illustrated in Figure 12-2, to satisfy these needs.

Code II:ODI Presentation for Analysts

I:I:I:::IS Technical Specs ICII Presentation for Project Sponsors

FIGURE 12-2 Key outputs from a successful analytic project

Following is a brief review of the key outputs for each of the main stakeholders of an analytics project

and what they usually expect at the conclusion of a project:

• Business User typically tries to determine the benefits and implications of the findings to the business.

• Proj ect Sponsor typically asks questions related to the business impact of the project, the risks and return on investment (ROI). and how the project can be evangelized within the organization and beyond.

THE ENDGAME, OR PUTTING IT ALL TOGETHER

• Project Manager needs to determine if the project was completed on time and within budget.

• Business Intelligence Analyst needs to know if the reports and dashboards he manages will be impacted and need to change.

• Data Engineer and Database Administrator (DBA) typically need to share the code from the ana- lytical project and create technical documents that describe how to implement the code.

• Data Scientists need to share the code and explain the model to their peers, managers, and other stakeholders.

Although these seven roles represent many interests within a project, these interests usually overlap, and most of them can be met with four main deliverables:

• Presentation for Project Sponsors contains high-level takeaways for executive-level stakeholders, with a few key messages to aid their decision-making process. Focus on clean, easy visua ls for the presenter to explain and for the viewer to grasp.

• Presentation for Analysts, which describes changes to business processes and reports. Data scien- tists reading this presentation are comfortable with technical graphs (such as Receiver Operating Characteristic [ROC) curves, density plots, and histograms) and will be interested in the details.

• Code for technical people, such as engineers and others managing the production environment

• Technical specifications for implementing the code

As a rule, the more executive the audience, the more succinct the presentation needs to be for project sponsors. Ensure that the presentation gets to the point quickly and frames the results in terms of value

to the sponsor's organization. When presenting to other audiences with more quantitative backgrounds,

focus more time on the methodology and finding s. In these instances, the team can be more expansive in describing the outcomes, methodology, and analytical experiments with a peer group. This audience will be more interested in the techniques, especially if the team developed a new way of processing or

analyzing data that can be reused in the future or applied to similar problems. In addition, use imagery or data visualization when possible. Although it may take more time to develop imagery, pictures are more appeal ing, easier to remember, and more effective to deliver key messages than long lists of bullets.

12.2 Creating the Final Deliverables After reviewing the list of key stakeholders for data science projects and main deliverables, this sec tion

focuses on describing the deliverables in detail. To illustrate this approach, a fictional case study is used to make the examples more specific. Figure 12-3 describes a scenario of a fictional bank, YoyoDyne Bank, which would like to embark on a project to do churn prediction models of its customers. Churn rate in this context refers to the frequency with which customers sever their relationship as customers of YoyoDyne Bank or switch to a competing bank.

S)ROitsls or \'O)Dil)RC Jlank ('asc Stud)

• \'oyoDyne Bank is a retail bnnk that wants to improve its Net Present \' alue (NP\') and its customer retention rate.

• It wants to establish an effective marketing campaign targeting customers to reduce tlte chum rate by at least five percent.

• The bank wants to detennine whether those customers an~ worth retaining. In addition. the bank wants to analyze reasons for customer attrition and what it can do to keep customers from leaving.

• The bank wants to build a data warehouse to support marketing and ot11er related customer care groups.

FIGURE 12-3 Synopsis ofYoyoDyne Bank case study example

12.2 Creating the Final Deliverables

Based on this information, the data science team may create an analytics plan similar to Figure 12-4

during the project

Components of l{cluil Bunking: Yoyo()ync Bunk

Anulytic l'lun

Dlsco.-e~- How can the bank identify customers with the highest

Business Problem likelihood for chum? Frametl

Initial H~·polheses Transaction volume and type are key predictors of churn rates

Data and Scope 5 months of customer account history

l\Iotlel Planning - Logistic regression to identify most influential factors Analytic

predicting chum Technique

Key predictors of chum are: I. Once customers stop using their accounts for gas and

Result anti Ke~· groceries, their account holdings quickly diminish and Flntllngs the customers chum.

2. If the customers use their debit card fewer than5 times per month, they will leave the bank within60 days.

By targeting customers who are at high risk for chum.

Business lmi"ICt customer attrition can be reduced by 23%. This would save $3 million in lost customer revenue and avoid $1.5 million in new customer acquisition costs each year for the bank.

FtGURE 12-4 Analytics plan for YoyoDyne Bank case study

In addition to guiding the model planning and methodology, the analytic plan contains components

that can be used as inputs for writing about the scope, underlying assumptions, modeling techniques, initial

hypotheses, and key find ings in the final presentations. After spending substantial amounts of time in the

modeling and performing in-depth data analysis, it is critical to reflect on the project work and consider

THE ENDGAME, OR PUTTING IT ALL TOGETHER

the context of the problems the team set out to solve. Review the work that was completed during the project, and identify observations about the model outputs, scoring, and results. Based on these observa- tions, begin to identify the key messages and any unexpected insights.

In addition, it is important to tailor the project outputs to the audience. For a project sponsor, show that the team met the project goals. Focus on what was done, what the team accomplished, what ROI can be anticipated, and what business value can be realized. Give the project sponsor talking points to evangelize the work. Remember that the sponsor needs to relay the story to others, so make this person's job easy, and help ensure the message is accurate by providing a few talking points. Find ways to emphasize ROI and business value, and mention whether the models can be deployed within performance constraints of the sponsor's production environment.

In some organizations, the data science team may not be expected to make a full business case for future projects and implementation of the models. Instead, it needs to be able to provide guidance about the impact of the models to enable the project sponsor, or someone designated by that person, to create a business case to advocate for the pilot and subsequent deployment of this functionality. In other words, the data science team can assist in this effort by putting the results of the modeling and data science work into context to help assess the actual value and cost of implementing this work more broadly.

When presenting to a technical audience such as data scientists and analysts, focus on how the work was done. Discuss how the team accomplished the goals and the choices it made in selecting models or analyzing the data. Share analytical methods and decision-making processes so other analysts can learn from them for future projects. Describe methods, techniques, and technologies used, as this technical audience will be interested in learning about these details and considering whether the approach makes sense in this case and whether it can be extended to other, similar projects. Plan to provide specifics related to model accuracy and speed, such as how well the model will perform in a production environment.

Ideally, the team should consider starting the development of the final presentation during the project rather than at the end of the project as commonly occurs. This approach ensures that the team always has a version of the presentation with working hypotheses to show stakeholders, in case there is a need to show a work-in-process version of the project progress on short notice. In fact, many analysts write the executive summary at the outset of a project and then continually refine it over time so that at the end of the project, portions of the final presentation are already completed. This approach also reduces the chance that the team members will forget key points or insights discovered during the project. Finally, it reduces the amount of work to be done on the presentation at the conclusion of the project.

12.2.1 Developing Core Material for Multiple Audiences Because some of the components of the projects can be used for different audiences, it can be helpful to create a core set of materials regarding the project, which can be used to create presentations for either a technical audience or an executive sponsor.

Table 12-1 depicts the main components of the final presentations for the project sponsor and an analyst audience. Notice that teams can create a core set of materials in these seven areas, which can be used for the two presentation audiences. Three areas (Project Goals, Main Findings, and Model Description), can be used as is for both presentations. Other areas need additional elaboration, such as the Approach. Still other areas, such as the Key Points, require different levels of detail for the analysts and data scientists than for the project sponsor. Each of these main components of the final presentation is discussed in subsequent sections.

12.2 Creating the Final Dellverables

TABL£ 12-1 Comparison of Materials for Sponsor and Analyst Presentations

Project Presentation Sponsor

Component Presentation Analyst Presentation

Project Goals List top 3-5 agreed-upon goals.

Main Findings Emphasize key messages.

Approach High-level

methodology High-level methodology

Relevant details on modeling techniques and technology

Model Description Overview of the modeling technique

Key Points

Supported with Data

Model Details

Support key points with

simple charts

and graphics (example: bar charts).

Omit this sec-

tion, or discuss only at a high

level.

Recommendations Focus on busi- ness impact,

including risks

and ROI.

Give the spon- sor sa lient

points to help her evangelize

work within the organization.

12.2.2 Project Goals

Show details to support the key points.

Analyst-oriented charts and graphs, such as ROC curves and histograms

Visuals of key variables and significance of each

Show the code or main logic of the model, and include

model type, variables, and technology used to execute t he model and score data.

Identify key variables and impact of each.

Describe expected model performance and any caveats.

Detailed description of the modeling technique

Discuss variables, scope, and predictive power.

Supplement recommendations with implications for the modeling or for deploying in a production environment.

The Project Goals portion of the final presentation is generally the same, or similar, for sponsors and for

analysts. For each audience, the team needs to reiterate the goals of the project to lay the groundwork for

THE ENDGAME, OR PUTTING IT ALL TOGETHER

the solution and recommendations that are shared later in the presentation. In addition, the Goals slide

serves to ensure there is a shared understanding between the project team and the sponsors and confirm

they are al igned in moving forward in the project. Generally, the goals are agreed on early in the project.

It is good practice to write them down and share them to ensure the goals and objectives are clearly

understood by both the project team and the sponsors.

Figures 12-5 and 12-6 show two examples of slides for Project Goals. Figure 12-5 shows three goals

for creating a predictive model to anticipate customer churn. The points on this version of the Goals slide

emphasize what needs to be done, but not why, which will be included in the alternative.

Project Goa ls

Develop a predictive model to determine which customers are most

likely to churn and when

Model's predictive power should be at least as good as customer retention techniques currently being used by the bank

3 . Models should scale to run on a fu ll data set in production environment on weekly basis

FIGURE 12-5 Example of Project Goals slide for YoyoDyne case study

Figure 12-6 shows a variation of the previous Project Goals slide in Figure 12-5. It is a summary of the

situation prior to listing the goals. Keep in mind that when delivering final presentations, these deliverables

are shared within organizations, and the original context can be lost, especially if the original sponsor leaves

the group or changes roles. It is good practice to briefly recap the situation prior to showing the project

goals. Keep in mind that adding a situation overview to the Goals slide does make it appear busier. The

team needs to determine whether to split this into a separate slide or keep it together, depending on the

audience and the team's style for delivering the final presentation.

One method for writing the situational overview in a succinct way is to summarize it in three bullets,

as follows:

• Situation: Give a one-sentence overview of the situation that has led to the analytics project.

• Complication: Give a one-sentence overview of the need for addressing this now. Something has triggered the organization to decide to take action at this time. For instance, perhaps it lost 100

12.2 Creating the Final Deliverables

customers in the past two weeks and now has an executive mandate to address an issue, or perhaps it has lost five points of market share to its biggest competitor in the past three months. Usually, this sentence represents the driver for why a particular project is being initiated at this time, rather than in some vague time in the future.

• Implication: Give a one-sentence overview of the impact of the complication. For instance, if the bank fails to address its cus tomer attri tion problem, it stands to lose its dominant market posi tion in three key markets. Focus on the business impact to illustrate the urgency of doing the project.

Situation & Project Goals

Situation

YoyoDyne Bank wants to improve the Net Present Value (NPV) and retention rate of the customers

In the last 90 days, YoyoDyne has lost 6 of its top 100 customers and is seeing increased competition from its biggest competitor

Without a fast remediation plan, YoyoDyne risks losing its dominant position in three key markets

Goals ofYoyoDyne ~churn Project"

Develop a predictive model to determine which customers are mostlike_y to churn and when

Model's predictive power should be at least as good as customer retention techniques currently being used by the bank

Models should scale to run on a full data set in production environment on weekly basis

FIGURE 12· 6 Example of Situation & Project Goals slide for YoyoDyne case study

12.2.3 Main Findings Write a solid executive summary to portray the main findings of a project. In many cases, the summary may be the only portion of the presentation that hurried managers will read. For this reason, it is imperative to

make the language clear, concise, and complete. Those reading the executive summary should be able to grasp the full story of the project and the key insights in a single slide. In addition, this is an opportunity

to provide key talking points for the executive sponsor to use to evangelize the project work with others in the customer's organization. Be sure to frame the outcomes of the project in terms of both quantitative and qualitative business value. Th is is especially important if the presentation is for the project sponsor. The executive summary slide con taining the main find ings is generally the same for both sponsor and

analyst audiences. Figure 12-7 shows an example of an executive summary slide for the YoyoDyne case study. It is useful

to take a closer look at the parts of the slide to make sure it is clear. Keep in mind this is not the only format

for conveying the Executive Summary; it varies based on the author's style, although many of the key components are common themes in Executive Summaries.

THE ENDGAME, OR PUTTING IT ALL TOGETHER

Executive Summary

Running an early churn warning test each day using social media can

reduce annual churn by 30 % and save $4.5M annually

Customers churn within 60 days of changing their spending habits

Once customers stop using their accounts for gas and groceries, their account holdings quickly diminish and the customers churn

If customers use their debit card fewer than 5 times per month, they will leave the bank within 60 days

Combining social networking data and existing TlmelnMontM

CRM data increases the model's predictive power to identify churners We can pinpoint social media chatter from bank customers and influence of churner's contacts

With CRM data, we can identify 20% of churners, adding social media data Increases this to30%

Models can run in minutes, rather than current process of monthly cycles

FIGURE 12 7 Example of Executive Summary slide for YoyoDyne case study

The key message should be clear and conspicuous at the front of the slide. It can be set apart with color or shading, as shown in Figure 12-8; other techniques can also be used to draw attention to it. The key message may become the single talking point that executives or the project sponsor take away from the

project and use to support the team 's recommendation for a pilot project, so it needs to be succinct and

compelling. To make this message as strong as possible, measure the value of the work and quantify the cost savings, revenue, time savings, or other benefits to make the business impact concrete.

Follow the key message with three major supporting points. Although Executive Summary slides can

have more than three major points, going beyond three ideas makes it difficult for people to recall the main points, so it is important to ensure that the ideas remain clear and limited to the few most impactful ideas the team wants the audience to take away from the work that was done. If the author lists ten key points,

messages become diluted, and the audience may remember only one or two main points. In addition, because this is an analytics project, be sure to make one of the key points related to if, and

how well, the work will meet the sponsor's service level agreement (SLA) or expectations. Traditionally, the

SLA refers to an arrangement between someone providing services, such as an information technology (IT) department or a consulting firm, and an end user or customer. In this case, the SLA refers to system

performance, expected uptime of a system, and other constraints that govern an agreement. This term has become less formal and many times conveys system performance or expectations more generally related to performance or timeliness. It is in this sense that SLA is being used here. Namely, in this contex t, SLA

12.2 Creating the Final Deliverables

refers to the expected performance of a system and the intent that the models developed will not adversely

impact the expected performance of the system into which they are integrated.

Finally, although it's not required, it is often a good idea to support the main points with a visual or graph.

Visual imagery serves to make a visceral connection and helps retain the main message with the reader.

Anatomy of an Exec utive Summary

Key Message

Major Points

~Executive Summary

Business Impact "

Runmng on early churn wornmg test each day using social medta con

reduce annual churn by 30 !16 and save $4.5M annually

Customers churn within 60 days of changing their spending habits

Once cu\tOmtn stop using tht1r ICCOunts tor gas 1nd groctnes, their account hold nss quickly dlmlmsh •nd the customers churn If custo!Tifrs use their dtb1t urd fewer than 5 tJmts per month, they wtllleave the bank within 60davs

Combining social networking data and existing -·-CRM data increases the model's predictive power to identify churners We can pl,polnt social media chatter from bank customers and Influence of churner's contacts W1th CRM data, we can idenufy 20% of chur'ners; adding social media data Increases this to 30"

SLA f Models can run In minutes, rather than current process of monthly cycles I

FiGURE 12-8 Anatomy of an Executive Summary slide

12.2.4 Approach In the Approach portion of the presentation, the team needs to explain the methodology pursued on the

project. This can include interviews with domain experts, the groups collaborating within the organization,

and a few statements about the solution developed. The objective of this slide is to ensure the audience

understands the course of action that was pursued well enough to explain it to others with in the organi-

zation. The team should also include any additional comments related to working assumptions the team

followed as it performed the work, because this can be critical in defending why they followed a specific

course of action. When explaining the solution, the discussion should remain at a high level for the project sponsors. If

presenting to analysts or data scientists, provide additional detail about the type of model used, including

the technology and the actual performance of the model during the tests. Finally, as part of the description

of the approach, the team may want to mention constraints from systems, tools, or existing processes and

any implications for how these things may need to change with this project.

THE ENDGAME, OR PUTTING IT ALL TOGETHER

Figure 12-9 shows an example of how to describe the methodology followed during a data science

project to a sponsor audience.

Approach (for Sponsors)

• Interviewed 14 members of retail lending team to understand YoyoDyne's lending policies and marketing practices for customer retent ion

• Collaborated with IT to ident ify relevant datasets and assess data quality and availabili ty

• Developed churn model to ident ify customers most likely to leave the bank

Identify most influent1al factors

Provide greater explanatory power for analyZIM81mpact of d1fferent factors on churn

Mined and added social media data to the model to improve predictive power

• Worked with IT to simulate model performance within YoyoDyne's production environment

FIGURE 12-9 Example describing the project methodology for project sponsors

Note that the third bullet describes the churn model in general terms. Furthermore, the subbullets pro-

vide additional details in nontechnical terms. Compare this approach to the variation shown in Figure 12-10.

Approach (for Analysts)

• Interviewed 14 members of retail lending team to understand YoyoDyne's lending policies and marketing practices for customer retent ion

Collaborated with IT to ident ify relevant datasets and assess data quality and availability

• Developed churn model in R using a Generalized Addictive Modeling technique

Minimizes variable transformations and binnlna

Provide greater explanatory power for ana 1yzms1mpact of d1tferent factors on churn

Examined impact of social network variables and found that it helped identify more potential churners

Work with IT to simulate model performance within YoyoDyne's product ion environment

The model can be rapidly scored m the database over large datasets using a SQL code generator for the purpose

FiGURE 12·10 Example describing the project methodology for analysts and data scientists

)

Figure 12-10 shows a va riation on the approach and methodology used in the data science p roject.

In this case, most of the language and description are the same as in the example for project sponsors.

12.2 Creating the Final Deliverables

The main difference is that this version conta ins additional detail regarding the kind of model used and the way the model will score data quickly to meet the SLA. These differences are highlighted in the boxes

shown in Figure 12-10.

12.2.5 Model Description After describing the project approach, teams generally include a description of the model that was used. Figure 12-11 provides the model description for the Yoyodyne Bank example. Although the Model Description slide can be the same for both audiences, the interests and objectives differ for each. For the

sponsor, the general methodology needs to be articulated without getting into excessive detail. Convey the basic methodology followed in the team's work to allow the sponsor to communicate this to others

within the organization and provide talking points. Mentioning the scope of the data used is critical. The purpose is to illustrate thoroughness and exude

confidence that the team used an approach that accurately portrays its problem and is as free from bias as possible. A key trait of a good data scientist is the ability to be skeptical of one's own work. Th is is an opportunity to view the work and the deliverable critically and consider how the audience wi ll receive the

work. Try to ensure it is an unbiased view of the project and the results.

Assuming that the model will meet the agreed-upon SLAs, mention that the model wi ll meet the SLAs based on the performance of the model within the testing or staging environment. For instance, one may want to indicate that the model processed 500,000 records in 5 minutes to give stakeholders an idea of the

speed of the model during run time. Analysts will want to understand the details of the model, including the decisions made in constructing the model and the scope of the data extracts for testing and training. Be prepared to explain the team's thought process on this, as well as the speed of running the model within

the test environment.

Model Descri pti on

Overview of Basic Methodology: pred•ct the I <e I hood o7 chu"Tl ~or each customer. ldent.'y customers w•th a greater probab1 ~tv for chum then compare \'lith actual chum outcomes to tra n the a1gonthm and enao1e pred1ct1ons forextsttng customers.

M odel: log•stiC regress1on model Dependent variable: Binary vanable, of chum/no chum

S<ope : 500,000 Yovodyne bank customers, based on churn wtth•n a 150 day penod after 1/31/2011

500,000 Customerswtth all churners through 6/30/11, p!us a random sample of 45,000 accounts

Atl selected customers were ActNe, Suspended or Pendtng as 0 1 2011·01·31

Call Hostory detaol data extracted from Call Data Record Warehouse for customers from 1/31/11 to 6/30/11

Sampling

Traonong sample: 50,000 subscnbers

Tesung sample: 100,000 subscrobers

The model developed has predictive power at least as good as the bank's current churn model

we created a baseline model w~thout soCial networking variables and the bank's marke-tmg anatytlcs team venfled that the pred1cttve pm·.~erwas at least as good as the current model

soc1al networkang vanables were added to the model and that further 1ncreased 1ts predacuve power

FIGURE 12-11 Example of a model description for a data science project

THE ENDGAME, OR PUTTING IT ALL TOGETHER

12.2.6 Key Points Supported with Data The next step is to identify key points based on insights and observations resulting from the data and model scoring results. Find ways to illustrate the key points with charts and visualization techniques, using simpler

charts for sponsors and more technical data visualization for analysts and data scientists. Figure 12-12 shows an example of providing supporting detail regarding the rate of bank customers

who would churn in various months. When developing the key points, consider the insights that will drive

the biggest business impact and can be defended with data. For project sponsors, use simple charts such

as bar charts, which illustrate data clearly and enable the audience to understand the value ofthe insights. This is also a good point to foreshadow some of the team's recommendations and begin tying together ideas to demonstrate what led to the recommendations and why. In other word s, this section supplies the

data and foundation for the recommendations that come later in the presentation. Creating clear, compel- ling slides to show the key points makes the recommendations more credible and more likely to be acted upon by the customer or sponsor.

Key Points Implementing an early churn model can identify 30% of likely churners

• Top Chum Chatters Top 5% Per Base Model All Customers

Sep

£ Oct c: 0 :E Nov

Dec

0% 5% 10% 15% 20% Churn Rate

FIGURE 12·12 Example of a presentation of key points of a data science project shown as a barchart

For analyst presentations, use more granular or technical charts and graphs. In this case, appropriate visualization techniques include dot charts, density plots, ROC curves, or histograms of a data distribution

to support decisions made in the modeling techniques. Basic concepts of data visualization are discussed later in the chapter.

12.2.7 Model Details Model details are typically needed by people who have a more technical understanding than the spon-

sors, such as those who will implement the code, or col leagues on the analytics team. Project sponsors are typically less interested in the model details; they are usually more focused on the business implica- tions of the work rather than the details of the model. This portion of the presentation needs to show the code or main logic of the model, includ ing the model type, variables, and technology used to execute

12.2 Creating the Final Deliverables

the model and score the data. The model details segment of the presentation should focus on describing

expected model performance and any caveats related to the model performance.ln addition, this portion of the presentation should provide a detailed description of the modeling technique, variables, scope, and expected effectiveness of the model.

This is where the team can provide discussion or written details related to the variables used in the model and explain how or why these variables were selected. In addition, the team should share the actual code (or at least an excerpt) developed to explain what was created and how it operates. This also serves

to foster discussion related to any additional constraints or implications related to the main logic of the

code. In addition, the team can use this section to illustrate detai ls of the key variables and the predictive power of the model, using analyst-oriented charts and graphs, such as histograms, dot charts, density

plots, and ROC curves. Figure 12-13 provides a sample slide describing the data variables, and Figure 12-14 shows a sample

slide with a technical graph to support the work.

Model Detail s

Candidate variables: 22 from CRM, 154 from call his tory, and 12 social networking variables

Through PCA and doscussion with domain experts, we reduced - 190 variables to the 9 most predictive of customer churn

General Additove Model {GAM) model built in R :

gom M, b)J c-borlt!O:d'lJtrt 110 p-

s(~orl. £!=·a "_b)!-:cJO.l-:::!~,.gtt1cvs:o~ lnot.s I

•s(vorJ . £!= "cs":b)o :cJOJ •s(vor3,Ju:"c:s' l-=S]

• s(vor.: .bs= "cs 'k=S.lw=c.JOI

· s(lvo.S .bs= 'cs • k=SI

• sfvot'S1

• S(VO<Sj,

kno::s=l..st(var1 =cvstom kffO!JJ.

doto=tro , df.fom.:O,=b·nOITI ot. ~.ghr=we·o~ gommo=l .: )

FtGURE 12-13 Example of made/ details showing model type and variables

As part of the model detail description, guidance should be provided regarding the speed with which the model can run in the test environment; the expected performance in a live, production environ- ment; and the technology needed. This kind of discussion addresses how well the model can meet the

organization's SLA. This section of the presentation needs to include additional caveats, assumptions, or constraints of the

model and model performance, such as systems or data the model needs to interact with, performance

THE ENDGAME, OR PUTTING IT ALL TOGETHER

issues, and ways to feed the outputs of the model into existing business processes. The author of this sec-

tion needs to describe the relationships of the main variables on the project objectives, such as the effects of key variables on predicting churn, and the relationship of key variables to other variables. The team may even want to make suggestions to improve the model, highlight any risks to introducing bias into the

modeling technique, or describe certain segments of the data that may skew the overall predictive power

of the methodology.

Va r 1 has a larger ancl ea rlrer rrnpact on churn chatters

U'l N

£ 0 N

u '5 ~ U'l Q.

1'5 "' :§ ~ .~

"' .. U'l c: "' ci 6

0 ci

0 200 400

Varl ~td - churn th•ttt'rs

Black- all ol~rs

FIGURE 12·14 Model details comparing two data variables

12.2.8 Recommendations

600

The final main component of the presentation involves creating a set of recommendations that include how to deploy the model from a business perspective within the organization and any other suggestions on the

rollout of the model's logic. For the Yoyodyne Bank example, Figure 12-15 provides possible recommenda- tions from the project. In this section of the presentation, measuring the impact of the improvements and stating how to leverage that impact within the recommendations are key. For instance, the presentation might mention that every customer retained represents a time savings of six hours for one of the bank's account managers or $50,000 in savings of new account acquisitions, due to marketing costs, sales, and

system-related costs. For a presentation to a project sponsor audience, focus on the business impact of the project, including

risks and ROI. Because project sponsors will be most interested in the business impact of the project, the presentation should also provide the sponsor with salient points to help evangelize the work within the organization. When preparing a presentation for analysts, supplement the main set of recommendations with any implications for the modeling or for deployment in a production environment. In either case, the

1 2.2 Creating the Fina l De liverables

team should focus on recommending actions to operationalize the work and the benefits the customer will receive because of implementing these recommendations.

Recommendation s

Implement the model as a pilot, before more w ide-scale rollout- test and learn from initial pilot on performance and precision

Addressing these promptly can pote nt ially save more customers from churning over time and also prevent more networking that seems to drive a dditional churn

An early churn warning trigger can be set up based on this model

Run the pred ictive model daily or weekly to be proactive on customer churn

In-database scorer can score large datasets in a mat ter of minutes and can be run daily

Each customer retained via early wa rning t rigger saves 4 hours of account retention efforts & SOk in new account acquisition costs

Develop targeted customer surveys to investigate the causes of churn, which will make the collect ion of data for investigat ion into the causes of churn easier

FIGURE 12-15 Sample recommendations for a data science project

12.2.9 Additional Tips on the Final Presentation As a team completes a project and strives to move on to the next one, it must remember to invest adequate time in developing the final presentations. Orienting the audience to the project and providing context is

important. On occasion, a team is so immersed in the project that it fails to provide sufficient context for its recommendations and the outputs of the models. A team needs to remember to spell out terminology

and acronyms and avoid excessive use of jargon. It should also keep in mind that presentations may be shared extensively; therefore, recipients may not be familiar with the context and the journey the team has gone through over the course of the project.

The story may need to be told multiple t imes to different audiences, so the team must remain patient in repeating some of the key messages. These presentations should be viewed as opportunities to refine

the key messages and evangelize the good work that was done. By this point in the process, the team has invested many hours of work and uncovered insights for the business. These presentations are an oppor-

tunity to communicate these projects and build support for future projects. As with most presentations, it is important to gauge the audience to guide shaping the message and the level of detail. Here are several more tips on developing the presentations.

• Use imagery and visual representat ions: Visuals tend to make the presentation more compelling. Also, people recall imagery better than words, because images can have a more visceral impact. These visual representations can be static and interactive data.

THE ENDGAME, OR PUTTING IT ALL TOGETHER

o Make sure the text is mutually exclusive and collectively exhaustive (MECE): This means having an economy of words in the presentation and making sure the key points are covered but not repeated unnecessarily.

o Measure and quantify the benefits ofthe project: This can be challenging and requires time and effort to do well. This kind of measurement should attempt to quantify benefits that have financial and other benefits in a specific way. Making the statement that a project provided "$8.5M in annual cost savings" is much more compelling than saying it has "great value."

o Make the benefits of the project clear and conspicuous: After calculating the benefits of the proj- ect, make sure to articulate them clearly in the presentation.

12.2.10 Providing Technical Specifications and Code In addition to authoring the final presentations, the team needs to deliver the actual code that was devel- oped and the technical documentation needed to support it. The team should consider how the project will affect the end users and the technical people who will need to implement the code.lt is recommended that the team think through the implications of its work on the recipients of the code, the kinds of questions they will have, and their interests. For instance, indicating that the model will need to perform real-time monitoring may require extensive changes to an IT runtime environment, so the team may need to consider a compromise of nightly batch jobs to process the data. In addition, the team may need to get the technical team talking with the project sponsor to ensure the implementation and SLA will meet the business needs during the technical deployment.

The team should anticipate questions from IT related to how computationally expensive it will be to run the model in the production environment. If possible, indicate how well the model ran in the test scenarios and whether there are opportunities to tune the model or environment to optimize performance in the production environment.

Teams should approach writing technical documentation for their code as if it were an application programming interface (API). Many times, the models become encapsulated as functions that read a set of inputs in the production environment, possibly perform preprocessing on data, and create an output, including a set of post-processing results.

Consider the inputs, outputs, and other system constraints to enable a technical person to implement the analytical model, even if this person has not had a connection to the data science project up to this point. Think about the documentation as a way to introduce the data that the model needs, the logic it is using, and how other related systems need to interact with it in a production environment for it to operate well. The specifications detail the inputs the code needs and the data format and structures. For instance, it may be useful to specify whether structured data is needed or whether the expected data needs to be numeric or string formats. Describe any transformations that need to be made on the input data before the code can use it, and if scripting was created to perform these tasks. These kinds of details are important when other engineers must modify the code or utilize a different dataset or table, if and when the environment changes.

Regarding exception handling, the team must consider how the code should handle data that is outside the expected data ranges of the model parameters and how it will handle missing data values (Chapter 3, "Review of Basic Data Analytic Methods Using R"), null values, zeros, NAs, or data that is in an unexpected format or type. The technical documentation describes how to treat these exceptions and what implications may emerge on downstream processes. For the model outputs, the team must explain to what extent to post-process the output. For example, if the model returns a value representing

1 2.3 Data Visua lization Basics

the probability of customer churn, additional logic may be needed to identify the scoring threshold to

determine which customer accounts to flag as being at risk of churn. In addition, some provision should be made for adjusting this threshold and training the algorithm, either in an automated learning fashion or with human intervention.

Although the team must create technical documentation, many times engineers and other technical staff receive the code and may try to use it without reading through all the documentation. Therefore, it is

important to add extensive comments in the code. Th is directs the people implementing the code on how to use it, explains what pieces of the logic are supposed to do, and guides other people through the code until they're fam iliar with it. If the team can do a thorough job adding comments in the code, it is much

easier for someone else to maintain the code and tune it in the runtime environment. In addition, it helps

the engineers edit the code when their environment changes or they need to modify processes that may be providing inputs to the code or receiving its outputs.

12.3 Data Visualization Basics As the volume of data continues to increase, more vendors and communities are developing tools to create clear and impactful graphics for use in presentations and appl ications. Although not exhaustive, Table 12-21ists some popular tools.

TABLE 12 ·2 Common Tools for Data Visualization

Open Source Commercial Tools

R (Base package, lattice, ggplot2)

GGobi/Rggobi

Gnuplot

lnkscape

Modest Maps

Open l ayers

Processing

03.js

Weave

Tableau

Spotfire (TIBCO)

QlikView

Adobe Illustrator

As the volume and complexity of data has grown, users have become more reliant on using crisp visuals to illustrate key ideas and portray rich data in a simple way. Over time, the open source community has

developed many libraries to offer more options for portraying graphics data visually. Although th is book showed examples primarily using the base package ofR, ggpl ot2 provides additional options for creat- ing professional-looking data visualization, as does the l attice library for R.

Gnuplot and GGobi have a command-line-driven approach to generating data visualization. The genesis of these tools mainly grew out of scientific computing and the need to express complex data visually. GGobi

THE ENDGAME, OR PUTTING IT ALL TOGETHER

also has a variant called Rggobi that enables users to access the GGobi functionality with the R software

and programming language. There are many open source mapping tools available, including Modest Maps and OpenLayers, both designed for developers who would like to create interactive maps and embed them within their own development projects or on the web. The software programming language develop-

ment environment, Processing, employs a Java-like language for developers to create professional-looking

data visualization. Because it is based on a programming language rather than a GUI, Processing enables developers to create robust visua lization and have precise control over the output. D3.js is a JavaScript library for manipulating data and creating web-based visualization with standards, such as Hypertext

Markup Language (HTML), Scalable Vector Graphics (SVG), and Cascading Style Sheets (CSS). For more examples of using open source visualization tools, refer to Nathan Yau's website, flowingdata.com [1), or his book Visualize This [2]. wh ich discusses additional methods for creating data representations with

open source tools.

Regarding the commercial tools shown in Table 12-2, Tableau, Spot fire (by TIBCO), and QlikView function as data visualization tools and as interactive business intelligence (BI) tools. Due to the growth of data in the past few years, organizations for the first time are beginning to place more emphasis on ease of use and

visualization in Bl over more traditional Bl tools and databases. These tools make visualization easy and have

user interfaces that are cleaner and simpler to navigate than their predecessors. Although not traditionally considered a data visualization tool, Adobe Illustrator is listed in Table 12-2 because some professionals use it to enhance visualization made in other tools. For example, some users develop a simple data visualization

in R, save the image as a PDF or JPEG, and then use a tool such as Illustrator to enhance the quality of the graphic or stitch multiple visualization work into an infographic. lnkscape is an open source tool used for similar use cases, with much of Illustrator's functiona lity.

12.3.1 Key Points Supported with Data It is more difficult to observe key insights when data is in tables instead of in charts. To underscore th is point, in Say it w ith Charts, Gene Zelazny [3) mentions that to highlight data, it is best to create a visual

representation out of it, such as a chart, graph, or other data visualization. The opposite is also true. Suppose an analyst chooses to downplay the data. Sharing it in a table draws less attention to it and makes it more difficult for people to digest.

The way one chooses to organize the visual in terms of the color scheme, labels, and sequence of information also influences how the viewer processes the information and what he perceives as the key message from the chart. The table shown in Figure 12-16 contains many data points. Given the layout of

the information, it is difficult to identify the key points at a glance. Looking at 45 years of store opening data can be challenging, as shown in Figure 12-16.

~10-o 1 I I ~ C 4 IC 1l lot 20 t• tl' 29 24 )7 JJ 117 41 M 19 11 10 91 11 16 106 7'1 61 61 &() «9 2l 26 ll C1 11 71 67 64 11 91 Jl 1