Lab 1: Review of Scientific Computing in Python#

This lab is adapted from AM207 (Harvard). Data files are in the book’s data/ folder. Worked solutions are collapsed: try each exercise before expanding them.

In this lab

  1. What Is Data?

  2. Exploring Data: Data Visualization

  3. Computational Tools

What is Data?#

Where Does Data Come From?#

Internal sources: already collected by or is part of the overall data collection of you organization.

Existing External Sources: available in ready to read format from an outside source for free or for a fee.

External Sources Requiring Collection Efforts: available from external source but acquisition requires special processing.

What Does Data Look Like?#

Simple or atomic data:

  • Numeric: integers, floats

  • Boolean: binary or true false values

  • Strings: sequence of symbols

What Does Data Look Like?#

Compound, composed of a bunch of atomic types:

  • Date and time: compound value with a specific structure

  • Lists: a list is a sequence of values

  • Dictionaries: collections of key-value pairs, a pair of values x : y, where x is usually a string called key representing the “name” of the value, and y is a value of any type.

    Example: Student record

    • First: Weiwei

    • Last: Pan

    • Nationality: USA

How is your data represented and stored?#

Data formats:

  • Tabular Data: a dataset that is a two-dimensional table, where each row typically represents a single data record, and each column represents one type of measurement (csv, xlsx etc.).

  • Structured Data: each data record is presented in a form of a, possibly complex and multi-tiered, dictionary (json, xml etc.)

  • Semistructured Data: not all records are represented by the same set of keys or some data records are not represented using the key-value pair structure.

Tabular Data#

In tabular data, each row or observation represents a set of measurements of a single object or event.

../_images/fig2.jpg

Each type of measurement is an attribute of the data. The number of attributes is the dimension of the data.

Types of Attributes in Tabular Data#

It’s vital to distinguish between classes of attributes based on the type of values they take on.

  • Quantitative attribute: a real valued number whose values can be ordered.

    Example: Height is a quantitative attribute

  • Categorical attribute: a real valued or string with no inherent order among the values.

    Example: “What kind of pet you have” is a categorical attribute

Is the data any good?#

  • Missing values: how do we fill in?

  • Wrong values: how can we detect and correct?

  • Messy format: how can we convert structured or semistructured data into tabular data?

  • Not usable: what if the data cannot answer the question posed?

Exploring the Data: Data Visualization#

Why Data Visualization?#

If I tell you that the average score for the final exam is: 7.64/15.

What does that suggest?

Why Data Visualization?#

If I then show you the following graph, what does it suggest?

../_images/fig7.jpg

What is Data Visualization Good For?#

Analyze:

  • Identify hidden patterns and trends

  • Help formulate/test hypotheses

  • Help determine the next step in analysis/modeling

What is Data Visualization Good For?#

Communicate:

  • Present information and ideas succinctly

  • Provide evidence and support

  • Influence and persuade

Types of Data Visualization#

What do you want your visualization to show about your data?

  • Distribution: how a variable or variables in the dataset distribute over a range of possible values.

  • Relationship: how the values of multiple variables in the dataset relate

  • Composition: how the dataset breaks down into subgroups

  • Comparison: how trends in multiple variable or datasets compare

Visualizing Distributions#

A histogram is a way to visualize how a quantitative attribute is distributed across certain values.

../_images/fig8.jpg

Note: Trends in histograms are sensitive to number of bins.

Visualizing Distributions#

A bar chart is a way to visualize how a categorical attribute is distributed across certain values.

../_images/fig4.jpg

Visualizing Relationships#

A scatter plot is a way to visualize the relationship between two different attributes.

../_images/fig9.jpg

Visualizing Comparisons of Subgroups#

Plotting multiple histograms or curves on the same axes is a way to visualize how different subgroups of data compare.

For example: the following are the blood-glucose distributions of three subgroups within the dataset.

../_images/fig101.jpg

Generating Hypotheses#

We can see that birth weight is positively correlated with femur length.

../_images/fig11.jpg

Can we describe exactly how they are correlated?

Generating Hypotheses#

We can see that types of iris seem to be distinguished by petal and sepal lengths.

../_images/fig12.jpg

Can we predict the type of iris given petal and sepal lengths?

Computational Tools#

Computing Tools#

In all computation in this book, we will be using python, for which there are many robust and well documented libraries for machine learning and data science.

Specifically, we will use

  1. Jupyter notebook - a web-based interactive development environment for Jupyter notebooks, code, and data.

  2. colab notebook - a Google web app for creating interactive document containing text, equations, live code and outputs.

  3. pandas - a python library for reading and manipulating data

  4. matplotlib - a python library for data visualization

  5. numpy - a python library for manipulating numeric data

  6. scikit-learn - a python library with many machine learning models

  7. keras - a python library for deep learning

  8. autograd - a python library for automatic differentiation

  9. pymc3 - a python library for performing sampling based inference on models

Jupyter or colab Notebooks#

What Does Colab Notebook Look Like?#

Go to https://colab.research.google.com/

../_images/fig13.jpg

What Does Colab Notebook Look Like?#

Each notebook consists of blocks of cells. Each cell can be of two types: (1) rich text (Markdown) cells or (2) code cells.

../_images/fig14.jpg

What Does Colab Notebook Look Like?#

Code is executed by an “computational engine” called the kernel (IPython). The output of the code is displayed directly below..

../_images/fig15.jpg

What Does Colab Notebook Look Like?#

