Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
4798 lines (4798 sloc) 206.356 kb
{
"metadata": {
"name": "",
"signature": "sha256:f066be0cc350e6372bbdb872eb18175b0f4453d758f4206d4d337a6a9f7e6fde"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Python for Data Science"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Joe McCarthy](http://interrelativity.com/joe), \n",
"*Director, Analytics & Data Science*, [Atigeo, LLC](http://atigeo.com)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.display import display, Image, HTML"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"1. Introduction"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"http://www.python.org/\"><img src=\"https://www.python.org/static/community_logos/python-logo.png\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"Python\" alt=\"python-logo-master-v3-TM.png\" /></a>\n",
"This short primer on [Python](http://www.python.org/) is designed to provide a rapid \"on-ramp\" to enable computer programmers who are already familiar with concepts and constructs in other programming languages learn enough about Python to facilitate the effective use of open-source and proprietary Python-based machine learning and data science tools.\n",
"\n",
"<a href=\"http://www.nltk.org/book/\"><img src=\"http://covers.oreilly.com/images/9780596516499/cat.gif\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"The Natural Language Toolkit (NLTK) Book\" alt=\"nltk_book_cover.gif\" /></a>\n",
"The primer is motivated, in part, by the approach taken in the [Natural Language Toolkit (NLTK) book](http://www.nltk.org/book/), which provides a rapid on-ramp for using Python and the open-source [NLTK library](http://www.nltk.org/) to develop programs using natural language processing techniques (many of which involve [machine learning](http://www.nltk.org/book/ch06.html)).\n",
"\n",
"The [Python Tutorial](http://docs.python.org/2/tutorial/) offers a more comprehensive primer, and opens with an excellent - if biased - overview of some of the general strengths of the Python programming language:\n",
"\n",
"> Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python\u2019s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.\n",
"\n",
"<a href=\"http://www.amazon.com/Python-Scripting-Computational-Science-Engineering/dp/3642093159\"><img src=\"https://images.springer.com/sgw/books/medium/9783540739159.jpg\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"Python Scripting for Computational Science, by Hans Petter Langtangen\" alt=\"Python Scripting for Computational Science cover\" /></a>\n",
"[Hans Petter Langtangen](http://folk.uio.no/hpl/), author of [Python Scripting for Computational Science](http://www.amazon.com/Python-Scripting-Computational-Science-Engineering/dp/3642093159), emphasizes the utility of Python for many of the common tasks in all areas of computational science:\n",
"\n",
"> Very often programming is about shuffling data in and out of different tools, converting one data format to another, extracting numerical data from a text, and administering numerical experiments involving a large number of data files and directories. Such tasks are much faster to accomplish in a language like Python than in Fortran, C, C++, C#, or Java\n",
"\n",
"[Foster Provost](http://people.stern.nyu.edu/fprovost/), co-author of [Data Science for Business](http://data-science-for-biz.com/), describes why Python is such a useful programming language for practical data science in [Python: A Practical Tool for Data Science](https://docs.google.com/document/pub?id=1p6vowsEuiezLbWnFKgse70a8LxfsrRixqPF5nBg8F3A), :\n",
"\n",
"> The practice of data science involves many interrelated but different activities, including accessing data, manipulating data, computing statistics about data, plotting/graphing/visualizing data, building predictive and explanatory models from data, evaluating those models on yet more data, integrating models into production systems, etc. One option for the data scientist is to learn several different software packages that each specialize in one or two of these things, but don\u2019t do them all well, plus learn a programming language to tie them together. (Or do a lot of manual work.) \n",
"> \n",
"> An alternative is to use a general-purpose, high-level programming language that provides libraries to do all these things. Python is an excellent choice for this. It has a diverse range of open source libraries for just about everything the data scientist will do. It is available everywhere; high performance python interpreters exist for running your code on almost any operating system or architecture. Python and most of its libraries are both open source and free. Contrast this with common software packages that are available in a course via an academic license, yet are extremely expensive to license and use in industry.\n",
"\n",
"<a href=\"http://scikit-learn.org/\"><img src=\"http://scikit-learn.org/stable/_static/scikit-learn-logo-small.png\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"scikit-learn: Machine Learning for Python\" alt=\"scikit-learn-logo-small.png\" /></a>\n",
"The goal of this primer is to provide efficient and sufficient scaffolding for software engineers with no prior knowledge of Python to be able to effectively use Python-based tools for data science research and development, such as the open-source library [scikit-learn](http://scikit-learn.org/). There is another, more comprehensive tutorial for scikit-learn, [Python Scientific Lecture Notes](http://scipy-lectures.github.io/index.html), that includes coverage of a number of other useful Python open-source libraries used by scikit-learn ([numpy](http://www.numpy.org/), [scipy](http://www.scipy.org/) and [matplotlib](http://matplotlib.org)) - all highly recommended ... and, to keep things simple, all beyond the scope of this primer.\n",
"\n",
"<a href=\"http://atigeo.com/technology/\"><img src=\"http://atigeo.com/wp-content/uploads/2013/05/xp-logo-forslider.png\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"xPatterns, by Atigeo\" alt=\"xp-logo-forslider.png\" /></a>\n",
"The initial motivation for this primer was a 2-hour training session for a group of experienced software engineers to learn enough Python to utilize the [Atigeo xPatterns analytics framework API](http://atigeo.com/technology/) in their software development work. I am grateful to the company for affording me the opportunity to develop this educational tool, and to make it freely available to others who might be looking for a fast on-ramp to Python for data science.\n",
"\n",
"Using an IPython Notebook as a delivery vehicle for this primer was motivated by Brian Granger's inspiring tutorial, [The IPython Notebook: Get Close to Your Data with Python and JavaScript](http://strataconf.com/strata2014/public/schedule/detail/32033), one of the [highlights from my Strata 2014 conference experience](http://gumption.typepad.com/blog/2014/02/ipython-deep-learning-doing-good-some-highlights-from-strata-2014.html).\n",
"\n",
"One final note on external resources: the [Python Style Guide (PEP-0008)](http://legacy.python.org/dev/peps/pep-0008/) offers helpful tips on how best to format Python code. [Code like a Pythonista](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html) offers a number of additional tips on Python programming style and philosophy, several of which are incorporated into this primer.\n",
"\n",
"We will focus entirely on using Python within the interpreter environment (as supported within an IPython Notebook). Python scripts - files containing definitions of functions and variables, and typically including code invoking some of those functions - can also be run from a command line. Using Python scripts from the command line may be the subject of a future primer. \n",
"\n",
"To help motivate the data science-oriented Python programming examples provided in this primer, we will start off with a brief overview of basic concepts and terminology in data science."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"2. Data Science: Basic Concepts"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Data Science and Data Mining"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"http://data-science-for-biz.com/\"><img src=\"http://akamaicovers.oreilly.com/images/0636920028918/cat.gif\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"Data Science for Business, by Provost and Fawcett\" alt=\"DataScienceForBusiness_cover.jpg\" /></a>\n",
"Foster Provost and [Tom Fawcett](http://home.comcast.net/~tom.fawcett/public_html/index.html) offer succinct descriptions of data science and data mining in [Data Science for Business](http://data-science-for-biz.com/):\n",
"\n",
"> **Data science** involves principles, processes and techniques for understanding phenomena via the (automated) analysis of data.\n",
"> \n",
"> **Data mining** is the extraction of knowledge from data, via technologies that incorporate these principles."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Knowledge Discovery, Data Mining and Machine Learning"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Provost & Fawcett also offer some history and insights into the relationship between *data mining* and *machine learning*, terms which are often used somewhat interchangeably:\n",
"\n",
"> The field of Data Mining (or KDD: Knowledge Discovery and Data Mining) started as an offshoot of Machine Learning, and they remain closely linked. Both fields are concerned with the analysis of data to find useful or informative patterns. Techniques and algorithms are shared between the two; indeed, the areas are so closely related that researchers commonly participate in both communities and transition between them seamlessly. Nevertheless, it is worth pointing out some of the differences to give perspective.\n",
"> \n",
">Speaking generally, because Machine Learning is concerned with many types of performance improvement, it includes subfields such as robotics and computer vision that are not part of KDD. It also is concerned with issues of agency and cognition \u2014 how will an intelligent agent use learned knowledge to reason and act in its environment \u2014 which are not concerns of Data Mining.\n",
"> \n",
">Historically, KDD spun off from Machine Learning as a research field focused on concerns raised by examining real-world applications, and a decade and a half later the KDD community remains more concerned with applications than Machine Learning is. As such, research focused on commercial applications and business issues of data analysis tends to gravitate toward the KDD community rather than to Machine Learning. KDD also tends to be more concerned with the entire process of data analytics: data preparation, model learning, evaluation, and so on.\n"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Cross Industry Standard Process for Data Mining (CRISP-DM)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [Cross Industry Standard Process for Data Mining](https://en.wikipedia.org/wiki/Cross_Industry_Standard_Process_for_Data_Mining) introduced a process model for data mining in 2000 that has become widely adopted.\n",
"\n",
"<a href=\"https://en.wikipedia.org/wiki/Cross_Industry_Standard_Process_for_Data_Mining\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/b/b9/CRISP-DM_Process_Diagram.png/479px-CRISP-DM_Process_Diagram.png\" title=\"Cross Industry Standard Process for Data Mining\" alt=\"CRISP-DM_Process_Diagram\" /></a>\n",
"\n",
"The model emphasizes the ***iterative*** nature of the data mining process, distinguishing several different stages that are regularly revisited in the course of developing and deploying data-driven solutions to business problems:\n",
"\n",
"* Business understanding\n",
"* Data understanding\n",
"* Data preparation\n",
"* Modeling \n",
"* Deployment\n",
"\n",
"We will be focusing primarily on using Python for **data preparation** and **modeling**."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Data Science Workflow"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Philip Guo](http://www.pgbovine.net/) presents a [Data Science Workflow](http://cacm.acm.org/blogs/blog-cacm/169199-data-science-workflow-overview-and-challenges/fulltext) offering a slightly different process model emhasizing the importance of **reflection** and some of the meta-data, data management and bookkeeping challenges that typically arise in the data science process. His 2012 PhD thesis, [Software Tools to Facilitate Research Programming](http://pgbovine.net/projects/pubs/guo_phd_dissertation.pdf), offers an insightful and more comprehensive description of many of these challenges.\n",
"\n",
"<a href=\"http://cacm.acm.org/blogs/blog-cacm/169199-data-science-workflow-overview-and-challenges/fulltext\"><img src=\"http://cacm.acm.org/system/assets/0001/3678/rp-overview.jpg\" title=\"Data Science Workflow, by Philip Guo\" alt=\"pguo-data-science-overview.jpg\" style=\"width: 500px\" /></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Provost & Fawcett list a number of different tasks in which data science techniques are employed:\n",
"\n",
"* Classification and class probability estimation \n",
"* Regression (aka value estimation) \n",
"* Similarity matching \n",
"* Clustering \n",
"* Co-occurrence grouping (aka frequent itemset mining, association rule discovery, market-basket analysis) \n",
"* Profiling (aka behavior description, fraud / anomaly detection) \n",
"* Link prediction \n",
"* Data reduction \n",
"* Causal modeling \n",
"\n",
"We will be focusing primarily on **classification** and **class probability estimation** tasks, which are defined by Provost & Fawcett as follows:\n",
"\n",
"> *Classification* and *class probability estimation* attempt to predict, for each individual in a population, which of a (small) set of classes this individual belongs to. Usually the classes are mutually exclusive. An example classification question would be: \u201cAmong all the customers of MegaTelCo, which are likely to respond to a given offer?\u201d In this example the two classes could be called will respond and will not respond.\n",
"\n",
"To further simplify this primer, we will focus exclusively on **supervised** methods, in which the data is explicitly labeled with classes. There are also *unsupervised* methods that involve working with data in which there are no pre-specified class labels."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Supervised Classification"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [Natural Language Toolkit (NLTK) book](http://www.nltk.org/book) provides a diagram and succinct description (below, with italics and bold added for emphasis) of supervised classification:\n",
"\n",
"<a href=\"http://www.nltk.org/book/ch06.html\"><img src=\"http://www.nltk.org/images/supervised-classification.png\" title=\"Supervised Classification, from NLTK book, Chapter 6\" alt=\"nltk_ch06_supervised-classification.png\" style=\"width: 500px\" /></a>\n",
"\n",
"> *Supervised Classification*. (a) During *training*, a **feature extractor** is used to convert each **input value** to a **feature set**. These feature sets, which capture the basic information about each input that should be used to classify it, are discussed in the next section. Pairs of feature sets and **labels** are fed into the **machine learning algorithm** to generate a **model**. (b) During *prediction*, the same feature extractor is used to convert **unseen inputs** to feature sets. These feature sets are then fed into the model, which generates **predicted labels**."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Data Mining Terminology"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* **Structured** data has simple, well-defined patterns (e.g., a table or graph)\n",
"* **Unstructured** data has less well-defined patterns (e.g., text, images)\n",
"* **Model**: a pattern that captures / generalizes regularities in data (e.g., an equation, set of rules, decision tree)\n",
"* **Attribute** (aka *variable*, *feature*, *signal*, *column*): an element used in a model\n",
"* **Example** (aka *instance*, *feature vector*, *row*): a representation of an entity being modeled\n",
"* **Target attribute** (aka *dependent variable*, *class label*): the class / type / category of an entity being modeled"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Data Mining Example: UCI Mushroom dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [Center for Machine Learning and Intelligent Systems](http://cml.ics.uci.edu/) at the University of California, Irvine (UCI), hosts a [Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets.html) containing over 200 publicly available data sets.\n",
"\n",
"<a href=\"https://archive.ics.uci.edu/ml/datasets/Mushroom\"><img src=\"https://archive.ics.uci.edu/ml/assets/MLimages/Large73.jpg\" style=\"margin: 0px 0px 5px 20px; width: 125px; float: right;\" title=\"Mushrooms from Agaricus and Lepiota Family\" alt=\"mushroom\"/></a>\n",
"We will use the [mushroom](https://archive.ics.uci.edu/ml/datasets/Mushroom) data set, which forms the basis of several examples in Chapter 3 of the Provost & Fawcett data science book.\n",
"\n",
"The following description of the dataset is provided at the UCI repository:\n",
"\n",
">This data set includes descriptions of hypothetical samples corresponding to 23 species of gilled mushrooms in the Agaricus and Lepiota Family (pp. 500-525 [The Audubon Society Field Guide to North American Mushrooms, 1981]). Each species is identified as definitely edible, definitely poisonous, or of unknown edibility and not recommended. This latter class was combined with the poisonous one. The Guide clearly states that there is no simple rule for determining the edibility of a mushroom; no rule like leaflets three, let it be'' for Poisonous Oak and Ivy.\n",
"> \n",
"> **Number of Instances**: 8124\n",
"> \n",
"> **Number of Attributes**: 22 (all nominally valued)\n",
"> \n",
"> **Attribute Information**: (*classes*: edible=e, poisonous=p)\n",
"> \n",
"> 1. *cap-shape*: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s\n",
"> 2. *cap-surface*: fibrous=f, grooves=g, scaly=y, smooth=s\n",
"> 3. *cap-color*: brown=n ,buff=b, cinnamon=c, gray=g, green=r, pink=p, purple=u, red=e, white=w, yellow=y\n",
"> 4. *bruises?*: bruises=t, no=f\n",
"> 5. *odor*: almond=a, anise=l, creosote=c, fishy=y, foul=f, musty=m, none=n, pungent=p, spicy=s\n",
"> 6. *gill-attachment*: attached=a, descending=d, free=f, notched=n\n",
"> 7. *gill-spacing*: close=c, crowded=w, distant=d\n",
"> 8. *gill-size*: broad=b, narrow=n\n",
"> 9. *gill-color*: black=k, brown=n, buff=b, chocolate=h, gray=g, green=r, orange=o, pink=p, purple=u, red=e, white=w, yellow=y\n",
"> 10. *stalk-shape*: enlarging=e, tapering=t\n",
"> 11. *stalk-root*: bulbous=b, club=c, cup=u, equal=e, rhizomorphs=z, rooted=r, missing=?\n",
"> 12. *stalk-surface-above-ring*: fibrous=f, scaly=y, silky=k, smooth=s\n",
"> 13. *stalk-surface-below-ring*: fibrous=f, scaly=y, silky=k, smooth=s\n",
"> 14. *stalk-color-above-ring*: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y\n",
"> 15. *stalk-color-below-ring*: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y\n",
"> 16. *veil-type*: partial=p, universal=u\n",
"> 17. *veil-color*: brown=n, orange=o, white=w, yellow=y\n",
"> 18. *ring-number*: none=n, one=o, two=t\n",
"> 19. *ring-type*: cobwebby=c, evanescent=e, flaring=f, large=l, none=n, pendant=p, sheathing=s, zone=z\n",
"> 20. *spore-print-color*: black=k, brown=n, buff=b, chocolate=h, green=r, orange=o, purple=u, white=w, yellow=y\n",
"> 21. *population*: abundant=a, clustered=c, numerous=n, scattered=s, several=v, solitary=y\n",
"> 22. *habitat*: grasses=g, leaves=l, meadows=m, paths=p, urban=u, waste=w, woods=d\n",
"> \n",
"> **Missing Attribute Values**: 2480 of them (denoted by \"?\"), all for attribute #11.\n",
"> \n",
"> **Class Distribution**: -- edible: 4208 (51.8%) -- poisonous: 3916 (48.2%) -- total: 8124 instances\n",
"\n",
"The [data file](https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data) associated with this dataset has one instance of a hypothetical mushroom per line, with abbreviations for the values of the class and each of the other 22 attributes separated by commas.\n",
"\n",
"Here is a sample line from the data file:\n",
"\n",
"p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n",
"\n",
"This instance represents a mushroom with the following attribute values:\n",
"\n",
"*class*: edible=e, **poisonous=p**\n",
"\n",
"1. *cap-shape*: bell=b, conical=c, convex=x, flat=f, **knobbed=k**, sunken=s\n",
"2. *cap-surface*: **fibrous=f**, grooves=g, scaly=y, smooth=s\n",
"3. *cap-color*: **brown=n** ,buff=b, cinnamon=c, gray=g, green=r, pink=p, purple=u, red=e, white=w, yellow=y\n",
"4. *bruises?*: bruises=t, **no=f**\n",
"5. *odor*: almond=a, anise=l, creosote=c, fishy=y, foul=f, musty=m, **none=n**, pungent=p, spicy=s\n",
"6. *gill-attachment*: attached=a, descending=d, **free=f**, notched=n\n",
"7. *gill-spacing*: **close=c**, crowded=w, distant=d\n",
"8. *gill-size*: broad=b, **narrow=n**\n",
"9. *gill-color*: black=k, brown=n, buff=b, chocolate=h, gray=g, green=r, orange=o, pink=p, purple=u, red=e, **white=w**, yellow=y\n",
"10. *stalk-shape*: **enlarging=e**, tapering=t\n",
"11. *stalk-root*: bulbous=b, club=c, cup=u, equal=e, rhizomorphs=z, rooted=r, **missing=?**\n",
"12. *stalk-surface-above-ring*: fibrous=f, scaly=y, **silky=k**, smooth=s\n",
"13. *stalk-surface-below-ring*: fibrous=f, **scaly=y**, silky=k, smooth=s\n",
"14. *stalk-color-above-ring*: brown=n, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, **white=w**, yellow=y\n",
"15. *stalk-color-below-ring*: **brown=n**, buff=b, cinnamon=c, gray=g, orange=o, pink=p, red=e, white=w, yellow=y\n",
"16. *veil-type*: **partial=p**, universal=u\n",
"17. *veil-color*: brown=n, orange=o, **white=w**, yellow=y\n",
"18. *ring-number*: none=n, **one=o**, two=t\n",
"19. *ring-type*: cobwebby=c, **evanescent=e**, flaring=f, large=l, none=n, pendant=p, sheathing=s, zone=z\n",
"20. *spore-print-color*: black=k, brown=n, buff=b, chocolate=h, green=r, orange=o, purple=u, **white=w**, yellow=y\n",
"21. *population*: abundant=a, clustered=c, numerous=n, scattered=s, **several=v**, solitary=y\n",
"22. *habitat*: grasses=g, leaves=l, meadows=m, paths=p, urban=u, waste=w, **woods=d**\n",
"\n",
"Building a model with this data set will serve as a motivating example throughout much of this primer."
]
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"3. Python: Basic Concepts"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"A note on Python 2 vs. Python 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are 2 major versions of Python in widespread use: [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/). Python 3 has some features that are not backward compatible with Python 2, and some Python 2 libraries have not been updated to work with Python 3. I have been using Python 2, primarily because I use some of those Python 2[-only] libraries, but an increasing proportion of them are migrating to Python 3, and I anticipate shifting to Python 3 in the near future.\n",
"\n",
"For more on the topic, I recommend a very well documented IPython Notebook, which includes numerous helpful examples and links, by [Sebastian Raschka](http://sebastianraschka.com/), [Key differences between Python 2.7.x and Python 3.x](http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/key_differences_between_python_2_and_3.ipynb), the [Cheat Sheet: Writing Python 2-3 compatible code](http://python-future.org/compatible_idioms.html) by Ed Schofield ... or [googling Python 2 vs 3](https://www.google.com/q=python%202%20vs%203).\n",
"\n",
"[Nick Coghlan](https://twitter.com/ncoghlan_dev), a CPython core developer, sent me an email suggesting that relatively minor changes in this notebook would enable it to run with Python 2 *or* Python 3: importing the `print_function` from the [**`__future__`**](https://docs.python.org/2/library/__future__.html) module, and changing my [`print` *statements* (Python 2)](https://docs.python.org/2/reference/simple_stmts.html#print) to [`print` *function calls* (Python 3)](https://docs.python.org/3/library/functions.html#print). Although a relatively minor conceptual change, it necessitated the changing of many individual cells to reflect the Python 3 `print` syntax. I also needed to replace a few functions that are no longer available in Python 3 with related functions that are available in both versions; I've added notes in nearby cells where the incompatible functions were removed explaining why they are related ... and no longer available."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from __future__ import print_function, division"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Identifiers, strings, lists and tuples"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The sample instance of a mushroom shown above can be represented as a string. A Python *string* ([**`str`**](http://docs.python.org/2/tutorial/introduction.html#strings)) is a sequence of 0 or more characters enclosed within a pair of single quotes (`'`) or a pair double quotes (`\"`). "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 3,
"text": [
"'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'"
]
}
],
"prompt_number": 3
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python [*identifiers*](http://docs.python.org/2/reference/lexical_analysis.html#identifiers) (or [*names*](https://docs.python.org/2/reference/executionmodel.html#naming-and-binding)) are composed of letters, numbers and/or underscores ('`_`'), starting with a letter or underscore. Python identifiers are case sensitive. Although camelCase identifiers can be used, it is generally considered more [pythonic](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html) to use underscores. Python variables and functions typically start with lowercase letters; Python classes start with uppercase letters.\n",
"\n",
"The following [assignment statement](http://docs.python.org/2/reference/simple_stmts.html#assignment-statements) binds the value of the string shown above to the name `single_instance_str`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"single_instance_str = 'p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`print`**](https://docs.python.org/3/library/functions.html#print) function writes the value of its comma-delimited arguments to [**`sys.stdout`**](http://docs.python.org/2/library/sys.html#sys.stdout) (typically the console). Each value in the output is separated by a single blank space. If an **`end`** argument that does not include `\\n` (newline character) is supplied, the output cursor will not move to the next line."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Instance 1:', single_instance_str)\n",
"print('A', 'B', end=' ') # use a space rather than newline at the end of the line\n",
"print('C') # will appear on same line"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Instance 1: p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n",
"A B C\n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python comment character is **`'#'`**: anything after `'#'` on the line is ignored by the Python interpreter. \n",
"\n",
"Pairs of triple quotes (**`'''`** or **`\"\"\"`**) can be used to delimit multi-line comments."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"'''\n",
"A multi-line\n",
"comment\n",
"'''\n",
"print('no comment')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"no comment\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A [**`list`**](http://docs.python.org/2/tutorial/introduction.html#lists) is an ordered sequence of 0 or more comma-delimited elements enclosed within square brackets ('`[`', '`]`'). The Python [**`str.split(sep)`**](http://docs.python.org/2/library/stdtypes.html#str.split) method can be used to split a `sep`-delimited string into a corresponding list of elements."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"single_instance_list = single_instance_str.split(',')\n",
"print(single_instance_list)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd']\n"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python sequences are *heterogeneous*, i.e., they can contain elements of different types."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"mixed_list = ['a', 1, 2.3, True, [1, 'b']]\n",
"print(mixed_list)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['a', 1, 2.3, True, [1, 'b']]\n"
]
}
],
"prompt_number": 8
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python **`+`** operator can be used to concatenate lists."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"concatenated_list = ['a', 1] + [2.3, True] + [[1, 'b']]\n",
"print(concatenated_list)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['a', 1, 2.3, True, [1, 'b']]\n"
]
}
],
"prompt_number": 9
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Individual elements of [*sequences*](http://docs.python.org/2/library/stdtypes.html#typesseq) (lists, strings and other data structures) can be accessed by specifying their zero-based index position within square brackets ('`[`', '`]`')."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str[2], single_instance_list[2])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"k f\n"
]
}
],
"prompt_number": 10
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Negative index values can be used to specify a position offset from the end of the sequence. It is often useful to use a `-1` index value to access the last element of a sequence."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str[-1], single_instance_list[-1])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"d d\n"
]
}
],
"prompt_number": 11
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python *slice notation* can be used to access subsequences by specifying two index positions separated by a colon (':'); `seq[start:stop]` returns all the elements in `seq` between `start` and `stop - 1` (inclusive)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str[2:4])\n",
"print(single_instance_list[2:4])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"k,\n",
"['f', 'n']\n"
]
}
],
"prompt_number": 12
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Slices indices can be negative values."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str[-4:-2])\n",
"print(single_instance_list[-4:-2])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
",v\n",
"['e', 'w']\n"
]
}
],
"prompt_number": 13
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `start` and/or `stop` index can be omitted. A common use of slices with a single index value is to access all but the first element or all but the last element of a sequence."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str[:-1]) # all but the last\n",
"print(single_instance_list[:-1])\n",
"print(single_instance_str[1:]) # all but the first\n",
"print(single_instance_list[1:])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,\n",
"['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v']\n",
",k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n",
"['k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd']\n"
]
}
],
"prompt_number": 14
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Slice notation includes an optional third element, `step`, as in `seq[start:stop:step]`, that specifies the steps or increments by which elements are retrieved from `seq` between `start` and `step - 1`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str)\n",
"print(single_instance_str[::2]) # print elements in even-numbered positions (the values, in this case)\n",
"print(single_instance_str[1::2]) # print elements in odd-numbered positions (the commas, in this case)\n",
"print(single_instance_str[::-1]) # reverse the string"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n",
"pkfnfnfcnwe?kywnpwoewvd\n",
",,,,,,,,,,,,,,,,,,,,,,\n",
"d,v,w,e,o,w,p,n,w,y,k,?,e,w,n,c,f,n,f,n,f,k,p\n"
]
}
],
"prompt_number": 15
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [Python tutorial](http://docs.python.org/2/tutorial/introduction.html) offers a helpful ASCII art representation to show how positive and negative indexes are interpreted:\n",
"\n",
"<pre>\n",
" +---+---+---+---+---+\n",
" | H | e | l | p | A |\n",
" +---+---+---+---+---+\n",
" 0 1 2 3 4 5\n",
"-5 -4 -3 -2 -1\n",
"</pre>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python statements are typically separated by newlines (rather than, say, the semi-colon in Java). Statements can extend over more than one line; it is generally best to break the lines after commas within parentheses, braces or brackets. Inserting a backslash character ('\\\\') at the end of a line will also enable continuation of the statement on the next line, but it is generally best to look for other alternatives."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute_names = ['class', \n",
" 'cap-shape', 'cap-surface', 'cap-color', \n",
" 'bruises?', \n",
" 'odor', \n",
" 'gill-attachment', 'gill-spacing', 'gill-size', 'gill-color', \n",
" 'stalk-shape', 'stalk-root', \n",
" 'stalk-surface-above-ring', 'stalk-surface-below-ring', \n",
" 'stalk-color-above-ring', 'stalk-color-below-ring',\n",
" 'veil-type', 'veil-color', \n",
" 'ring-number', 'ring-type', \n",
" 'spore-print-color', \n",
" 'population', \n",
" 'habitat']\n",
"print(attribute_names)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['class', 'cap-shape', 'cap-surface', 'cap-color', 'bruises?', 'odor', 'gill-attachment', 'gill-spacing', 'gill-size', 'gill-color', 'stalk-shape', 'stalk-root', 'stalk-surface-above-ring', 'stalk-surface-below-ring', 'stalk-color-above-ring', 'stalk-color-below-ring', 'veil-type', 'veil-color', 'ring-number', 'ring-type', 'spore-print-color', 'population', 'habitat']\n"
]
}
],
"prompt_number": 16
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`str.strip([chars]`**)](http://docs.python.org/2/library/stdtypes.html#str.strip) method returns a copy of `str` in which any leading or trailing `chars` are removed. If no `chars` are specified, it removes all leading and trailing whitespace. [*Whitespace* is any sequence of spaces, tabs (`'\\t'`) and/or newline (`'\\n'`) characters.] \n",
"\n",
"Note that since a blank space is inserted in the output after every item in a comma-delimited list, the last asterisk is printed after a leading blank space is inserted on the new line."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('*', '\\tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\\n', '*')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"* \tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n",
" *\n"
]
}
],
"prompt_number": 17
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('*', '\\tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\\n'.strip(), '*')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"* p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d *\n"
]
}
],
"prompt_number": 18
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A common programming pattern when dealing with CSV (comma-separated values) data files containing is to repeatedly\n",
"\n",
"1. read a line from a file\n",
"2. strip off any leading and trailing whitespace\n",
"3. split the values separated by commas into a list\n",
"\n",
"We will get to repetition control structures (loops) and file input and output shortly, but here is an example of how `str.strip()` and `str.split()` be chained together in a single instruction:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"single_instance_str = '\\tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\\n'\n",
"single_instance_list = single_instance_str.strip().split(',') # first strip leading & trailing whitespace, then split on commas\n",
"print(single_instance_list)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['p', 'k', 'f', 'n', 'f', 'n', 'f', 'c', 'n', 'w', 'e', '?', 'k', 'y', 'w', 'n', 'p', 'w', 'o', 'e', 'w', 'v', 'd']\n"
]
}
],
"prompt_number": 19
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`str.join(words)`**](http://docs.python.org/2/library/string.html#string.join) method is the inverse of `str.split()`, returning a single string in which each string in the sequence of `words` is separated by `str`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('*', ','.join(single_instance_list), '*')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"* p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d *\n"
]
}
],
"prompt_number": 20
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A number of Python methods can be used on strings, lists and other sequences.\n",
"\n",
"The [**`len(s)`**](http://docs.python.org/2/library/functions.html#len) function can be used to find the length of (number of items in) a sequence `s`. It will also return the number of items in a *dictionary*, a data structure we will cover further below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(len(single_instance_str), len(single_instance_list))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"47 23\n"
]
}
],
"prompt_number": 21
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The **`in`** operator can be used to determine whether a sequence contains a value. \n",
"\n",
"Boolean values in Python are **`True`** and **`False`** (note the capitalization)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(',' in single_instance_str, ',' in single_instance_list)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"True False\n"
]
}
],
"prompt_number": 22
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`s.count(x)`**](http://docs.python.org/2/library/stdtypes.html#str.count) ormethod can be used to count the number of occurrences of item `x` in sequence `s`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str.count(','), single_instance_list.count('f'))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"22 3\n"
]
}
],
"prompt_number": 23
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`s.index(x)`**](http://docs.python.org/2/library/stdtypes.html#str.index) method can be used to find the first 0-based index of item `x` in sequence `s`. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(single_instance_str.index(','), single_instance_list.index('f'))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"2 2\n"
]
}
],
"prompt_number": 24
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One important distinction between strings and lists has to do with their [*mutability*](http://docs.python.org/2/reference/datamodel.html).\n",
"\n",
"Python strings are *immutable*, i.e., they cannot be modified. Most string methods (like `str.strip()`) return modified *copies* of the strings on which they are used.\n",
"\n",
"Python lists are *mutable*, i.e., they can be modified. \n",
"\n",
"The examples below illustrate a number of [`list`](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists) methods that modify lists."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"list_1 = [4, 2, 3, 5, 1]\n",
"list_2 = list_1 # list_2 now references the same object as list_1\n",
"print('list_1: ', list_1)\n",
"print('list_2: ', list_2)\n",
"list_1.remove(1)\n",
"print('list_1.remove(1):', list_1)\n",
"list_1.append(6)\n",
"print('list_1.append(6):', list_1)\n",
"list_1.sort()\n",
"print('list_1.sort(): ', list_1)\n",
"list_1.reverse()\n",
"print('list_1.reverse():', list_1)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"list_1: [4, 2, 3, 5, 1]\n",
"list_2: [4, 2, 3, 5, 1]\n",
"list_1.remove(1): [4, 2, 3, 5]\n",
"list_1.append(6): [4, 2, 3, 5, 6]\n",
"list_1.sort(): [2, 3, 4, 5, 6]\n",
"list_1.reverse(): [6, 5, 4, 3, 2]\n"
]
}
],
"prompt_number": 25
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When more than one name (e.g., a variable) is bound to the same mutable object, changes made to that object are reflected in all names bound to that object. For example, in the second statement above, `list_2` is bound to the same object that is bound to `list_1`, namely, the list `[4, 2, 3, 5 1]`. All changes made to the object bound to `list_1` will thus be reflected in `list_2` (since they both reference the same object)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('list_1: ', list_1)\n",
"print('list_2: ', list_2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"list_1: [6, 5, 4, 3, 2]\n",
"list_2: [6, 5, 4, 3, 2]\n"
]
}
],
"prompt_number": 26
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are sorting and reversing functions, [`sorted()`](https://docs.python.org/2.7/library/functions.html#sorted) and [`reversed()`](https://docs.python.org/2.7/library/functions.html#reversed), that do not modify their arguments, and can thus be used on mutable or immutable objects. We will elaborate on each of these functions further below, but here are a couple of examples of how `sorted()` returns a sorted list of each element in its argument."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('sorted(list_1):', sorted(list_1)) # return a copy of list_1 in sorted order\n",
"print('list_1: ', list_1)\n",
"print('sorted(single_instance_str):', sorted(single_instance_str)) # returns a list of sorted elements in the string\n",
"print('single_instance_str: ', single_instance_str)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"sorted(list_1): [2, 3, 4, 5, 6]\n",
"list_1: [6, 5, 4, 3, 2]\n",
"sorted(single_instance_str): ['\\t', '\\n', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', ',', '?', 'c', 'd', 'e', 'e', 'f', 'f', 'f', 'k', 'k', 'n', 'n', 'n', 'n', 'o', 'p', 'p', 'v', 'w', 'w', 'w', 'w', 'y']\n",
"single_instance_str: \tp,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d\n",
"\n"
]
}
],
"prompt_number": 27
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A [*tuple*](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) is an ordered, immutable sequence of 0 or more comma-delimited values enclosed in parentheses (`'('`, `')'`). Many of the functions that operate on strings and lists also operate on tuples."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = (1, 2, 3, 4, 5) # a tuple\n",
"print('x =', x, ', len(x) =', len(x), ', x.index(3) =', x.index(3), ', x[4:2:-1] = ', x[4:2:-1])\n",
"print('sorted(x, reverse=True):', sorted(x, reverse=True)) # sorted always returns a list; reverse=True specifies reverse sort order"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x = (1, 2, 3, 4, 5) , len(x) = 5 , x.index(3) = 2 , x[4:2:-1] = (5, 4)\n",
"sorted(x, reverse=True): [5, 4, 3, 2, 1]\n"
]
}
],
"prompt_number": 28
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If the `s.index(x)` or `list.remove(x)` method is used on a sequence `s` or `list` that does not contain the value `x`, a [`ValueError`](http://docs.python.org/2/library/exceptions.html#exceptions.ValueError) exception is raised."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(x.index(6)) # a ValueError will be raised"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "ValueError",
"evalue": "tuple.index(x): x not in tuple",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-29-553ddc490596>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# a ValueError will be raised\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: tuple.index(x): x not in tuple"
]
}
],
"prompt_number": 29
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Conditionals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One common approach to handling errors is to *look before you leap (LBYL)*, i.e., test for potential [exceptions](http://docs.python.org/2/tutorial/errors.html) before executing instructions that might raise those exceptions. \n",
"\n",
"This approach can be implemented using the [**`if`**](http://docs.python.org/2/tutorial/controlflow.html#if-statements) statement (which may optionally include an **`else`** and any number of **`elif`** clauses).\n",
"\n",
"The following is a simple example of an `if` statement:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class_value = 'e' # try changing this to 'p' or 'x'\n",
"\n",
"if class_value == 'e':\n",
" print('edible')\n",
"elif class_value == 'p':\n",
" print('poisonous')\n",
"else:\n",
" print('unknown')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"edible\n"
]
}
],
"prompt_number": 30
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that \n",
"\n",
"* a colon ('`:`') is used at the end of the lines with `if`, `else` or `elif`\n",
"* no parentheses are required to enclose the boolean condition (it is presumed to include everything between `if` or `elif` and the colon)\n",
"* the statements below each `if`, `elif` and `else` line are all indented\n",
"\n",
"Python does not have special characters to delimit statement blocks (like the '{' and '}' delimiters in Java); instead, sequences of statements with the same *indentation level* are treated as a statement block. The [Python Style Guide](http://legacy.python.org/dev/peps/pep-0008/) recommends using 4 spaces for each indentation level.\n",
"\n",
"An `if` statement can be used to follow the LBYL paradigm in preventing the `ValueError` that occured in an earlier example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute = 'bruises' # try substituting 'bruises?' for 'bruises' and re-running this code\n",
"\n",
"if attribute in attribute_names:\n",
" i = attribute_names.index(attribute)\n",
" print(attribute, 'is in position', i)\n",
"else:\n",
" print(attribute, 'is not in', attribute_names)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"bruises is not in ['class', 'cap-shape', 'cap-surface', 'cap-color', 'bruises?', 'odor', 'gill-attachment', 'gill-spacing', 'gill-size', 'gill-color', 'stalk-shape', 'stalk-root', 'stalk-surface-above-ring', 'stalk-surface-below-ring', 'stalk-color-above-ring', 'stalk-color-below-ring', 'veil-type', 'veil-color', 'ring-number', 'ring-type', 'spore-print-color', 'population', 'habitat']\n"
]
}
],
"prompt_number": 31
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another perspective on handling errors championed by some pythonistas is that it is [*easier to ask forgiveness than permission (EAFP)*](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl).\n",
"\n",
"As in many practical applications of philosophy, religion or dogma, it is helpful to *think before you choose (TBYC)*. There are a number of factors to consider in deciding whether to follow the EAFP or LBYL paradigm, including code readability and the anticipated likelihood and relative severity of encountering an exception. Oran Looney wrote a blog post providing a nice overview of the debate over [LBYL vs. EAFP](http://oranlooney.com/lbyl-vs-eafp/).\n",
"\n",
"We will follow the LBYL paradigm throughout most of this primer. However, as an illustration of EAFP in Python, here is an alternate implementation of the functionality of the code above, using a [**`try/except`**](http://docs.python.org/2/tutorial/errors.html#handling-exceptions) statement."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute = 'bruises' # try substituting 'bruises?' for 'bruises' and re-running this code\n",
"\n",
"try:\n",
" i = attribute_names.index(attribute)\n",
" print(attribute, 'is in position', i)\n",
"except ValueError:\n",
" print(attribute, 'is not found')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"bruises is not found\n"
]
}
],
"prompt_number": 32
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python *null object* is **`None`** (note the capitalization)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute = 'bruises?'\n",
"\n",
"if attribute not in attribute_names: # equivalent to 'not attribute in attribute_names'\n",
" value = None\n",
"else:\n",
" i = attribute_names.index(attribute)\n",
" value = single_instance_list[i]\n",
" \n",
"print(attribute, '=', value)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"bruises? = f\n"
]
}
],
"prompt_number": 33
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Defining and calling functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python [*function definitions*](http://docs.python.org/2/tutorial/controlflow.html#defining-functions) start with the **`def`** keyword followed by a function name, a list of 0 or more comma-delimited *parameters* (aka 'formal parameters') enclosed within parentheses, and then a colon ('`:`'). \n",
"\n",
"A function definition may include one or more [**`return`**](http://docs.python.org/2/reference/simple_stmts.html#the-return-statement) statemens to indicate the value(s) returned to where the function is called. It is good practice to include a short [docstring](http://docs.python.org/2/tutorial/controlflow.html#tut-docstrings) to briefly describe the behavior of the function and the value(s) it returns."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def attribute_value(instance, attribute, attribute_names):\n",
" '''Returns the value of attribute in instance, based on the position of attribute in the list of attribute_names'''\n",
" if attribute not in attribute_names:\n",
" return None\n",
" else:\n",
" i = attribute_names.index(attribute)\n",
" return instance[i] # using the parameter name here"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 34
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A *function call* starts with the function name, followed by a list of 0 or more comma-delimited *arguments* (aka 'actual parameters') enclosed within parentheses. A function call can be used as a statement or within an expression."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute = 'cap-shape' # try substituting any of the other attribute names shown above\n",
"print(attribute, '=', attribute_value(single_instance_list, attribute, attribute_names))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"cap-shape = k\n"
]
}
],
"prompt_number": 35
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that Python does not distinguish between names used for *variables* and names used for *functions*. An assignment statement binds a value to a name; a function definition also binds a value to a name. At any given time, the value most recently bound to a name is the one that is used. \n",
"\n",
"The [**`type(object)`**](http://docs.python.org/2.7/library/functions.html#type) function returns the `type` of `object`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = 0\n",
"print('x used as a variable:', x, type(x))\n",
"\n",
"def x():\n",
" print('x')\n",
" \n",
"print('x used as a function:', x, type(x))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x used as a variable: 0 <type 'int'>\n",
"x used as a function: <function x at 0x1050076e0> <type 'function'>\n"
]
}
],
"prompt_number": 36
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another way to determine the `type` of an object is to use [**`isinstance(object, class)`**](https://docs.python.org/2/library/functions.html#isinstance). This is generally [preferable](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python), as it takes into account [class inheritance](https://docs.python.org/2/tutorial/classes.html#inheritance). There is a larger issue of [*duck typing*](https://en.wikipedia.org/wiki/Duck_typing), and whether code should ever explicitly check for the type of an object, but we will omit further discussion of the topic in this notebook.\n",
"\n",
"Checking whether an object is a `function` type will require the use of the `types` library ... and more [thorough checking](http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function/624948#624948) could be done if one wants to include built-in as well as user-defined functions."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import types\n",
"\n",
"x = 0\n",
"print('Is x an int?', isinstance(x, int))\n",
"print('Is x a function?', isinstance(x, types.FunctionType))\n",
"\n",
"def x():\n",
" print('x')\n",
" \n",
"print('Is x an int?', isinstance(x, int))\n",
"print('Is x a function?', isinstance(x, types.FunctionType))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Is x an int? True\n",
"Is x a function? False\n",
"Is x an int? False\n",
"Is x a function? True\n"
]
}
],
"prompt_number": 37
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another important feature of Python functions is that arguments are passed using [*call by sharing*](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing). If a *mutable* object is passed as an argument to a function parameter, assignment statements using that parameter do not affect the passed argument, however mutations to the parameter do affect the passed argument.\n",
"\n",
"Not being aware of - or forgetting - this important distinction can lead to challenging debugging sessions. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def modify_parameters(parameter1, parameter2):\n",
" '''Inserts \"x\" at the head of parameter1, assigns \"x\" to parameter2'''\n",
" parameter1.insert(0, 'x')\n",
" print('parameter1, after inserting \"x\":', parameter1)\n",
" parameter2 = 'x'\n",
" print('parameter2, after assigning \"x\"', parameter2)\n",
" return\n",
"\n",
"argument1 = [1, 2, 3] # passing a named object will affect the object bound to that name\n",
"argument2 = 4\n",
"print('argument1, before calling modify_parameters:', argument1)\n",
"print('argument2, before calling modify_parameters:', argument2)\n",
"print()\n",
"modify_parameters(argument1, argument2)\n",
"print()\n",
"print('argument1, after calling modify_parameters:', argument1)\n",
"print('argument2, after calling modify_parameters:', argument2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"argument1, before calling modify_parameters: [1, 2, 3]\n",
"argument2, before calling modify_parameters: 4\n",
"\n",
"parameter1, after inserting \"x\": ['x', 1, 2, 3]\n",
"parameter2, after assigning \"x\" x\n",
"\n",
"argument1, after calling modify_parameters: ['x', 1, 2, 3]\n",
"argument2, after calling modify_parameters: 4\n"
]
}
],
"prompt_number": 38
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One way of preventing functions from modifying mutable objects passed as parameters is to make a copy of those objects inside the function. Here is another version of the function above that makes a shallow copy of the *list_parameter* using the slice operator. \n",
"\n",
"*\\[Note: the Python [copy](http://docs.python.org/2/library/copy.html) module provides both [shallow] [`copy()`](http://docs.python.org/2/library/copy.html#copy.copy) and [`deepcopy()`](http://docs.python.org/2/library/copy.html#copy.deepcopy) methods; we will cover modules further below.]*"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def modify_parameter_copy(parameter_1):\n",
" '''Inserts \"x\" at the head of parameter_1, without modifying the list argument'''\n",
" parameter_1_copy = parameter_1[:]\n",
" parameter_1_copy.insert(0, 'x')\n",
" print('Inserted x:', parameter_1_copy)\n",
" return\n",
"\n",
"argument_1 = [1, 2, 3] # passing a named object will not affect the object bound to that name\n",
"print('Before:', argument_1)\n",
"modify_parameter_copy(argument_1)\n",
"print('After:', argument_1)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Before: [1, 2, 3]\n",
"Inserted x: ['x', 1, 2, 3]\n",
"After: [1, 2, 3]\n"
]
}
],
"prompt_number": 39
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python functions can return more than one value, by separating those return values with commas in the **return** statement. Multiple values are returned as a tuple. If the function-invoking expression is an assignment statement, multiple variables can be assigned the multiple values returned by the function in a single statement. This combining of values and subsequent separation is known as tuple *packing* and *unpacking*."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def min_and_max(list_of_values):\n",
" '''Returns a tuple containing the min and max values in the list_of_values'''\n",
" return min(list_of_values), max(list_of_values)\n",
"\n",
"list_1 = [3, 1, 4, 2, 5]\n",
"print('min and max of', list_1, ':', min_and_max(list_1))\n",
"\n",
"min_and_max_list_1 = min_and_max(list_1) # a single variable is assigned the two-element tuple\n",
"print('min and max of', list_1, ':', min_and_max_list_1)\n",
"\n",
"min_list_1, max_list_1 = min_and_max(list_1) # the 1st variable is assigned the 1st value, the 2nd variable is assigned the 2nd value\n",
"print('min and max of', list_1, ':', min_list_1, ',', max_list_1)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"min and max of [3, 1, 4, 2, 5] : (1, 5)\n",
"min and max of [3, 1, 4, 2, 5] : (1, 5)\n",
"min and max of [3, 1, 4, 2, 5] : 1 , 5\n"
]
}
],
"prompt_number": 40
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Iteration: for, range"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`for`**](http://docs.python.org/2/tutorial/controlflow.html#for-statements) statement iterates over the elements of a sequence."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for i in [0, 1, 2]:\n",
" print(i)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0\n",
"1\n",
"2\n"
]
}
],
"prompt_number": 41
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for c in 'abc':\n",
" print(c)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"a\n",
"b\n",
"c\n"
]
}
],
"prompt_number": 42
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python 2, the [**`range(stop)`**](http://docs.python.org/2/tutorial/controlflow.html#the-range-function) function returns a list of values from 0 up to `stop - 1` (inclusive). It is often used in the context of a `for` loop that iterates over the list of values."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Values for the', len(attribute_names), 'attributes:', end='\\n\\n')\n",
"for i in range(len(attribute_names)):\n",
" print(attribute_names[i], '=', \n",
" attribute_value(single_instance_list, attribute_names[i], attribute_names))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Values for the 23 attributes:\n",
"\n",
"class = p\n",
"cap-shape = k\n",
"cap-surface = f\n",
"cap-color = n\n",
"bruises? = f\n",
"odor = n\n",
"gill-attachment = f\n",
"gill-spacing = c\n",
"gill-size = n\n",
"gill-color = w\n",
"stalk-shape = e\n",
"stalk-root = ?\n",
"stalk-surface-above-ring = k\n",
"stalk-surface-below-ring = y\n",
"stalk-color-above-ring = w\n",
"stalk-color-below-ring = n\n",
"veil-type = p\n",
"veil-color = w\n",
"ring-number = o\n",
"ring-type = e\n",
"spore-print-color = w\n",
"population = v\n",
"habitat = d\n"
]
}
],
"prompt_number": 43
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The more general form of the function, [**`range(start, stop[, step])`**](http://docs.python.org/2/library/functions.html#range), returns a list of values from `start` to `stop - 1` (inclusive) increasing by `step` (which defaults to `1`), or from `start` down to `stop + 1` (inclusive) decreasing by `step` if `step` is negative."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for i in range(3, 0, -1):\n",
" print(i)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"3\n",
"2\n",
"1\n"
]
}
],
"prompt_number": 44
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python 2, the [**`xrange(stop[, stop[, step]])`**](http://docs.python.org/2/library/functions.html#xrange) function is an [*iterable*](http://docs.python.org/2/glossary.html#term-iterable) version of the `range()` function. In the context of a `for` loop, it returns the *next* item of the sequence for each iteration of the loop rather than creating *all* the elements of the sequence before the first iteration. This can reduce memory consumption in cases where iteration over all the items is not required.\n",
"\n",
"In Python 3, the `range()` function behaves the same way as the `xrange()` function does in Python 2, and so the `xrange()` function is not defined in Python 3. \n",
"\n",
"To maximize compatibility, we will use `range()` throughout this notebook; however, note that it is generally advisable to use `xrange()` rather than `range()` wherever possible in Python 2."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Modules, namespaces and dotted notation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A Python [*module*](http://docs.python.org/2/tutorial/modules.html) is a file containing related definitions (e.g., of functions and variables). Modules are used to help organize the Python [*namespaces*](http://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces), the set of identifiers accessible in a particular contexts. All of the functions and variables we define in this IPython Notebook are in the `__main__` namespace, so accessing them does not require any specification of a module.\n",
"\n",
"A Python module named `simple_ml` (in the file `simple_ml.py`), contains a set of solutions to the exercises in this IPython Notebook. Accessing functions in that module requires that we first [`import`](http://docs.python.org/2/reference/simple_stmts.html#the-import-statement) the module, and then prefix the function names with the module name followed by a dot (this is known as *dotted notation*).\n",
"\n",
"For example, the following function call Exercise 1 below: \n",
"\n",
"`simple_ml.print_attribute_names_and_values(single_instance_list, attribute_names)`\n",
"\n",
"uses dotted notation to reference the `print_attribute_names_and_values()` function in the `simple_ml` module.\n",
"\n",
"After you have defined your function in Exercise 1, you can test it by deleting the `simple_ml` module specification, so that the statement becomes\n",
"\n",
"`print_attribute_names_and_values(single_instance_list, attribute_names)`\n",
"\n",
"This will reference the `print_attribute_names_and_values()` function in the current namespace (`__main__`), i.e., the top-level interpreter environment. The `simple_ml.print_attribute_names_and_values()` function will still be accessible in the `simple_ml` namespace by using the \"`simple_ml.`\" prefix."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 1: define print_attribute_names_and_values()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Complete the following function definition, `print_attribute_names_and_values(instance, attribute_names)`, so that it generates exactly the same output as the code above."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def print_attribute_names_and_values(instance, attribute_names):\n",
" '''Prints the attribute names and values for an instance'''\n",
" # your code goes here\n",
" return\n",
"\n",
"import simple_ml # this module contains my solutions to exercises\n",
"\n",
"# to test your function, delete the 'simple_ml.' module specification in the call to print_attribute_names_and_values() below\n",
"simple_ml.print_attribute_names_and_values(single_instance_list, attribute_names)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Values for the 23 attributes:\n",
"\n",
"class = p\n",
"cap-shape = k\n",
"cap-surface = f\n",
"cap-color = n\n",
"bruises? = f\n",
"odor = n\n",
"gill-attachment = f\n",
"gill-spacing = c\n",
"gill-size = n\n",
"gill-color = w\n",
"stalk-shape = e\n",
"stalk-root = ?\n",
"stalk-surface-above-ring = k\n",
"stalk-surface-below-ring = y\n",
"stalk-color-above-ring = w\n",
"stalk-color-below-ring = n\n",
"veil-type = p\n",
"veil-color = w\n",
"ring-number = o\n",
"ring-type = e\n",
"spore-print-color = w\n",
"population = v\n",
"habitat = d\n"
]
}
],
"prompt_number": 45
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"File I/O"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python [file input and output](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) is done through [file](http://docs.python.org/2/library/stdtypes.html#file-objects) objects. A file object is created with the [`open(name[, mode])`](http://docs.python.org/2/library/functions.html#open) statement, where `name` is a string representing the name of the file, and `mode` is `'r'` (read), `'w'` (write) or `'a'` (append); if no second argument is provided, the mode defaults to `'r'`.\n",
"\n",
"A common Python programming pattern for processing an input text file is to \n",
"\n",
"* [**`open`**](http://docs.python.org/2/library/functions.html#open) the file using a [**`with`**](http://docs.python.org/2/reference/compound_stmts.html#the-with-statement) statement (which will automatically [**`close`**](http://docs.python.org/2/library/stdtypes.html#file.close) the file after the statements inside the `with` execute)\n",
"* iterate over each line in the file using a **`for`** statement\n",
"\n",
"The following code creates a list of instances, where each instance is a list of attribute values (like `instance_1_str` above). "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"all_instances = [] # initialize instances to an empty list\n",
"data_filename = 'agaricus-lepiota.data'\n",
"\n",
"with open(data_filename, 'r') as f:\n",
" for line in f:\n",
" all_instances.append(line.strip().split(','))\n",
" \n",
"print('Read', len(all_instances), 'instances from', data_filename)\n",
"print('First instance:', all_instances[0]) # we don't want to print all the instances, so let's just print one to verify"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Read 8124 instances from agaricus-lepiota.data\n",
"First instance: ['p', 'x', 's', 'n', 't', 'p', 'f', 'c', 'n', 'k', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'u']\n"
]
}
],
"prompt_number": 46
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 2: define load_instances()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `load_instances(filename)`, that returns a list of instances in a text file. The function definition is started for you below. The function should exhibit the same behavior as the code above."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def load_instances(filename):\n",
" '''Returns a list of instances stored in a file.\n",
" \n",
" filename is expected to have a series of comma-separated attribute values per line, e.g.,\n",
" p,k,f,n,f,n,f,c,n,w,e,?,k,y,w,n,p,w,o,e,w,v,d'''\n",
" instances = []\n",
" # your code goes here\n",
" return instances\n",
"\n",
"data_filename = 'agaricus-lepiota.data'\n",
"# to test your function, delete the 'simple_ml.' module specification in the call to load_instances() below\n",
"all_instances_2 = simple_ml.load_instances(data_filename)\n",
"print('Read', len(all_instances_2), 'instances from', data_filename)\n",
"print('First instance:', all_instances_2[0])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Read 8124 instances from agaricus-lepiota.data\n",
"First instance: ['p', 'x', 's', 'n', 't', 'p', 'f', 'c', 'n', 'k', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'u']\n"
]
}
],
"prompt_number": 47
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Output to text file is usually done via [**`file.write(str)`**](http://docs.python.org/2/library/stdtypes.html#file.write) method.\n",
"\n",
"As we saw earlier, the [`str.join(words)`](http://docs.python.org/2/library/stdtypes.html#str.join) method returns a single `str`-delimited string containing each of the strings in the list `words`.\n",
"\n",
"SQL and Hive database tables often use the pipe ('|') delimiter to separate column values for each row when they are stored as flat files. The following code creates a new data file using pipes rather than commas to separate the attribute values.\n",
"\n",
"To help maintain internal consistency, it is generally a good practice to define a variable such as `delimiter` or `separator` and bind it to the intended delimiter string, and then use the variable throughout."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"delimiter = '|'\n",
"\n",
"print('Converting to {}-delimited strings, e.g.,'.format(delimiter), delimiter.join(all_instances[0]))\n",
"\n",
"datafile2 = 'agaricus-lepiota-2.data'\n",
"with open(datafile2, 'w') as f:\n",
" for instance in all_instances:\n",
" f.write('|'.join(instance) + '\\n') # '+' is the concatenation operator when used with strings\n",
"\n",
"all_instances_3 = []\n",
"with open(datafile2, 'r') as f:\n",
" for line in f:\n",
" all_instances_3.append(line.strip().split(delimiter)) # note: changed ',' to '|'\n",
"print('Read', len(all_instances_3), 'instances from', datafile2)\n",
"print('First instance:', all_instances_3[0]) # we don't want to print all the instances, so let's just print one to verify"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Converting to |-delimited strings, e.g., p|x|s|n|t|p|f|c|n|k|e|e|s|s|w|w|p|w|o|p|k|s|u\n",
"Read 8124 instances from agaricus-lepiota-2.data\n",
"First instance: ['p', 'x', 's', 'n', 't', 'p', 'f', 'c', 'n', 'k', 'e', 'e', 's', 's', 'w', 'w', 'p', 'w', 'o', 'p', 'k', 's', 'u']\n"
]
}
],
"prompt_number": 48
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"List comprehensions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python provides a powerful [*list comprehension*](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) construct to simplify the creation of a list by specifying a formula in a single expression.\n",
"\n",
"Some programmers find list comprehensions confusing, and avoid their use. We won't rely on list comprehensions here, but will show examples with and without list comprehensions below.\n",
"\n",
"One common use of list comprehensions is in the context of the [`str.join(words)`](http://docs.python.org/2/library/string.html#string.join) method we saw earlier.\n",
"\n",
"If we wanted to construct a pipe-delimited string containing elements of the list, we could use a `for` loop to iteratively add list elements and pipe delimiters to a string. We would thereby add one pipe delimiter too many, and would thus have to shave that off at the end."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"delimited_string = ''\n",
"for x in [1, 2, 3]:\n",
" delimited_string += str(x) + delimiter\n",
"delimited_string = delimited_string[:-1]\n",
"delimited_string"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 49,
"text": [
"'1|2|3'"
]
}
],
"prompt_number": 49
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This process is much simpler using a list comprehension."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"delimiter.join([str(x) for x in [1, 2, 3]])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 50,
"text": [
"'1|2|3'"
]
}
],
"prompt_number": 50
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As noted in the initial description of the UCI mushroom set above, 2480 of the 8124 instances have missing values (denoted by `'?'`) for an attribute. There are several techniques for dealing with instances that include missing values, but to simplify things in the context of this primer - and following the example in the [Data Science for Business](http://www.data-science-for-biz.com/) book - we will restrict our focus to only those *clean* instances that have no missing values.\n",
"\n",
"We could use several lines of code - with an `if` statement inside a `for` loop - to create a `clean_instances` list from the `all_instances` list. Or we could use a list comprehension.\n",
"\n",
"We will show both approaches to creating `clean_instances` below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# version 1: using an if statement nested within a for statement\n",
"unknown_value = '?'\n",
"\n",
"clean_instances = []\n",
"for instance in all_instances:\n",
" if unknown_value not in instance:\n",
" clean_instances.append(instance)\n",
" \n",
"print(len(clean_instances), 'clean instances')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"5644 clean instances\n"
]
}
],
"prompt_number": 51
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# version 2: using an equivalent list comprehension\n",
"clean_instances_2 = [instance for instance in all_instances if unknown_value not in instance]\n",
"\n",
"print(len(clean_instances_2), 'clean instances')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"5644 clean instances\n"
]
}
],
"prompt_number": 52
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Dictionaries (dicts)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Although single character abbreviations of attribute values (e.g., 'x') allow for more compact data files, they are not as easy to understand by human readers as the longer attribute value descriptions (e.g., 'convex').\n",
"\n",
"A Python [dictionary (or **`dict`**)](http://docs.python.org/2/tutorial/datastructures.html#dictionaries) is an unordered, comma-delimited collection of *key, value* pairs, serving a siimilar function as a hash table or hashmap in other programming languages.\n",
"\n",
"We could create a dictionary for the `cap-type` attribute values shown above:\n",
"\n",
"> bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s\n",
"\n",
"Since we will want to look up the value using the abbreviation (which is the representation of the value stored in the file), we will use the abbreviations as *keys* and the descriptions as *values*.\n",
"\n",
"A Python dictionary can be created by specifying all `key: value` pairs (with colons separating each *key* and *value*), or by adding them iteratively. We will use the first method below, and use the second method further below. A *value* in a Python dictionary (`dict`) is accessed by specifying its *key* using the general form `dict[key]`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute_values_cap_type = {'b': 'bell', \n",
" 'c': 'conical', \n",
" 'x': 'convex', \n",
" 'f': 'flat', \n",
" 'k': 'knobbed', \n",
" 's': 'sunken'}\n",
"\n",
"attribute_value_abbrev = 'x'\n",
"print(attribute_value_abbrev, '=', attribute_values_cap_type[attribute_value_abbrev])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x = convex\n"
]
}
],
"prompt_number": 53
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A Python dictionary is an *iterable* container, so we can iterate over the keys in a dictionary using a `for` loop.\n",
"\n",
"Note that since a dictionary is an *unordered* collection, the sequence of abbreviations and associated values is not guaranteed to appear in any particular order. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for attribute_value_abbrev in attribute_values_cap_type:\n",
" print(attribute_value_abbrev, '=', attribute_values_cap_type[attribute_value_abbrev])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"c = conical\n",
"b = bell\n",
"f = flat\n",
"k = knobbed\n",
"s = sunken\n",
"x = convex\n"
]
}
],
"prompt_number": 54
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python supports *dictionary comprehensions*, which have a similar form as the *list comprehensions* described above.\n",
"\n",
"For example, if we provisionally omit the 'convex' cap-type (whose abbreviation is the last letter rather than first letter in the attribute name), we could construct a dictionary of abbreviations and descriptions using the following expression."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute_values_cap_type_2 = {x[0]: x for x in ['bell', 'conical', 'flat', 'knobbed', 'sunken']}\n",
"print(attribute_values_cap_type_2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"{'s': 'sunken', 'c': 'conical', 'b': 'bell', 'k': 'knobbed', 'f': 'flat'}\n"
]
}
],
"prompt_number": 55
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While it's useful to have a dictionary of values for the `cap-type` attribute, it would be even more useful to have a dictionary of values for every attribute. Earlier, we created a list of `attribute_names`; let's expand this to create a list of `attribute_values` wherein each list element is a dictionary.\n",
"\n",
"Rather than explicitly type in each dictionary entry in the Python interpreter, we'll define a function to read a file containing the list of attribute names, values and value abbreviations in the format shown above:\n",
"\n",
"* class: edible=e, poisonous=p\n",
"* cap-shape: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s\n",
"* cap-surface: fibrous=f, grooves=g, scaly=y, smooth=s\n",
"* ..."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def load_attribute_values(filename):\n",
" '''Returns a list of attribute values in a file.\n",
" \n",
" The attribute values are represented as dictionaries, wherein the keys are abbreviations and the values are descriptions.\n",
" filename is expected to have one attribute name and set of values per line, with the following format:\n",
" name: value_description=value_abbreviation[,value_description=value_abbreviation]*\n",
" for example\n",
" cap-shape: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s\n",
" The attribute value description dictionary created from this line would be the following:\n",
" {'c': 'conical', 'b': 'bell', 'f': 'flat', 'k': 'knobbed', 's': 'sunken', 'x': 'convex'}'''\n",
" attribute_values = []\n",
" with open(filename) as f:\n",
" for line in f:\n",
" attribute_name_and_value_string_list = line.strip().split(':')\n",
" attribute_name = attribute_name_and_value_string_list[0]\n",
" if len(attribute_name_and_value_string_list) < 2:\n",
" attribute_values.append({}) # no values for this attribute\n",
" else:\n",
" value_abbreviation_description_dict = {}\n",
" description_and_abbreviation_string_list = attribute_name_and_value_string_list[1].strip().split(',')\n",
" for description_and_abbreviation_string in description_and_abbreviation_string_list:\n",
" description_and_abbreviation = description_and_abbreviation_string.strip().split('=')\n",
" description = description_and_abbreviation[0]\n",
" if len(description_and_abbreviation) < 2: # assumption: no more than 1 value is missing an abbreviation\n",
" value_abbreviation_description_dict[None] = description\n",
" else:\n",
" abbreviation = description_and_abbreviation[1]\n",
" value_abbreviation_description_dict[abbreviation] = description\n",
" attribute_values.append(value_abbreviation_description_dict)\n",
" return attribute_values\n",
"\n",
"attribute_filename = 'agaricus-lepiota.attributes'\n",
"attribute_values = load_attribute_values(attribute_filename)\n",
"print('Read', len(attribute_values), 'attribute values from', attribute_filename)\n",
"print('First attribute values list:', attribute_values[0])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Read 23 attribute values from agaricus-lepiota.attributes\n",
"First attribute values list: {'p': 'poisonous', 'e': 'edible'}\n"
]
}
],
"prompt_number": 56
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 3: define load_attribute_values()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We earlier created the `attribute_names` list manually. The `load_attribute_values()` function above creates the `attribute_values` list automatically from the contents of a file ... each line of which starts with the name of each attribute ... which we discard.\n",
"\n",
"Complete the following function definition so that the code implements the functionality described in the docstring."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def load_attribute_names_and_values(filename):\n",
" '''Returns a list of attribute names and values in a file.\n",
" \n",
" This list contains dictionaries wherein the keys are names \n",
" and the values are value description dictionariess.\n",
" \n",
" Each value description sub-dictionary will use the attribute value abbreviations as its keys \n",
" and the attribute descriptions as the values.\n",
" \n",
" filename is expected to have one attribute name and set of values per line, with the following format:\n",
" name: value_description=value_abbreviation[,value_description=value_abbreviation]*\n",
" for example\n",
" cap-shape: bell=b, conical=c, convex=x, flat=f, knobbed=k, sunken=s\n",
" The attribute name and values dictionary created from this line would be the following:\n",
" {'name': 'cap-shape', 'values': {'c': 'conical', 'b': 'bell', 'f': 'flat', 'k': 'knobbed', 's': 'sunken', 'x': 'convex'}}'''\n",
" attribute_names_and_values = [] # this will be a list of dicts\n",
" # your code goes here\n",
" return attribute_names_and_values\n",
"\n",
"attribute_filename = 'agaricus-lepiota.attributes'\n",
"# to test your function, delete the 'simple_ml.' module specification in the call to load_attribute_names_and_values() below\n",
"attribute_names_and_values = simple_ml.load_attribute_names_and_values(attribute_filename)\n",
"print('Read', len(attribute_names_and_values), 'attribute values from', attribute_filename)\n",
"print('First attribute name:', attribute_names_and_values[0]['name'], \n",
" '; values:', attribute_names_and_values[0]['values'])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Read 23 attribute values from agaricus-lepiota.attributes\n",
"First attribute name: class ; values: {'p': 'poisonous', 'e': 'edible'}\n"
]
}
],
"prompt_number": 57
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Counting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Data scientists often need to count things. For example, we might want to count the numbers of edible and poisonous mushrooms in the *clean_instances* list we created earlier."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"edible_count = 0\n",
"for instance in clean_instances:\n",
" if instance[0] == 'e':\n",
" edible_count += 1 # this is shorthand for edible_count = edible_count + 1\n",
"\n",
"print('There are', edible_count, 'edible mushrooms among the', \n",
" len(clean_instances), 'clean instances')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"There are 3488 edible mushrooms among the 5644 clean instances\n"
]
}
],
"prompt_number": 58
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More generally, we often want to count the number of occurrences (frequencies) of each possible value for an attribute. One way to do so is to create a dictionary where each dictionary key is an attribute value and each dictionary value is the count of instances with that attribute value.\n",
"\n",
"Using an ordinary dictionary, we must be careful to create a new dictionary entry the first time we see a new attribute value (that is not already contained in the dictionary)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"cap_state_value_counts = {}\n",
"for instance in clean_instances:\n",
" cap_state_value = instance[1] # cap-state is the 2nd attribute\n",
" if cap_state_value not in cap_state_value_counts:\n",
" cap_state_value_counts[cap_state_value] = 0\n",
" cap_state_value_counts[cap_state_value] += 1\n",
"\n",
"print('Counts for each value of cap-state:')\n",
"for value in cap_state_value_counts:\n",
" print(value, ':', cap_state_value_counts[value])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Counts for each value of cap-state:\n",
"c : 4\n",
"b : 300\n",
"f : 2432\n",
"k : 36\n",
"s : 32\n",
"x : 2840\n"
]
}
],
"prompt_number": 59
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python [**`collections`**](http://docs.python.org/2/library/collections.html) module provides a number of high performance container datatypes. A frequently useful datatype is a [**`defaultdict`**](http://docs.python.org/2/library/collections.html#defaultdict-objects), which automatically creates an appropriate default value for a new key. For example, a `defaultdict(int)` automatically initializes a new dictionary entry to 0 (zero); a `defaultdict(list)` automatically initializes a new dictionary entry to the empty list (`[]`).\n",
"\n",
"After first importing `defaultdict` from `collections`, we can use `defaultdict(int)` to simplify the code above:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from collections import defaultdict # don't need to use collections.defaultdict() below\n",
"\n",
"cap_state_value_counts = defaultdict(int)\n",
"for instance in clean_instances:\n",
" cap_state_value = instance[1]\n",
" cap_state_value_counts[cap_state_value] += 1\n",
"\n",
"print('Counts for each value of cap-state:')\n",
"for value in cap_state_value_counts:\n",
" print(value, ':', cap_state_value_counts[value])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Counts for each value of cap-state:\n",
"c : 4\n",
"b : 300\n",
"f : 2432\n",
"k : 36\n",
"s : 32\n",
"x : 2840\n"
]
}
],
"prompt_number": 60
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 4: define attribute_value_counts()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `attribute_value_counts(instances, attribute, attribute_names)`, that returns a `defaultdict` containing the counts of occurrences of each value of `attribute` in the list of `instances`. `attribute_names` is the list we created above, where each element is the name of an attribute."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# your definition goes here\n",
"\n",
"attribute = 'cap-shape'\n",
"# remove 'simple_ml.' below to test your function definition\n",
"attribute_value_counts = simple_ml.attribute_value_counts(clean_instances, attribute, attribute_names)\n",
"\n",
"print('Counts for each value of', attribute, ':')\n",
"for value in attribute_value_counts:\n",
" print(value, ':', attribute_value_counts[value])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Counts for each value of cap-shape :\n",
"c : 4\n",
"b : 300\n",
"f : 2432\n",
"k : 36\n",
"s : 32\n",
"x : 2840\n"
]
}
],
"prompt_number": 61
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Sorting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Earlier, we saw that there is a `list.sort()` method that will sort a list in-place, i.e., by replacing the original value of `list` with a sorted version of the elements in `list`. \n",
"\n",
"The Python [**`sorted(iterable[, cmp[, key[, reverse]]])`**](http://docs.python.org/2/library/functions.html#sorted) function can be used to return a *copy* of a list, dictionary or any other [*iterable*](http://docs.python.org/2/glossary.html#term-iterable) container it is passed, in ascending order."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"original_list = [3, 1, 4, 2, 5]\n",
"sorted_list = sorted(original_list)\n",
"print(original_list)\n",
"print(sorted_list)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[3, 1, 4, 2, 5]\n",
"[1, 2, 3, 4, 5]\n"
]
}
],
"prompt_number": 62
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since it returns a copy, `sorted()` can be used with strings."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(sorted('python'))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['h', 'n', 'o', 'p', 't', 'y']\n"
]
}
],
"prompt_number": 63
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`sorted()` can also be used with dictionaries (it returns a sorted list of the dictionary *keys*)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(sorted(attribute_values_cap_type)) # returns a list of sorted keys (but not values) in the dictionary"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['b', 'c', 'f', 'k', 's', 'x']\n"
]
}
],
"prompt_number": 64
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, we can use the sorted *keys* to access the *values* of a dictionary."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for attribute_value_abbrev in sorted(attribute_values_cap_type):\n",
" print(attribute_value_abbrev, '=', attribute_values_cap_type[attribute_value_abbrev])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"b = bell\n",
"c = conical\n",
"f = flat\n",
"k = knobbed\n",
"s = sunken\n",
"x = convex\n"
]
}
],
"prompt_number": 65
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An optional [keyword argument](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments), **`reverse`**, can be used to reverse the order of the sorted list returned by the function. The default value of this optional parameter is `False`, to get non-default behavior, we must specify the name and value of the argument: `reverse=True`. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(sorted([3, 1, 4, 2, 5], reverse=True))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[5, 4, 3, 2, 1]\n"
]
}
],
"prompt_number": 66
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print(sorted(attribute_values_cap_type, reverse=True))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['x', 's', 'k', 'f', 'c', 'b']\n"
]
}
],
"prompt_number": 67
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute = 'cap-shape'\n",
"attribute_value_counts = simple_ml.attribute_value_counts(clean_instances, attribute, attribute_names)\n",
"\n",
"print('Counts for each value of', attribute, ':')\n",
"for value in sorted(attribute_value_counts):\n",
" print(value, ':', attribute_value_counts[value])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Counts for each value of cap-shape :\n",
"b : 300\n",
"c : 4\n",
"f : 2432\n",
"k : 36\n",
"s : 32\n",
"x : 2840\n"
]
}
],
"prompt_number": 68
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Sorting a dictionary by values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We often want to sort a dictionary by its *values* rather than its *keys*. \n",
"\n",
"For example, when we printed out the counts of the attribute values for `cap-shape` above, the counts appeared in an ascending alphabetic order of their attribute names. It is often more helpful to show the attribute value counts in descending order of the counts (which are the values in that dictionary).\n",
"\n",
"There are a [variety of ways to sort a dictionary by values](http://writeonly.wordpress.com/2008/08/30/sorting-dictionaries-by-value-in-python-improved/), but the approach described in [PEP-256](http://legacy.python.org/dev/peps/pep-0265/) is generally considered the most efficient.\n",
"\n",
"In order to understand the components used in this approach, we will revisit and elaborate on a few concepts involving *dictionaries*, *iterators* and *modules*."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`dict.items()`**](http://docs.python.org/2/library/stdtypes.html#dict.items) method returns an unordered list of `(key, value)` tuples in `dict`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute_values_cap_type.items()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 69,
"text": [
"[('c', 'conical'),\n",
" ('b', 'bell'),\n",
" ('f', 'flat'),\n",
" ('k', 'knobbed'),\n",
" ('s', 'sunken'),\n",
" ('x', 'convex')]"
]
}
],
"prompt_number": 69
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python 2, a related method, [**`dict.iteritems()`**](http://docs.python.org/2/library/stdtypes.html#dict.iteritems), returns an [**`iterator`**](http://docs.python.org/2/library/stdtypes.html#iterator-types): a callable object that returns the *next* item in a sequence each time it is referenced (e.g., during each iteration of a for loop), which can be more efficient than generating *all* the items in the sequence before any are used ... and so should be used rather than `items()` wherever possible\n",
"\n",
"This is similar to the distinction between `xrange()` and `range()` described above ... and, also similarly, `dict.items()` is an `iterator` in Python 3 and so `dict.iteritems()` is no longer needed (nor defined) ... and further similarly, we will use only `dict.items()` in this notebook, but `dict.iteritems()` should be used wherever possible in Python 2."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for key, value in attribute_values_cap_type.items():\n",
" print(key, ':', value)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"c : conical\n",
"b : bell\n",
"f : flat\n",
"k : knobbed\n",
"s : sunken\n",
"x : convex\n"
]
}
],
"prompt_number": 70
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Python [**`operator`**](http://docs.python.org/2/library/operator.html) module contains a number of functions that perform object comparisons, logical operations, mathematical operations, sequence operations, and abstract type tests.\n",
"\n",
"To facilitate sorting a dictionary by values, we will use the [**`operator.itemgetter(item)`**](http://docs.python.org/2/library/operator.html#operator.itemgetter) function that can be used to retrieve an indexed value (`item`) in a tuple (such as a `(key, value)` pair returned by `[iter]items()`).\n",
"\n",
"We can use `operator.itemgetter(1)`) to reference the value - the 2nd item in each `(key, value)` tuple, (at zero-based index position 1) - rather than the key - the first item in each `(key, value)` tuple (at index position 0).\n",
"\n",
"We will use the optional keyword argument **`key`** in [`sorted(iterable[, cmp[, key[, reverse]]])`](http://docs.python.org/2/library/functions.html#sorted) to specify a *sorting* key that is not the same as the `dict` key (the `dict` key is the default *sorting* key)"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import operator\n",
"\n",
"sorted(attribute_values_cap_type.items(), key=operator.itemgetter(1))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 71,
"text": [
"[('b', 'bell'),\n",
" ('c', 'conical'),\n",
" ('x', 'convex'),\n",
" ('f', 'flat'),\n",
" ('k', 'knobbed'),\n",
" ('s', 'sunken')]"
]
}
],
"prompt_number": 71
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now sort the counts of attribute values in descending frequency of occurrence, and print them out using tuple unpacking."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"attribute = 'cap-shape'\n",
"value_counts = simple_ml.attribute_value_counts(clean_instances, attribute, attribute_names)\n",
"\n",
"print('Counts for each value of', attribute, '(sorted by count):')\n",
"for value, count in sorted(value_counts.items(), key=operator.itemgetter(1), reverse=True):\n",
" print(value, ':', count)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Counts for each value of cap-shape (sorted by count):\n",
"x : 2840\n",
"f : 2432\n",
"b : 300\n",
"k : 36\n",
"s : 32\n",
"c : 4\n"
]
}
],
"prompt_number": 72
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 5: define print_all_attribute_value_counts()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `print_all_attribute_value_counts(instances, attribute_names)`, that prints each attribute name in `attribute_names`, and then for each attribute value, prints the value abbreviation, the count of occurrences of that value and the proportion of instances that have that attribute value.\n",
"\n",
"You may find it helpful to use [fancier output formatting](http://docs.python.org/2/tutorial/inputoutput.html#fancier-output-formatting). More details can be found in the Python documentation on [format string syntax](http://docs.python.org/2/library/string.html#format-string-syntax).\n",
"\n",
"Examples of the `str.format()` function used in conjunction with print statements is shown below, followed by sample output of the `simple_ml` version of `print_all_attribute_value_counts()` (which uses similar formatting, but without hard-coded values)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Output of a sample line using str.format():')\n",
"print('class:', end=' ') # keeps cursor on the same line for subsequent print statements\n",
"print('{} = {} ({:5.3f}),'.format('e', 3488, 3488 / 5644.0), end=' ')\n",
"print('{} = {} ({:5.3f}),'.format('p', 2156, 2156 / 5644.0), end=' ')\n",
"print() # a print statement with no arguments will advance the cursor to the beginning of the next line\n",
"print('End of sample line')"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Output of a sample line using str.format():\n",
"class: e = 3488 (0.618), p = 2156 (0.382), \n",
"End of sample line\n"
]
}
],
"prompt_number": 73
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define your version of `print_all_attribute_value_counts(instances, attribute_names)` below, deleting the `simple_ml.` module specification when you are ready to test your function."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# your function definition goes here\n",
"\n",
"print('\\nCounts for all attributes and values:\\n')\n",
"simple_ml.print_all_attribute_value_counts(clean_instances, attribute_names)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"Counts for all attributes and values:\n",
"\n",
"class: e = 3488 (0.618), p = 2156 (0.382), \n",
"cap-shape: x = 2840 (0.503), f = 2432 (0.431), b = 300 (0.053), k = 36 (0.006), s = 32 (0.006), c = 4 (0.001), \n",
"cap-surface: y = 2220 (0.393), f = 2160 (0.383), s = 1260 (0.223), g = 4 (0.001), \n",
"cap-color: g = 1696 (0.300), n = 1164 (0.206), y = 1056 (0.187), w = 880 (0.156), e = 588 (0.104), b = 120 (0.021), p = 96 (0.017), c = 44 (0.008), \n",
"bruises?: t = 3184 (0.564), f = 2460 (0.436), \n",
"odor: n = 2776 (0.492), f = 1584 (0.281), a = 400 (0.071), l = 400 (0.071), p = 256 (0.045), c = 192 (0.034), m = 36 (0.006), \n",
"gill-attachment: f = 5626 (0.997), a = 18 (0.003), \n",
"gill-spacing: c = 4620 (0.819), w = 1024 (0.181), \n",
"gill-size: b = 4940 (0.875), n = 704 (0.125), \n",
"gill-color: p = 1384 (0.245), n = 984 (0.174), w = 966 (0.171), h = 720 (0.128), g = 656 (0.116), u = 480 (0.085), k = 408 (0.072), r = 24 (0.004), y = 22 (0.004), \n",
"stalk-shape: t = 2880 (0.510), e = 2764 (0.490), \n",
"stalk-root: b = 3776 (0.669), e = 1120 (0.198), c = 556 (0.099), r = 192 (0.034), \n",
"stalk-surface-above-ring: s = 3736 (0.662), k = 1332 (0.236), f = 552 (0.098), y = 24 (0.004), \n",
"stalk-surface-below-ring: s = 3544 (0.628), k = 1296 (0.230), f = 552 (0.098), y = 252 (0.045), \n",
"stalk-color-above-ring: w = 3136 (0.556), p = 1008 (0.179), g = 576 (0.102), n = 448 (0.079), b = 432 (0.077), c = 36 (0.006), y = 8 (0.001), \n",
"stalk-color-below-ring: w = 3088 (0.547), p = 1008 (0.179), g = 576 (0.102), n = 496 (0.088), b = 432 (0.077), c = 36 (0.006), y = 8 (0.001), \n",
"veil-type: p = 5644 (1.000), \n",
"veil-color: w = 5636 (0.999), y = 8 (0.001), \n",
"ring-number: o = 5488 (0.972), t = 120 (0.021), n = 36 (0.006), \n",
"ring-type: p = 3488 (0.618), l = 1296 (0.230), e = 824 (0.146), n = 36 (0.006), \n",
"spore-print-color: n = 1920 (0.340), k = 1872 (0.332), h = 1584 (0.281), w = 148 (0.026), r = 72 (0.013), u = 48 (0.009), \n",
"population: v = 2160 (0.383), y = 1688 (0.299), s = 1104 (0.196), a = 384 (0.068), n = 256 (0.045), c = 52 (0.009), \n",
"habitat: d = 2492 (0.442), g = 1860 (0.330), p = 568 (0.101), u = 368 (0.065), m = 292 (0.052), l = 64 (0.011), \n"
]
}
],
"prompt_number": 74
},
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"4. Using Python to Build and Use a Simple Decision Tree Classifier"
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Decision Trees"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Wikipedia offers the following description of a [decision tree](https://en.wikipedia.org/wiki/Decision_tree) (with italics added to emphasize terms that will be elaborated below):\n",
"\n",
"> A decision tree is a flowchart-like structure in which each *internal node* represents a *test* of an *attribute*, each branch represents an *outcome* of that test and each *leaf node* represents *class label* (a decision taken after testing all attributes in the path from the root to the leaf). Each path from the root to a leaf can also be represented as a classification rule.\n",
"\n",
"The image below depicts a decision tree created from the UCI mushroom dataset that appears on [Andy G's blog post about Decision Tree Learning](http://gieseanw.wordpress.com/2012/03/03/decision-tree-learning/), where \n",
"\n",
"* a white box represents an *internal node* (and the label represents the *attribute* being tested)\n",
"* a blue box represents an attribute value (an *outcome* of the *test* of that attribute)\n",
"* a green box represents a *leaf node* with a *class label* of *edible*\n",
"* a red box represents a *leaf node* with a *class label* of *poisonous*\n",
"\n",
"<img src=\"http://gieseanw.files.wordpress.com/2012/03/mushroomdecisiontree.png\" style=\"width: 800px;\" />\n",
"\n",
"It is important to note that the UCI mushroom dataset consists entirely of [categorical variables](https://en.wikipedia.org/wiki/Categorical_variable), i.e., every variable (or *attribute*) has an enumerated set of possible values. Many datasets include numeric variables that can take on int or float values. Tests for such variables typically use comparison operators, e.g., $age < 65$ or $36,250 < adjusted\\_gross\\_income <= 87,850$. *[Aside: Python supports boolean expressions containing multiple comparison operators, such as the expression comparing adjusted_gross_income in the preceding example.]*\n",
"\n",
"Our simple decision tree will only accommodate categorical variables. We will closely follow a version of the [decision tree learning algorithm implementation](http://www.onlamp.com/pub/a/python/2006/02/09/ai_decision_trees.html?page=3) offered by Chris Roach.\n",
"\n",
"Our goal in the following sections is to use Python to\n",
"\n",
"* *create* a simple decision tree based on a set of training instances\n",
"* *classify* (predict class labels for) for an instance using a simple decision tree\n",
"* *evaluate* the performance of the simple decision tree on classifying a set of test instances\n",
"\n",
"First, we will explore some concepts and algorithms used in building and using decision trees."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Entropy"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When building a supervised classification model, the frequency distribution of attribute values is a potentially important factor in determining the relative importance of each attribute at various stages in the model building process.\n",
"\n",
"In data modeling, we can use frequency distributions to compute ***entropy***, a measure of disorder (impurity) in a set.\n",
"\n",
"We compute the entropy of multiplying the proportion of instances with each class label by the log of that proportion, and then taking the negative sum of those terms.\n",
"\n",
"More precisely, for a 2-class (binary) classification task:\n",
"\n",
"$entropy(S) = - p_1 log_2 (p_1) - p_2 log_2 (p_2)$\n",
"\n",
"where $p_i$ is proportion (relative frequency) of class *i* within the set *S*.\n",
"\n",
"From the output above, we know that the proportion of `clean_instances` that are labeled `'e'` (class `edible`) in the UCI dataset is $3488 \\div 5644 = 0.618$, and the proportion labeled `'p'` (class `poisonous`) is $2156 \\div 5644 = 0.382$.\n",
"\n",
"After importing the Python [`math`](http://docs.python.org/2/library/math.html) module, we can use the [`math.log(x[, base])`](http://docs.python.org/2/library/math.html#math.log) function in computing the entropy of the `clean_instances` of the UCI mushroom data set as follows.\n",
"\n",
"Note that you can use a backslash character (`\\`) at the end of a line to continue the statement on the next line (this should generally be used sparingly)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import math\n",
"\n",
"entropy = - (3488 / 5644.0) * math.log(3488 / 5644.0, 2) \\\n",
" - (2156 / 5644.0) * math.log(2156 / 5644.0, 2)\n",
"print(entropy)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0.959441337353\n"
]
}
],
"prompt_number": 75
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 6: define entropy()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `entropy(instances)`, that computes the entropy of `instances`. You may assume the class label is in position 0; we will later see how to specify default parameter values in function definitions.\n",
"\n",
"[Note: the class label in many data files is the *last* rather than the *first* item on each line.]"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# your function definition here\n",
"\n",
"# delete 'simple_ml.' below to test your function\n",
"print(simple_ml.entropy(clean_instances))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0.959441337353\n"
]
}
],
"prompt_number": 76
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Information Gain"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Informally, a decision tree is constructed using a recursive algorithm that \n",
"\n",
"* selects the *best* attribute \n",
"* splits the set into subsets based on the values of that attribute (each subset is composed of instances from the original set that have the same value for that attribute)\n",
"* repeats the process on each of these subsets until a stopping condition is met (e.g., a subset has no instances or has instances which all have the same class label)\n",
"\n",
"Entropy is a metric that can be used in selecting the best attribute for each split: the best attribute is the one resulting in the *largest decrease in entropy* for a set of instances. [Note: other metrics can be used for determining the best attribute]\n",
"\n",
"*Information gain* measures the decrease in entropy that results from splitting a set of instances based on an attribute.\n",
"\n",
"$IG(S, a) = entropy(S) - [p(s_1) \u00d7 entropy(s_1) + p(s_2) \u00d7 entropy(s_2) ... + p(s_n) \u00d7 entropy(s_n)]$\n",
"\n",
"Where $n$ is the number of distinct values of attribute $a$, and $s_i$ is the subset of $S$ where all instances have the $i$th value of $a$."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Information gain for different attributes:', end='\\n\\n')\n",
"for i in range(1, len(attribute_names)):\n",
" print('{:5.3f} {:2} {}'.format(\n",
" simple_ml.information_gain(clean_instances, i), i, attribute_names[i]))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Information gain for different attributes:\n",
"\n",
"0.017 1 cap-shape\n",
"0.005 2 cap-surface\n",
"0.195 3 cap-color\n",
"0.140 4 bruises?\n",
"0.860 5 odor\n",
"0.004 6 gill-attachment\n",
"0.058 7 gill-spacing\n",
"0.032 8 gill-size\n",
"0.213 9 gill-color\n",
"0.275 10 stalk-shape\n",
"0.097 11 stalk-root\n",
"0.425 12 stalk-surface-above-ring\n",
"0.409 13 stalk-surface-below-ring\n",
"0.306 14 stalk-color-above-ring\n",
"0.279 15 stalk-color-below-ring\n",
"0.000 16 veil-type\n",
"0.002 17 veil-color\n",
"0.012 18 ring-number\n",
"0.463 19 ring-type"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"0.583 20 spore-print-color\n",
"0.110 21 population\n",
"0.101 22 habitat\n"
]
}
],
"prompt_number": 77
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can sort the attributes based in decreasing order of information gain."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Information gain for different attributes:', end='\\n\\n')\n",
"sorted_information_gain_indexes = sorted([(simple_ml.information_gain(clean_instances, i), i) \\\n",
" for i in range(1, len(attribute_names))], \n",
" reverse=True)\n",
"print(sorted_information_gain_indexes, end='\\n\\n')\n",
"\n",
"for gain, i in sorted_information_gain_indexes:\n",
" print('{:5.3f} {:2} {}'.format(gain, i, attribute_names[i]))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Information gain for different attributes:\n",
"\n",
"[(0.8596704358849709, 5), (0.5828694793608379, 20), (0.46290566555455265, 19), (0.42456477093655975, 12), (0.40865780788318695, 13), (0.3062989793570199, 14), (0.27891994708759504, 15), (0.2750355212178639, 10), (0.2127971869976022, 9), (0.19495343617580085, 3), (0.1400386042032834, 4), (0.1097880400299237, 21), (0.10067585994181227, 22), (0.09733858997769329, 11), (0.05836192763098613, 7), (0.03242975884332899, 8), (0.01740692300090696, 1), (0.01205967443646827, 18), (0.004572013423856602, 2), (0.0044397141315495325, 6), (0.0019702590992403124, 17), (0.0, 16)]"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"\n",
"0.860 5 odor\n",
"0.583 20 spore-print-color\n",
"0.463 19 ring-type\n",
"0.425 12 stalk-surface-above-ring\n",
"0.409 13 stalk-surface-below-ring\n",
"0.306 14 stalk-color-above-ring\n",
"0.279 15 stalk-color-below-ring\n",
"0.275 10 stalk-shape\n",
"0.213 9 gill-color\n",
"0.195 3 cap-color\n",
"0.140 4 bruises?\n",
"0.110 21 population\n",
"0.101 22 habitat\n",
"0.097 11 stalk-root\n",
"0.058 7 gill-spacing\n",
"0.032 8 gill-size\n",
"0.017 1 cap-shape\n",
"0.012 18 ring-number\n",
"0.005 2 cap-surface\n",
"0.004 6 gill-attachment\n",
"0.002 17 veil-color\n",
"0.000 16 veil-type\n"
]
}
],
"prompt_number": 78
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following variation does not use a list comprehension:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print('Information gain for different attributes:', end='\\n\\n')\n",
"\n",
"information_gain_values = []\n",
"for i in range(1, len(attribute_names)):\n",
" information_gain_values.append((simple_ml.information_gain(clean_instances, i), i))\n",
" \n",
"sorted_information_gain_indexes = sorted(information_gain_values, \n",
" reverse=True)\n",
"print(sorted_information_gain_indexes, end='\\n\\n')\n",
"\n",
"for gain, i in sorted_information_gain_indexes:\n",
" print('{:5.3f} {:2} {}'.format(gain, i, attribute_names[i]))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Information gain for different attributes:\n",
"\n",
"[(0.8596704358849709, 5), (0.5828694793608379, 20), (0.46290566555455265, 19), (0.42456477093655975, 12), (0.40865780788318695, 13), (0.3062989793570199, 14), (0.27891994708759504, 15), (0.2750355212178639, 10), (0.2127971869976022, 9), (0.19495343617580085, 3), (0.1400386042032834, 4), (0.1097880400299237, 21), (0.10067585994181227, 22), (0.09733858997769329, 11), (0.05836192763098613, 7), (0.03242975884332899, 8), (0.01740692300090696, 1), (0.01205967443646827, 18), (0.004572013423856602, 2), (0.0044397141315495325, 6), (0.0019702590992403124, 17), (0.0, 16)]"
]
},
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"\n",
"0.860 5 odor\n",
"0.583 20 spore-print-color\n",
"0.463 19 ring-type\n",
"0.425 12 stalk-surface-above-ring\n",
"0.409 13 stalk-surface-below-ring\n",
"0.306 14 stalk-color-above-ring\n",
"0.279 15 stalk-color-below-ring\n",
"0.275 10 stalk-shape\n",
"0.213 9 gill-color\n",
"0.195 3 cap-color\n",
"0.140 4 bruises?\n",
"0.110 21 population\n",
"0.101 22 habitat\n",
"0.097 11 stalk-root\n",
"0.058 7 gill-spacing\n",
"0.032 8 gill-size\n",
"0.017 1 cap-shape\n",
"0.012 18 ring-number\n",
"0.005 2 cap-surface\n",
"0.004 6 gill-attachment\n",
"0.002 17 veil-color\n",
"0.000 16 veil-type\n"
]
}
],
"prompt_number": 79
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 7: define information_gain()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `information_gain(instances, i)`, that returns the information gain achieved by selecting the `i`th attribute to split `instances`. It should exhibit the same behavior as the `simple_ml` version of the function."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# your definition of information_gain(instances, i) here\n",
"\n",
"# delete 'simple_ml.' below to test your function\n",
"sorted_information_gain_indexes = sorted([(simple_ml.information_gain(clean_instances, i), i) for i in range(1, len(attribute_names))], \n",
" reverse=True)\n",
"\n",
"print('Information gain for different attributes:', end='\\n\\n')\n",
"for gain, i in sorted_information_gain_indexes:\n",
" print('{:5.3f} {:2} {}'.format(gain, i, attribute_names[i]))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Information gain for different attributes:\n",
"\n",
"0.860 5 odor\n",
"0.583 20 spore-print-color\n",
"0.463 19 ring-type\n",
"0.425 12 stalk-surface-above-ring\n",
"0.409 13 stalk-surface-below-ring\n",
"0.306 14 stalk-color-above-ring\n",
"0.279 15 stalk-color-below-ring\n",
"0.275 10 stalk-shape\n",
"0.213 9 gill-color\n",
"0.195 3 cap-color\n",
"0.140 4 bruises?\n",
"0.110 21 population\n",
"0.101 22 habitat\n",
"0.097 11 stalk-root\n",
"0.058 7 gill-spacing\n",
"0.032 8 gill-size\n",
"0.017 1 cap-shape\n",
"0.012 18 ring-number\n",
"0.005 2 cap-surface\n",
"0.004 6 gill-attachment\n",
"0.002 17 veil-color\n",
"0.000 16 veil-type\n"
]
}
],
"prompt_number": 80
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Building a Simple Decision Tree"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will implement a modified version of the [ID3](https://en.wikipedia.org/wiki/ID3_algorithm) algorithm for building a simple decision tree.\n",
"\n",
" ID3 (Examples, Target_Attribute, Attributes)\n",
" Create a root node for the tree\n",
" If all examples are positive, Return the single-node tree Root, with label = +.\n",
" If all examples are negative, Return the single-node tree Root, with label = -.\n",
" If number of predicting attributes is empty, then Return the single node tree Root,\n",
" with label = most common value of the target attribute in the examples.\n",
" Otherwise Begin\n",
" A \u2190 The Attribute that best classifies examples.\n",
" Decision Tree attribute for Root = A.\n",
" For each possible value, v_i, of A,\n",
" Add a new tree branch below Root, corresponding to the test A = v_i.\n",
" Let Examples(v_i) be the subset of examples that have the value v_i for A\n",
" If Examples(v_i) is empty\n",
" Then below this new branch add a leaf node with label = most common target value in the examples\n",
" Else below this new branch add the subtree ID3 (Examples(v_i), Target_Attribute, Attributes \u2013 {A})\n",
" End\n",
" Return Root"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In building a decision tree, we will need to split the instances based on the index of the *best* attribute, i.e., the attribute that offers the *highest information gain*. We will use separate utility functions to handle these subtasks. To simplify the functions, we will rely exclusively on attribute indexes rather than attribute names.\n",
"\n",
"***Note:*** the algorithm above is *recursive*, i.e., the there is a recursive call to `ID3` within the definition of `ID3`. Covering recursion is beyond the scope of this primer, but there are a number of other resources on [using recursion in Python](https://www.google.com/search?q=python+recursion). Familiarity with recursion will be important for understanding both the tree construction and classification functions below.\n",
"\n",
"First, we will define a function, **`split_instances(instances, attribute_index)`**, to split a set of instances based on any attribute. This function will return a dictionary where the *key* of each dictionary is a distinct value of the specified `attribute_index`, and the *value* of each dictionary is a list representing the subset of `instances` that have that attribute value."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def split_instances(instances, attribute_index):\n",
" '''Returns a list of dictionaries, splitting a list of instances according to their values of a specified attribute''\n",
" \n",
" The key of each dictionary is a distinct value of attribute_index,\n",
" and the value of each dictionary is a list representing the subset of instances that have that value for the attribute'''\n",
" partitions = defaultdict(list)\n",
" for instance in instances:\n",
" partitions[instance[attribute_index]].append(instance)\n",
" return partitions\n",
"\n",
"partitions = split_instances(clean_instances, 5)\n",
"print([(partition, len(partitions[partition])) for partition in partitions])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[('a', 400), ('c', 192), ('f', 1584), ('m', 36), ('l', 400), ('n', 2776), ('p', 256)]\n"
]
}
],
"prompt_number": 81
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we can split instances based on a particular attribute, we would like to be able to choose the *best* attribute with which to split the instances, where *best* is defined as the attribute that provides the greatest information gain if instances were split based on that attribute. We will want to restrict the candidate attributes so that we don't bother trying to split on an attribute that was used higher up in the decision tree (or use the target attribute as a candidate)."
]
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 8: define choose_best_attribute_index()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `choose_best_attribute_index(instances, candidate_attribute_indexes)`, that returns the index in the list of `candidate_attribute_indexes` that provides the highest information gain if `instances` are split based on that attribute index."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# your function here\n",
"\n",
"# delete 'simple_ml.' below to test your function:\n",
"print('Best attribute index:', \n",
" simple_ml.choose_best_attribute_index(clean_instances, range(1, len(attribute_names))))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Best attribute index: 5\n"
]
}
],
"prompt_number": 82
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A leaf node in a decision tree represents the most frequently occurring - or majority - class value for that path through the tree. We will need a function that determines the majority value for the class index among a set of instances.\n",
"\n",
"We earlier saw how the [`defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict) container in the [`collections`](http://docs.python.org/2/library/collections.html) module can be used to simplify the construction of a dictionary containing the counts of all attribute values for all attributes, by automatically setting the count for any attribute value to zero when the attribute value is first added to the dictionary.\n",
"\n",
"The `collections` module has another useful container, a [**`Counter`**](http://docs.python.org/2/library/collections.html#collections.Counter) class, that can further simplify the construction of a specialized dictionary of counts. When a `Counter` object is instantiated with a list of items, it returns a dictionary-like container in which the *keys* are the unique items in the list, and the *values* are the counts of each unique item in that list. \n",
"\n",
"This container has an additional method, [**`most_common([n])`**](http://docs.python.org/2/library/collections.html#collections.Counter.most_common), which returns a list of 2-element tuples representing the values and their associated counts for the most common `n` values; if `n` is omitted, the method returns all tuples.\n",
"\n",
"The following is an example of how we can use a `Counter` to represent the frequency of different class labels, and how we can identify the most frequent value and its count."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from collections import Counter\n",
"\n",
"class_counts = Counter([instance[0] for instance in clean_instances])\n",
"print('class_counts: {}; most_common(1): {}, most_common(1)[0][0]: {}'.format(\n",
" class_counts, # the Counter object\n",
" class_counts.most_common(1), # returns a list in which the 1st element is a tuple with the most common value and its count\n",
" class_counts.most_common(1)[0][0])) # the most common value (1st element in that tuple)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"class_counts: Counter({'e': 3488, 'p': 2156}); most_common(1): [('e', 3488)], most_common(1)[0][0]: e\n"
]
}
],
"prompt_number": 83
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following variation does not use a list comprehension:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class_values = []\n",
"for instance in clean_instances:\n",
" class_values.append(instance[0])\n",
" \n",
"class_counts = Counter(class_values)\n",
"print ('class_counts: {}; most_common(1): {}, most_common(1)[0][0]: {}'.format(\n",
" class_counts, # the Counter object\n",
" class_counts.most_common(1), # returns a list in which the 1st element is a tuple with the most common value and its count\n",
" class_counts.most_common(1)[0][0])) # the most common value (1st element in that tuple)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"class_counts: Counter({'e': 3488, 'p': 2156}); most_common(1): [('e', 3488)], most_common(1)[0][0]: e\n"
]
}
],
"prompt_number": 84
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before putting all this together to define a decision tree construction function, it may be helpful to cover a few additional aspects of Python the function will utilize."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python offers a very flexible mechanism for the [testing of truth values](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#testing-for-truth-values): in an **if** condition, any null object, zero-valued numerical expression or empty container (string, list, dictionary or tuple) is interpreted as *False* (i.e., *not True*):"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for x in [False, None, 0, 0.0, \"\", [], {}, ()]:\n",
" print('\"{}\" is'.format(x), end=' ')\n",
" if x:\n",
" print(True)\n",
" else:\n",
" print(False)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\"False\" is False\n",
"\"None\" is False\n",
"\"0\" is False\n",
"\"0.0\" is False\n",
"\"\" is False\n",
"\"[]\" is False\n",
"\"{}\" is False\n",
"\"()\" is False\n"
]
}
],
"prompt_number": 85
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python also offers a [conditional expression (ternary operator)](http://docs.python.org/2/reference/expressions.html#conditional-expressions) that allows the functionality of an if/else statement that returns a value to be implemented as an expression. For example, the if/else statement in the code above could be implemented as a conditional expression as follows:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for x in [False, None, 0, 0.0, \"\", [], {}, ()]:\n",
" print('\"{}\" is {}'.format(x, True if x else False)) # using conditional expression as second argument to format()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\"False\" is False\n",
"\"None\" is False\n",
"\"0\" is False\n",
"\"0.0\" is False\n",
"\"\" is False\n",
"\"[]\" is False\n",
"\"{}\" is False\n",
"\"()\" is False\n"
]
}
],
"prompt_number": 86
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python function definitions can specify [default parameter values](http://docs.python.org/2/tutorial/controlflow.html#default-argument-values) indicating the value those parameters will have if no argument is explicitly provided when the function is called. Arguments can also be passed using [keyword parameters](http://docs.python.org/2/tutorial/controlflow.html#keyword-arguments) indicting which parameter will be assigned a specific argument value (which may or may not correspond to the order in which the parameters are defined).\n",
"\n",
"The [Python Tutorial page on default parameters](http://docs.python.org/2/tutorial/controlflow.html#default-argument-values) includes the following warning:\n",
"\n",
"> Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. \n",
"\n",
"Thus it is generally better to use the Python null object, `None`, rather than an empty `list` (`[]`), `dict` (`{}`) or other mutable data structure when specifying default parameter values for any of those data types."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def parameter_test(parameter1=None, parameter2=None):\n",
" '''Prints the values of parameter1 and parameter2'''\n",
" print('parameter1: {}; parameter2: {}'.format(parameter1, parameter2))\n",
" \n",
"parameter_test() # no args are required\n",
"parameter_test(1) # if any args are provided, 1st arg gets assigned to parameter1\n",
"parameter_test(1, 2) # 2nd arg gets assigned to parameter2\n",
"parameter_test(2) # remember: if only 1 arg, 1st arg gets assigned to arg1\n",
"parameter_test(parameter2=2) # can use keyword to [only] provide an explicit value for parameter2\n",
"parameter_test(parameter2=2, parameter1=1) # can use keywords for either arg, in either order"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"parameter1: None; parameter2: None\n",
"parameter1: 1; parameter2: None\n",
"parameter1: 1; parameter2: 2\n",
"parameter1: 2; parameter2: None\n",
"parameter1: None; parameter2: 2\n",
"parameter1: 1; parameter2: 2\n"
]
}
],
"prompt_number": 87
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Exercise 9: define majority_value()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Define a function, `majority_value(instances, class_index)`, that returns the most frequently occurring value of `class_index` in `instances`. The `class_index` parameter should be optional, and have a default value of `0` (zero)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# your definition of majority_value(instances) here\n",
"\n",
"# delete 'simple_ml.' below to test your function:\n",
"print('Majority value of index {}: {}'.format(\n",
" 0, simple_ml.majority_value(clean_instances))) # note: relying on default parameter here\n",
"# although there is only one class_index for the dataset, we'll test it by providing non-default values\n",
"print('Majority value of index {}: {}'.format(\n",
" 1, simple_ml.majority_value(clean_instances, 1))) # supplyling an optional 2nd argument\n",
"print('Majority value of index {}: {}'.format(\n",
" 2, simple_ml.majority_value(clean_instances, class_index=2))) # supplying argument as a keyword"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Majority value of index 0: e\n",
"Majority value of index 1: x\n",
"Majority value of index 2: y\n"
]
}
],
"prompt_number": 88
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The recursive `create_decision_tree()` function below uses an optional parameter, `class_index`, which defaults to `0`. This is to accommodate other datasets in which the class label is the last element on each line (which would be most easily specified by using a `-1` value). Most data files in the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets.html) have the class labels as either the first element or the last element.\n",
"\n",
"To show how the decision tree is being built, an optional `trace` parameter, when non-zero, will generate some trace information as the tree is constructed. The indentation level is incremented with each recursive call via the use of the conditional expression (ternary operator), `trace + 1 if trace else 0`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def create_decision_tree(instances, candidate_attribute_indexes=None, class_index=0, default_class=None, trace=0):\n",
" '''Returns a new decision tree trained on a list of instances.\n",
" \n",
" The tree is constructed by recursively selecting and splitting instances based on \n",
" the highest information_gain of the candidate_attribute_indexes.\n",
" \n",
" The class label is found in position class_index.\n",
" \n",
" The default_class is the majority value for the current node's parent in the tree.\n",
" A positive (int) trace value will generate trace information with increasing levels of indentation.\n",
" \n",
" Derived from the simplified ID3 algorithm presented in Building Decision Trees in Python by Christopher Roach,\n",
" http://www.onlamp.com/pub/a/python/2006/02/09/ai_decision_trees.html?page=3'''\n",
" \n",
" # if no candidate_attribute_indexes are provided, assume that we will use all but the target_attribute_index\n",
" if candidate_attribute_indexes is None:\n",
" candidate_attribute_indexes = [i for i in range(len(instances[0])) if i != class_index]\n",
" #candidate_attribute_indexes.remove(class_index)\n",
" \n",
" class_labels_and_counts = Counter([instance[class_index] for instance in instances])\n",
"\n",
" # If the dataset is empty or the candidate attributes list is empty, return the default value\n",
" if not instances or not candidate_attribute_indexes:\n",
" if trace:\n",
" print('{}Using default class {}'.format('< ' * trace, default_class))\n",
" return default_class\n",
" \n",
" # If all the instances have the same class label, return that class label\n",
" elif len(class_labels_and_counts) == 1:\n",
" class_label = class_labels_and_counts.most_common(1)[0][0]\n",
" if trace:\n",
" print('{}All {} instances have label {}'.format(\n",
" '< ' * trace, len(instances), class_label))\n",
" return class_label\n",
" else:\n",
" default_class = simple_ml.majority_value(instances, class_index)\n",
"\n",
" # Choose the next best attribute index to best classify the instances\n",
" best_index = simple_ml.choose_best_attribute_index(\n",
" instances, candidate_attribute_indexes, class_index) \n",
" if trace:\n",
" print('{}Creating tree node for attribute index {}'.format('> ' * trace, best_index))\n",
"\n",
" # Create a new decision tree node with the best attribute index and an empty dictionary object (for now)\n",
" tree = {best_index:{}}\n",
"\n",
" # Create a new decision tree sub-node (branch) for each of the values in the best attribute field\n",
" partitions = simple_ml.split_instances(instances, best_index)\n",
"\n",
" # Remove that attribute from the set of candidates for further splits\n",
" remaining_candidate_attribute_indexes = [i for i in candidate_attribute_indexes if i != best_index]\n",
" for attribute_value in partitions:\n",
" if trace:\n",
" print('{}Creating subtree for value {} ({}, {}, {}, {})'.format(\n",
" '> ' * trace,\n",
" attribute_value, \n",
" len(partitions[attribute_value]), \n",
" len(remaining_candidate_attribute_indexes), \n",
" class_index, \n",
" default_class))\n",
" \n",
" # Create a subtree for each value of the the best attribute\n",
" subtree = create_decision_tree(\n",
" partitions[attribute_value],\n",
" remaining_candidate_attribute_indexes,\n",
" class_index,\n",
" default_class,\n",
" trace + 1 if trace else 0)\n",
"\n",
" # Add the new subtree to the empty dictionary object in the new tree/node we just created\n",
" tree[best_index][attribute_value] = subtree\n",
"\n",
" return tree\n",
"\n",
"# split instances into separate training and testing sets\n",
"training_instances = clean_instances[:-20]\n",
"testing_instances = clean_instances[-20:]\n",
"tree = create_decision_tree(training_instances, trace=1) # remove trace=1 to turn off tracing\n",
"print(tree)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"> Creating tree node for attribute index 5\n",
"> Creating subtree for value a (400, 21, 0, e)\n",
"< < All 400 instances have label e\n",
"> Creating subtree for value c (192, 21, 0, e)\n",
"< < All 192 instances have label p\n",
"> Creating subtree for value f (1584, 21, 0, e)\n",
"< < All 1584 instances have label p\n",
"> Creating subtree for value m (28, 21, 0, e)\n",
"< < All 28 instances have label p\n",
"> Creating subtree for value l (400, 21, 0, e)\n",
"< < All 400 instances have label e\n",
"> Creating subtree for value n (2764, 21, 0, e)\n",
"> > Creating tree node for attribute index 20\n",
"> > Creating subtree for value k (1296, 20, 0, e)\n",
"< < < All 1296 instances have label e\n",
"> > Creating subtree for value r (72, 20, 0, e)\n",
"< < < All 72 instances have label p\n",
"> > Creating subtree for value w (100, 20, 0, e)\n",
"> > > Creating tree node for attribute index 21\n",
"> > > Creating subtree for value y (24, 19, 0, e)\n",
"< < < < All 24 instances have label e\n",
"> > > Creating subtree for value c (16, 19, 0, e)\n",
"< < < < All 16 instances have label p\n",
"> > > Creating subtree for value v (60, 19, 0, e)\n",
"< < < < All 60 instances have label e\n",
"> > Creating subtree for value n (1296, 20, 0, e)\n",
"< < < All 1296 instances have label e\n",
"> Creating subtree for value p (256, 21, 0, e)\n",
"< < All 256 instances have label p\n",
"{5: {'a': 'e', 'c': 'p', 'f': 'p', 'm': 'p', 'l': 'e', 'n': {20: {'k': 'e', 'r': 'p', 'w': {21: {'y': 'e', 'c': 'p', 'v': 'e'}}, 'n': 'e'}}, 'p': 'p'}}\n"
]
}
],
"prompt_number": 89
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The structure of the tree shown above is rather difficult to discern from the normal printed representation of a dictionary.\n",
"\n",
"The Python [**`pprint`**](http://docs.python.org/2/library/pprint.html) module has a number of useful methods for pretty-printing or formatting objects in a more human readable way.\n",
"\n",
"The [**`pprint.pprint(object, stream=None, indent=1, width=80, depth=None)`**](http://docs.python.org/2/library/pprint.html#pprint.pprint) method will print `object` to a `stream` (a default value of `None` will dictate the use of [sys.stdout](http://docs.python.org/2/library/sys.html#sys.stdout), the same destination as `print` function output), using `indent` spaces to differentiate nesting levels, using up to a maximum `width` columns and up to to a maximum nesting level `depth` (`None` indicating no maximum).\n",
"\n",
"We will use the a variation on the import statement that imports one or more functions into the current namespace:\n",
"\n",
" from pprint import pprint\n",
" \n",
"This will to enable us to use `pprint()` rather than having to use dotted notation, i.e., `pprint.pprint()`. \n",
"\n",
"Note that if we wanted to define our own `pprint()` function, we would be best only using\n",
"\n",
" import pprint\n",
" \n",
"so that we can still access the `pprint()` function in the `pprint` module (since defining `pprint()` in the current namespace would otherwise override the imported definition of the function)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from pprint import pprint\n",
"\n",
"pprint(tree)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"{5: {'a': 'e',\n",
" 'c': 'p',\n",
" 'f': 'p',\n",
" 'l': 'e',\n",
" 'm': 'p',\n",
" 'n': {20: {'k': 'e',\n",
" 'n': 'e',\n",
" 'r': 'p',\n",
" 'w': {21: {'c': 'p', 'v': 'e', 'y': 'e'}}}},\n",
" 'p': 'p'}}\n"
]
}
],
"prompt_number": 90
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Classifying Instances with a Simple Decision Tree"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Usually, when we construct a decision tree based on a set of *training* instances, we do so with the intent of using that tree to classify a set of one or more *testing* instances.\n",
"\n",
"We will define a function, **`classify(tree, instance, default_class=None)`**, to use a decision `tree` to classify a single `instance`, where an optional `default_class` can be specified as the return value if the instance represents a set of attribute values that don't have a representation in the decision tree.\n",
"\n",
"We will use a design pattern in which we will use a series of `if` statements, each of which returns a value if the condition is true, rather than a nested series of `if`, `elif` and/or `else` clauses, as it helps constrain the levels of indentation in the function."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def classify(tree, instance, default_class=None):\n",
" '''Returns a classification label for instance, given a decision tree'''\n",
" if not tree:\n",
" return default_class\n",
" if not isinstance(tree, dict): \n",
" return tree\n",
" attribute_index = list(tree.keys())[0] # using list(dict.keys()) for Python 3 compatibility\n",
" attribute_values = list(tree.values())[0]\n",
" instance_attribute_value = instance[attribute_index]\n",
" if instance_attribute_value not in attribute_values:\n",
" return default_class\n",
" return classify(attribute_values[instance_attribute_value], instance, default_class)\n",
"\n",
"for instance in testing_instances:\n",
" predicted_label = classify(tree, instance)\n",
" actual_label = instance[0]\n",
" print('predicted: {}; actual: {}'.format(predicted_label, actual_label))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"predicted: p; actual: p\n",
"predicted: p; actual: p\n",
"predicted: p; actual: p\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: p; actual: p\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: p; actual: p\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: p; actual: p\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: e; actual: e\n",
"predicted: p; actual: p\n",
"predicted: p; actual: p\n"
]
}
],
"prompt_number": 91
},
{
"cell_type": "heading",
"level": 3,
"metadata": {},
"source": [
"Evaluating the Accuracy of a Simple Decision Tree"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is often helpful to evaluate the performance of a model using a dataset not used in the training of that model. In the simple example shown above, we used all but the last 20 instances to train a simple decision tree, then classified those last 20 instances using the tree.\n",
"\n",
"The advantage of this training/testing split is that visual inspection of the classifications (sometimes called *predictions*) is relatively straightforward, revealing that all 20 instances were correctly classified.\n",
"\n",
"There are a variety of metrics that can be used to evaluate the performance of a model. [Scikit Learn's Model Evaluation](http://scikit-learn.org/stable/modules/model_evaluation.html) library provides an overview and implementation of several possible metrics. For now, we'll simply measure the *accuracy* of a model, i.e., the percentage of testing instances that are correctly classified (*true positives* and *true negatives*).\n",
"\n",
"The accuracy of the model above, given the set of 20 testing instances, is 100% (20/20).\n",
"\n",
"The function below calculates the classification accuracy of a `tree` over a set of `testing_instances` (with an optional `class_index` parameter indicating the position of the class label in each instance)."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def classification_accuracy(tree, testing_instances, class_index=0, default_class=None):\n",
" '''Returns the accuracy of classifying testing_instances with tree, where the class label is in position class_index'''\n",
" num_correct = 0\n",
" for i in range(len(testing_instances)):\n",
" prediction = classify(tree, testing_instances[i], default_class)\n",
" actual_value = testing_instances[i][class_index]\n",
" if prediction == actual_value:\n",
" num_correct += 1\n",
" return num_correct / len(testing_instances)\n",
"\n",
"print(classification_accuracy(tree, testing_instances))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1.0\n"
]
}
],
"prompt_number": 92
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`zip([iterable, ...])`**](http://docs.python.org/2.7/library/functions.html#zip) function combines 2 or more sequences or iterables; the function returns a list of tuples, where the *i*th tuple contains the *i*th element from each of the argument sequences or iterables."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"zip([0, 1, 2], ['a', 'b', 'c'])"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 93,
"text": [
"[(0, 'a'), (1, 'b'), (2, 'c')]"
]
}
],
"prompt_number": 93
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use [list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions), the `Counter` class and the `zip()` function to modify `classification_accuracy()` so that it returns a packed tuple with \n",
"\n",
"* the number of correctly classified instances\n",
"* the number of incorrectly classified instances\n",
"* the percentage of instances correctly classified"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def classification_accuracy(tree, instances, class_index=0, default_class=None):\n",
" '''Returns the accuracy of classifying testing_instances with tree, where the class label is in position class_index'''\n",
" predicted_labels = [classify(tree, instance, default_class) for instance in instances]\n",
" actual_labels = [x[class_index] for x in instances]\n",
" counts = Counter([x == y for x, y in zip(predicted_labels, actual_labels)])\n",
" return counts[True], counts[False], counts[True] / len(instances)\n",
"\n",
"print(classification_accuracy(tree, testing_instances))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"(20, 0, 1.0)\n"
]
}
],
"prompt_number": 94
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We sometimes want to partition the instances into subsets of equal sizes to measure performance. One metric this partitioning allows us to compute is a [learning curve](https://en.wikipedia.org/wiki/Learning_curve), i.e., assess how well the model performs based on the size of its training set. Another use of these partitions (aka *folds*) would be to conduct an [*n-fold cross validation*](https://en.wikipedia.org/wiki/Cross-validation_(statistics)) evaluation.\n",
"\n",
"The following function, **`partition_instances(instances, num_partitions)`**, partitions a set of `instances` into `num_partitions` relatively equally sized subsets.\n",
"\n",
"We'll use this as yet another opportunity to demonstrate the power of using list comprehensions, this time, to condense the use of nested `for` loops."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def partition_instances(instances, num_partitions):\n",
" '''Returns a list of relatively equally sized disjoint sublists (partitions) of the list of instances'''\n",
" return [[instances[j] for j in range(i, len(instances), num_partitions)] \\\n",
" for i in range(num_partitions)]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 95
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before testing this function on the 5644 `clean_instances` from the UCI mushroom dataset, let's create a small number of simplified instances to verify that the function has the desired behavior."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"instance_length = 3\n",
"num_instances = 5\n",
"\n",
"simplified_instances = [[j for j in range(i, instance_length + i)] for i in range(num_instances)]\n",
"\n",
"print('Instances:', simplified_instances)\n",
"partitions = partition_instances(simplified_instances, 2)\n",
"print('Partitions:', partitions)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Instances: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]\n",
"Partitions: [[[0, 1, 2], [2, 3, 4], [4, 5, 6]], [[1, 2, 3], [3, 4, 5]]]\n"
]
}
],
"prompt_number": 96
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following variations do not use list comprehensions."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def partition_instances(instances, num_partitions):\n",
" '''Returns a list of relatively equally sized disjoint sublists (partitions) of the list of instances'''\n",
" partitions = []\n",
" for i in range(num_partitions):\n",
" partition = []\n",
" # iterate over instances starting at position i in increments of num_paritions\n",
" for j in range(i, len(instances), num_partitions): \n",
" partition.append(instances[j])\n",
" partitions.append(partition)\n",
" return partitions\n",
"\n",
"simplified_instances = []\n",
"for i in range(num_instances):\n",
" new_instance = []\n",
" for j in range(i, instance_length + i):\n",
" new_instance.append(j)\n",
" simplified_instances.append(new_instance)\n",
"\n",
"print('Instances:', simplified_instances)\n",
"partitions = partition_instances(simplified_instances, 2)\n",
"print('Partitions:', partitions)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Instances: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]\n",
"Partitions: [[[0, 1, 2], [2, 3, 4], [4, 5, 6]], [[1, 2, 3], [3, 4, 5]]]\n"
]
}
],
"prompt_number": 97
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The [**`enumerate(sequence, start=0)`**](http://docs.python.org/2.7/library/functions.html#enumerate) function creates an iterator that successively returns the index and value of each element in a `sequence`, beginning at the `start` index."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for i, x in enumerate(['a', 'b', 'c']):\n",
" print(i, x)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0 a\n",
"1 b\n",
"2 c\n"
]
}
],
"prompt_number": 98
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use `enumerate()` to facilitate slightly more rigorous testing of our `partition_instances` function on our `simplified_instances`."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for i in range(5):\n",
" print('\\n# partitions:', i)\n",
" for j, partition in enumerate(partition_instances(simplified_instances, i)):\n",
" print('partition {}: {}'.format(j, partition))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"\n",
"# partitions: 0\n",
"\n",
"# partitions: 1\n",
"partition 0: [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]\n",
"\n",
"# partitions: 2\n",
"partition 0: [[0, 1, 2], [2, 3, 4], [4, 5, 6]]\n",
"partition 1: [[1, 2, 3], [3, 4, 5]]\n",
"\n",
"# partitions: 3\n",
"partition 0: [[0, 1, 2], [3, 4, 5]]\n",
"partition 1: [[1, 2, 3], [4, 5, 6]]\n",
"partition 2: [[2, 3, 4]]\n",
"\n",
"# partitions: 4\n",
"partition 0: [[0, 1, 2], [4, 5, 6]]\n",
"partition 1: [[1, 2, 3]]\n",
"partition 2: [[2, 3, 4]]\n",
"partition 3: [[3, 4, 5]]\n"
]
}
],
"prompt_number": 99
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Returning our attention to the UCI mushroom dataset, the following will partition our `clean_instances` into 10 relatively equally sized disjoint subsets. We will use a list comprehension to print out the length of each partition"
]
},
{