Each cell can be executed independently, but once a block of code is executed, it lives in the memory of the kernel.

../_images/fig16.jpg

Learning python#

Many readings, cheatsheets and tutorials are available online for mastering general python programming as well as using python libraries for data manipulation/visualization.

Tips for learning a programming language:

  1. Don’t read code line by line (at first)

  2. Copy as much as possible (learn patterns and templates)

  3. Don’t be afraid to play (trial and error)

  4. Read documentation!

pandas: Reading and Manipulating Data#

pandas#

pandas provides ways of storing tabular data along with labels on the rows and columns.

To use any python library, we must include the line

import pandas as pd

After which we may use any function or object in this library using for example, pd.Series().

pandas Series#

The pandas Series object stores a 1D array of data with an index object (labels).

../_images/fig21.jpg

pandas Series#

Each pandas series has a .values and an .index attribute.

../_images/fig22.jpg

pandas DataFrames#

The pandas DataFrame object stores a 2D table of data with column and row index object (labels).

../_images/fig23.jpg

Each column in the data frame is a series.

Reading Data with pandas#

We can import tabular data in a csv file into a data frame:

../_images/fig24.jpg

Basic Data Exploration with pandas#

We should start by checking how large is the data.

We do this by checking the shape of the DataFrame.

../_images/fig26.jpg

Basic Data Exploration with pandas#

We should start by getting a rough sense of what’s in the data.

../_images/fig25.jpg

Basic Data Exploration with pandas#

The .head() function returns the first N rows of your data frame!

../_images/fig27.jpg

Basic Data Exploration with pandas#

The .describe() function returns the descriptive stats for each numeric column as a data frame object!

../_images/fig28.jpg

Basic Data Manipulation with pandas#

Accessing a column by label:

../_images/fig29.jpg

Basic Data Manipulation with pandas#

Accessing columns by criteria (filtering):

../_images/fig31.jpg

numpy: Numerical Computation#

numpy Arrays#

numpy is a package for scientific computation.

Notably, it provides an multi-dimensional array object which optimizes storing and manipulating data.

Each array has a shape, recorded as a tuple (n, m, ...).

../_images/numpy.jpg

1D Arrays#

Creating 1D arrays:

import numpy as np
my_array = np.array([1, 2, 3, 4])
my_array.shape
(4,)

Computing summary statistic for 1D arrays:

print('mean: {}, std: {}'.format(my_array.mean(), my_array.std()))
mean: 2.5, std: 1.118033988749895

2D Arrays#

Creating 2D arrays:

my_array = np.array([[1, 2], [3, 4]])
my_array
array([[1, 2],
       [3, 4]])
my_array.shape
(2, 2)

Indexing 2D Arrays#

The element at the n-th row and the m-th column is indexed as [n, m]. Just like lists, you can also get multiple array values at a time:

../_images/np_index.jpg

Filtering Arrays#

You can get values from an array that satisfy a bunch of criteria!

my_array == 1
array([[ True, False],
       [False, False]])
my_array[(my_array == 1) | (my_array == 2)]
array([1, 2])

The numpy.linalg Module#

The numpy linear algebra functions provide implementation standard linear algebra algorithms:

A = np.diag([5, 6])
B = np.ones((2, 2)) + A

print(np.linalg.inv(A.dot(B)))
[[ 0.03414634 -0.00406504]
 [-0.00487805  0.02439024]]

The numpy.random Module#

The functions in random simulate sample from different statistical distributions:

sample = np.random.normal(0, 1, size=1)
sample
array([1.36111975])
sample = np.random.multivariate_normal([0, 0], np.eye(2), size=1)
sample
array([[0.96233174, 0.57055047]])

matplotlib: Visualization#

Data Visualization with matplotlib#

matplotlib is a plotting library, the pyplot module contains a set of functions especially useful for generating a wide range of visualizations:

import matplotlib.pyplot as plt
%matplotlib inline

samples = np.random.multivariate_normal([0, 0], np.eye(2), size=1000)
fig, ax = plt.subplots(1, 1, figsize=(10, 5 ))
ax.scatter(samples[:, 0], samples[:, 1], color='orange', alpha=0.4)
plt.show()
../_images/55f79176fe64d3505a61eaba5f7a9ee5777b254d58f7ec41335b302d893749ea.png

Common Types of Visualizations#

../_images/plt_fn.jpg

Exercise: Simulation of Statistical Models#

Model of USPS Package Processing Time#

In this problem we want to model how much time it takes an USPS package processing system to process packages that arrive in a day.

Assumptions:

  1. packages arrive randomly in any given hour according to a Poisson distribution. That is, the number of packages \(N\) is distributed as \(Poi(\lambda)\), with \(\lambda = 3\).

  2. each package has a random size \(S\) (measured in \(in^3\)) and weight \(W\) (measured in pounds) jointly distributed as \(\mathcal{N}\left([120, 4], \left[\begin{array}{cc} 1.5& 1\\ 1 & 1.5 \end{array} \right] \right)\).

  3. processing time \(T\) (in seconds) for each package is given by \(T = 60 + 0.6 W + 0.2 S + \epsilon\), \(\epsilon \sim \mathcal{N}(0, 5)\).

Tasks:

  1. Compute the expected total weight and size of packages that arrive over a single day. Compute the expected average weight and size of packages that arrive over a single day.

  2. Compute the expected number of packages that arrives in a single day.

  3. Compute the expected processing time of a single package.

  4. Compute the expected processing time of all packages over a single day.