Probabilistic Programming
=====
and Bayesian Methods for Hackers
========

##### Version 0.1

`Original content created by Cam Davidson-Pilon`

`Ported to Python 3 and PyMC3 by Max Margenot (@clean_utensils) and Thomas Wiecki (@twiecki) at Quantopian (@quantopian)`
___

Welcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!

```python

```

Chapter 1
======
***

The Philosophy of Bayesian Inference
------

> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...

If you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain.  Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives.

### The Bayesian state of mind

Bayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians.

The Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability.

For this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability.

Bayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?

Notice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:

- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result.

-  Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug.

-  A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs.

This philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist.

To align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.

John Maynard Keynes, a great economist and thinker, said "When the facts change, I change my mind. What do you do, sir?" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$:

1\. $P(A): \;\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\;\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.

2\.   $P(A): \;\;$  This big, complex code likely has a bug in it. $P(A | X): \;\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.

3\.  $P(A):\;\;$ The patient could have any number of diseases. $P(A | X):\;\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.

It's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others).

By introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*.

### Bayesian Inference in Practice

 If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.

For example, in our debugging problem above, calling the frequentist function with the argument "My code passed all $X$ tests; is my code bug-free?" would return a *YES*. On the other hand, asking our Bayesian function "Often my code has bugs. My code passed all $X$ tests; is my code bug-free?" would return something very different: probabilities of *YES* and *NO*. The function might return:

>    *YES*, with probability 0.8; *NO*, with probability 0.2

This is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument:  *"Often my code has bugs"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences.

#### Incorporating evidence

As we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like "I expect the sun to explode today", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.

Denote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \rightarrow \infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset.

One may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:

> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is "large enough," you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were "enough" you'd already be on to the next problem for which you need more data.

### Are frequentist methods incorrect then?

**No.**

Frequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.

#### A note on *Big Data*
Paradoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask "Do I really have big data?")

The much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as  Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets.

### Our Bayesian framework

We are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.

Secondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:

\begin{align}
 P( A | X ) = & \frac{ P(X | A) P(A) } {P(X) } \\\\[5pt]
& \propto P(X | A) P(A)\;\; (\propto \text{is proportional to })
\end{align}

The above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.

##### Example: Mandatory coin-flip example

Every statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be.

We begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data.

Below we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).

```python
"""
The book uses a custom matplotlibrc file, which provides the unique styles for
matplotlib plots. If executing this book, and you wish to use the book's
styling, provided are two options:
    1. Overwrite your own matplotlibrc file with the rc-file provided in the
       book's styles/ dir. See http://matplotlib.org/users/customizing.html
    2. Also in the styles is  bmh_matplotlibrc.json file. This can be used to
       update the styles in only this notebook. Try running the following code:

        import json
        s = json.load(open("../styles/bmh_matplotlibrc.json"))
        matplotlib.rcParams.update(s)

"""

# The code below can be passed over, as it is currently not important, plus it
# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!
%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
figsize(11, 9)

import scipy.stats as stats

dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)

# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
    sx = plt.subplot(len(n_trials)/2, 2, k+1)
    plt.xlabel("$p$, probability of heads") \
        if k in [0, len(n_trials)-1] else None
    plt.setp(sx.get_yticklabels(), visible=False)
    heads = data[:N].sum()
    y = dist.pdf(x, 1 + heads, 1 + N - heads)
    plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
    plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
    plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)

    leg = plt.legend()
    leg.get_frame().set_alpha(0.4)
    plt.autoscale(tight=True)

plt.suptitle("Bayesian updating of posterior probabilities",
             y=1.02,
             fontsize=14)

plt.tight_layout()
```

The posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line).

Notice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head?). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.

The next example is a simple demonstration of the mathematics of Bayesian inference.

##### Example: Bug, or just sweet, unintended feature?

Let $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$.

We are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.

What is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests.

$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\sim A\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:

\begin{align}
P(X ) & = P(X \text{ and } A) + P(X \text{ and } \sim A) \\\\[5pt]
 & = P(X|A)P(A) + P(X | \sim A)P(\sim A)\\\\[5pt]
& = P(X|A)p + P(X | \sim A)(1-p)
\end{align}

We have already computed $P(X|A)$ above. On the other hand, $P(X | \sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\sim A) = 0.5$. Then

\begin{align}
P(A | X) & = \frac{1\cdot p}{ 1\cdot p +0.5 (1-p) } \\\\
& = \frac{ 2 p}{1+p}
\end{align}
This is the posterior probability. What does it look like as a function of our prior, $p \in [0,1]$?

```python
figsize(12.5, 4)
p = np.linspace(0, 1, 50)
plt.plot(p, 2*p/(1+p), color="#348ABD", lw=3)
#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=["#A60628"])
plt.scatter(0.2, 2*(0.2)/1.2, s=140, c="#348ABD")
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel("Prior, $P(A) = p$")
plt.ylabel("Posterior, $P(A|X)$, with $P(A) = p$")
plt.title("Are there bugs in my code?");
```

We can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33.

Recall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.

Similarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities.

```python
figsize(12.5, 4)
colours = ["#348ABD", "#A60628"]

prior = [0.20, 0.80]
posterior = [1./3, 2./3]
plt.bar([0, .7], prior, alpha=0.70, width=0.25,
        color=colours[0], label="prior distribution",
        lw="3", edgecolor=colours[0])

plt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,
        width=0.25, color=colours[1],
        label="posterior distribution",
        lw="3", edgecolor=colours[1])

plt.xticks([0.20, .95], ["Bugs Absent", "Bugs Present"])
plt.title("Prior and Posterior probability of bugs present")
plt.ylabel("Probability")
plt.legend(loc="upper left");
```

Notice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.

This was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.

_______

## Probability Distributions

**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter.

We can divide random variables into three classifications:

-   **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...

-   **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.

- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories.

### Discrete Case
If $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:

$$P(Z = k) =\frac{ \lambda^k e^{-\lambda} }{k!}, \; \; k=0,1,2, \dots $$

$\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\lambda$ can be any positive number. By increasing $\lambda$, we add more probability to larger values, and conversely by decreasing $\lambda$ we add more probability to smaller values. One can describe $\lambda$ as the *intensity* of the Poisson distribution.

Unlike $\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members.

If a random variable $Z$ has a Poisson mass distribution, we denote this by writing

$$Z \sim \text{Poi}(\lambda) $$

One useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:

$$E\large[ \;Z\; | \; \lambda \;\large] = \lambda $$

We will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\lambda$ values. The first thing to notice is that by increasing $\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.

```python
figsize(12.5, 4)

import scipy.stats as stats
a = np.arange(16)
poi = stats.poisson
lambda_ = [1.5, 4.25]
colours = ["#348ABD", "#A60628"]

plt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],
        label="$\lambda = %.1f$" % lambda_[0], alpha=0.60,
        edgecolor=colours[0], lw="3")

plt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],
        label="$\lambda = %.1f$" % lambda_[1], alpha=0.60,
        edgecolor=colours[1], lw="3")

plt.xticks(a + 0.4, a)
plt.legend()
plt.ylabel("probability of $k$")
plt.xlabel("$k$")
plt.title("Probability mass function of a Poisson random variable; differing \
$\lambda$ values");
```

### Continuous Case
Instead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:

$$f_Z(z | \lambda) = \lambda e^{-\lambda z }, \;\; z\ge 0$$

Like a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\lambda$ values.

When a random variable $Z$ has an exponential distribution with parameter $\lambda$, we say *$Z$ is exponential* and write

$$Z \sim \text{Exp}(\lambda)$$

Given a specific $\lambda$, the expected value of an exponential random variable is equal to the inverse of $\lambda$, that is:

$$E[\; Z \;|\; \lambda \;] = \frac{1}{\lambda}$$

```python
a = np.linspace(0, 4, 100)
expo = stats.expon
lambda_ = [0.5, 1, 2]

for l, c in zip(lambda_, colours):
    plt.plot(a, expo.pdf(a, scale=1./l), lw=3,
             color=c, label="$\lambda = %.1f$" % l)
    plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)

plt.legend()
plt.ylabel("PDF at $z$")
plt.xlabel("$z$")
plt.ylim(0,1.2)
plt.title("Probability density function of an Exponential random variable;\
 differing $\lambda$");
```

### But what is $\lambda \;$?

**This question is what motivates statistics**. In the real world, $\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\lambda$. Many different methods have been created to solve the problem of estimating $\lambda$, but since $\lambda$ is never actually observed, no one can say for certain which method is best!

Bayesian inference is concerned with *beliefs* about what $\lambda$ might be. Rather than try to guess $\lambda$ exactly, we can only talk about what $\lambda$ is likely to be by assigning a probability distribution to $\lambda$.

This might seem odd at first. After all, $\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\lambda$.

##### Example: Inferring behaviour from text-message data

Let's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:

>  You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)

```python
figsize(12.5, 3.5)
count_data = np.loadtxt("data/txtdata.csv")
n_count_data = len(count_data)
plt.bar(np.arange(n_count_data), count_data, color="#348ABD")
plt.xlabel("Time (days)")
plt.ylabel("count of text-msgs received")
plt.title("Did the user's texting habits change over time?")
plt.xlim(0, n_count_data);
```

Before we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period?

How can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$,

$$ C_i \sim \text{Poisson}(\lambda)  $$

We are not sure what the value of the $\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\lambda$ increases at some point during the observations. (Recall that a higher value of $\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)

How can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\tau$), the parameter $\lambda$ suddenly jumps to a higher value. So we really have two $\lambda$ parameters: one for the period before $\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:

$$
\lambda =
\begin{cases}
\lambda_1  & \text{if } t \lt \tau \cr
\lambda_2 & \text{if } t \ge \tau
\end{cases}
$$

If, in reality, no sudden change occurred and indeed $\lambda_1 = \lambda_2$, then the $\lambda$s posterior distributions should look about equal.

We are interested in inferring the unknown $\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\lambda$. What would be good prior probability distributions for $\lambda_1$ and $\lambda_2$? Recall that $\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\alpha$.

\begin{align}
&\lambda_1 \sim \text{Exp}( \alpha ) \\\
&\lambda_2 \sim \text{Exp}( \alpha )
\end{align}

$\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\alpha$ does not influence the model too strongly, so we have some flexibility in our choice.  A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:

$$\frac{1}{N}\sum_{i=0}^N \;C_i \approx E[\; \lambda \; |\; \alpha ] = \frac{1}{\alpha}$$

An alternative, and something I encourage the reader to try, would be to have two priors: one for each $\lambda_i$. Creating two exponential distributions with different $\alpha$ values reflects our prior belief that the rate changed at some point during the observations.

What about $\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying

\begin{align}
& \tau \sim \text{DiscreteUniform(1,70) }\\\\
& \Rightarrow P( \tau = k ) = \frac{1}{70}
\end{align}

So after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.

We next turn to PyMC3, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created.

Introducing our first hammer: PyMC3
-----

PyMC3 is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC3 is so cool.

We will model the problem above using PyMC3. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC3 framework.

B. Cronin [5] has a very motivating description of probabilistic programming:

>   Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.

Because of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is.

PyMC3 code is easy to read. The only novel thing should be the syntax. Simply remember that we are representing the model's components ($\tau, \lambda_1, \lambda_2$ ) as variables.

```python
import pymc3 as pm
import theano.tensor as tt

with pm.Model() as model:
    alpha = 1.0/count_data.mean()  # Recall count_data is the
                                   # variable that holds our txt counts
    lambda_1 = pm.Exponential("lambda_1", alpha)
    lambda_2 = pm.Exponential("lambda_2", alpha)

    tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data - 1)
```

In the code above, we create the PyMC3 variables corresponding to $\lambda_1$ and $\lambda_2$. We assign them to PyMC3's *stochastic variables*, so-called because they are treated by the back end as random number generators.

```python
with model:
    idx = np.arange(n_count_data) # Index
    lambda_ = pm.math.switch(tau > idx, lambda_1, lambda_2)
```

This code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\lambda$ from above. The `switch()` function assigns `lambda_1` or `lambda_2` as the value of `lambda_`, depending on what side of `tau` we are on. The values of `lambda_` up until `tau` are `lambda_1` and the values afterwards are `lambda_2`.

Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.

```python
with model:
    observation = pm.Poisson("obs", lambda_, observed=count_data)
```

The variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `observed` keyword.

The code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo* (MCMC), which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\lambda_1, \lambda_2$ and $\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.

```python
### Mysterious code to be explained in Chapter 3.
with model:
    step = pm.Metropolis()
    trace = pm.sample(10000, tune=5000,step=step)
```

    Multiprocess sampling (4 chains in 4 jobs)
    CompoundStep
    >Metropolis: [tau]
    >Metropolis: [lambda_2]
    >Metropolis: [lambda_1]

<div>
    <style>
        /* Turns off some styling */
        progress {
            /* gets rid of default border in Firefox and Opera. */
            border: none;
            /* Needs to be in here for Safari polyfill so background images work as expected. */
            background-size: auto;
        }
        .progress-bar-interrupted, .progress-bar-interrupted::-webkit-progress-bar {
            background: #F44336;
        }
    </style>
  <progress value='0' class='' max='60000' style='width:300px; height:20px; vertical-align: middle;'></progress>

</div>

    Sampling 4 chains for 5_000 tune and 10_000 draw iterations (20_000 + 40_000 draws total) took 38 seconds.
    The number of effective samples is smaller than 25% for some parameters.

```python
lambda_1_samples = trace['lambda_1']
lambda_2_samples = trace['lambda_2']
tau_samples = trace['tau']
```

```python
figsize(12.5, 10)
#histogram of the samples:

ax = plt.subplot(311)
ax.set_autoscaley_on(False)

plt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_1$", color="#A60628", density=True)
plt.legend(loc="upper left")
plt.title(r"""Posterior distributions of the variables
    $\lambda_1,\;\lambda_2,\;\tau$""")
plt.xlim([15, 30])
plt.xlabel("$\lambda_1$ value")

ax = plt.subplot(312)
ax.set_autoscaley_on(False)
plt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_2$", color="#7A68A6", density=True)
plt.legend(loc="upper left")
plt.xlim([15, 30])
plt.xlabel("$\lambda_2$ value")

plt.subplot(313)
w = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)
plt.hist(tau_samples, bins=n_count_data, alpha=1,
         label=r"posterior of $\tau$",
         color="#467821", weights=w, rwidth=2.)
plt.xticks(np.arange(n_count_data))

plt.legend(loc="upper left")
plt.ylim([0, .75])
plt.xlim([35, len(count_data)-20])
plt.xlabel(r"$\tau$ (in days)")
plt.ylabel("probability");
```

### Interpretation

Recall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\lambda$s and $\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\lambda_1$ is around 18 and $\lambda_2$ is around 23. The posterior distributions of the two $\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.

What other observations can you make? If you look at the original data again, do these results seem reasonable?

Notice also that the posterior distributions for the $\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.

Our analysis also returned a distribution for $\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points.

### Why would I want samples from the posterior, anyways?

We will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.

We'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \; 0 \le t \le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\lambda$. Therefore, the question is equivalent to *what is the expected value of $\lambda$ at time $t$*?

In the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\lambda_i$ for that day $t$, using $\lambda_i = \lambda_{1,i}$ if $t \lt \tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\lambda_i = \lambda_{2,i}$.

```python
figsize(12.5, 5)
# tau_samples, lambda_1_samples, lambda_2_samples contain
# N samples from the corresponding posterior distribution
N = tau_samples.shape[0]
expected_texts_per_day = np.zeros(n_count_data)
for day in range(0, n_count_data):
    # ix is a bool index of all tau samples corresponding to
    # the switchpoint occurring prior to value of 'day'
    ix = day < tau_samples
    # Each posterior sample corresponds to a value for tau.
    # for each day, that value of tau indicates whether we're "before"
    # (in the lambda1 "regime") or
    #  "after" (in the lambda2 "regime") the switchpoint.
    # by taking the posterior sample of lambda1/2 accordingly, we can average
    # over all samples to get an expected value for lambda on that day.
    # As explained, the "message count" random variable is Poisson distributed,
    # and therefore lambda (the poisson parameter) is the expected value of
    # "message count".
    expected_texts_per_day[day] = (lambda_1_samples[ix].sum()
                                   + lambda_2_samples[~ix].sum()) / N

plt.plot(range(n_count_data), expected_texts_per_day, lw=4, color="#E24A33",
         label="expected number of text-messages received")
plt.xlim(0, n_count_data)
plt.xlabel("Day")
plt.ylabel("Expected # text-messages")
plt.title("Expected number of text-messages received")
plt.ylim(0, 60)
plt.bar(np.arange(len(count_data)), count_data, color="#348ABD", alpha=0.65,
        label="observed texts per day")

plt.legend(loc="upper left");
```

Our analysis shows strong support for believing the user's behavior did change ($\lambda_1$ would have been close in value to $\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)

##### Exercises

1\.  Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\lambda_1$ and $\lambda_2$?

```python
#type your code here.
print(lambda_1_samples.mean())
print(lambda_2_samples.mean())
```

    17.743607156764146
    22.7093739712513

2\.  What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.

```python
#type your code here.
(lambda_1_samples/lambda_2_samples).mean()
```

    0.7825252356102967

3\. What is the mean of $\lambda_1$ **given** that we know $\tau$ is less than 45.  That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\lambda_1$ now? (You do not need to redo the PyMC3 part. Just consider all instances where `tau_samples < 45`.)

```python
#type your code here.
lambda_1_samples[tau_samples<45].mean()
```

    17.74444306523926

### References

-  [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg).
-  [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.pdf).
- [3] Salvatier, J, Wiecki TV, and Fonnesbeck C. (2016) Probabilistic programming in Python using PyMC3. *PeerJ Computer Science* 2:e55 <https://doi.org/10.7717/peerj-cs.55>
- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.
- [5] Cronin, Beau. "Why Probabilistic Programming Matters." 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. <https://plus.google.com/u/0/107971134877020469960/posts/KpeRdJKR6Z1>.

```python
from IPython.core.display import HTML
def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()
```

<style>
    @font-face {
        font-family: "Computer Modern";
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunss.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-weight: bold;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsx.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-style: oblique;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsi.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-weight: bold;
        font-style: oblique;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunso.otf');
    }
    div.cell{
        width:800px;
        margin-left:16% !important;
        margin-right:auto;
    }
    h1 {
        font-family: Helvetica, serif;
    }
    h4{
        margin-top:12px;
        margin-bottom: 3px;
       }
    div.text_cell_render{
        font-family: Computer Modern, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
        line-height: 145%;
        font-size: 130%;
        width:800px;
        margin-left:auto;
        margin-right:auto;
    }
    .CodeMirror{
            font-family: "Source Code Pro", source-code-pro,Consolas, monospace;
    }
    .prompt{
        display: None;
    }
    .text_cell_render h5 {
        font-weight: 300;
        font-size: 22pt;
        color: #4057A1;
        font-style: italic;
        margin-bottom: .5em;
        margin-top: 0.5em;
        display: block;
    }

    .warning{
        color: rgb( 240, 20, 20 )
        }
</style>

```python

```


# U of U IS Deep Learning Study Group - Notes #1
#### Author: Brian Sheng
#### Art Credit: Stephen Vickers

```python
from IPython.display import YouTubeVideo
import tensorflow as tf
import sympy as sp
from sympy import Matrix
sp.init_printing("latex")
```

Deep Learning has been getting a lot of attention lately. The question is why... and does it live up to the hype? Well, you may know that our ability to train and run bigger neural networks due to our increase in compute power since days past is a big part of it.

**Note**: This notebook explains things from the ground up, and you may be familiar with some of these concepts already. The intention of the simplistic explanations is not to insult or condescend, but to couch things in as simple terms as possible, but no simpler. As a result, plain English is often used to introduce heady concepts in layman's terms. Feel free to skim through concepts you're already solidly familiar with, but please be open to alternative perspectives that may be enlightening.

If you want the abridged version of everything, I'd suggest reading the headings, reading around the *bolded statements*, looking at the visuals, reading the formulas, and reading things that are indented in HTML quotes style like this:
> This is HTML quote style

At the same time it's important to know that I do not hold a Ph.D in Computer Science, nor am I currently an industy leader in AI, so what is written here is not dogma. I am simply a determined amateur who is doing his best to fill his knowledge gaps and do some good science. Many of the makers of these resources *are* experts in their field however, and I would advise that you go through them:

## Additional Learning Resources
**The de facto Deep Learning textbook from Goodfellow et al (free!)**:
http://deeplearningbook.org/

**An easier online Deep Learning textbook (free!)**:
http://neuralnetworksanddeeplearning.com/

**Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems (~$32)**:
https://www.amazon.com/gp/product/1491962291

**Hands-On Machine Learning Github (free code and Jupyter Notebooks!)**:
https://github.com/ageron/handson-ml

**How Deep Neural Networks Work**:
https://www.youtube.com/watch?v=ILsA4nyG7I0

**How Convolutional Neural Networks work**:
https://www.youtube.com/watch?v=FmpDIaiMIeA

**CS231N Winter 2016 Lectures from Andrej Karpathy at Stanford**: https://www.youtube.com/playlist?list=PLkt2uSq6rBVctENoVBg1TpCC7OQi31AlC

**CS231N Winter 2016 Lecture Notes**:
http://cs231n.github.io/

**ConvNetJS (neural nets in your browser with JavaScript!)**:
http://cs.stanford.edu/people/karpathy/convnetjs/

**Hvass Labs TensorFlow Jupyter Notebook Tutorials with YouTube Videos**:
https://github.com/Hvass-Labs/TensorFlow-Tutorials

**Stanford's Deep Natural Language Processing Video Lectures**:
https://www.youtube.com/playlist?list=PL3FW7Lu3i5Jsnh1rnUwq_TcylNr7EkRe6

**Berkeley's Deep Reinforcement Learning Course (even more learning resources recommended there!)**:
http://rll.berkeley.edu/deeprlcourse/

**YouTube playlist for developing visual intution for linear algebra**:
https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab

**YouTube playlist for developing visual intution for calculus**:
https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr

**Backpropagation Example Python Code:**
https://iamtrask.github.io/2017/03/21/synthetic-gradients/
https://iamtrask.github.io/2015/07/12/basic-python-network/

With that out of the way, let's proceed.

## Introduction and Learning Goals

### Introduction
#### Why can we go deeper? Why are neural nets suddenly working better?

In a nutshell:
- Backpropagation has been around for a while
- Neural nets are nothing new

#### Why are neural nets hot right now?
- More compute power
- More data
- Use of different neural net types
	- Convolutional Neural Net architectures exist that have ~10^2 layers (not all “layers” have neurons)
	- Vanilla Fully-Connected Nets usually don’t see much benefit from >3 layers depending on the application
	- Recurrent Net depth is <10^1 layers, usually more like 4 or 5. (due to nature of computation and exacerbated vanishing/exploding gradient problems)
- Use of different units
	- ReLU for ConvNets, some RNNs, Fully Connected Nets
	- LSTMs and GRUs for RNNs
	- These units train better and/or address vanishing/exploding gradients
- Better initialization
	- RBMs initially pre-trained and then stacked to create Deep Belief Networks
	- Turns out better initialization is all you really need (don’t need RBMs)
	*Citation: Andrej Karpathy’s CS231N lectures 4, 5, 6.
	- Small random values, normally or uniformly distributed depending on the network type, with std dev depending on number of inputs and outputs for a given neuron.
*RBM  = Restricted Boltzmann Machine
- Better regularization (L2, Dropout, DropConnect, Early Stopping, Ensemble, Bagging)

An *in-a-nutshell* statement on the current state of AI from DARPA can be found here:

```python
YouTubeVideo('-O01G3tSYpU')
```

An *in-a-nutshell* explanation of deep neural nets can be found here:

```python
YouTubeVideo('ILsA4nyG7I0')
```

### Learning Goals for this Group
- Develop a better intuition of how neural nets function from the ground up.
- Develop an intuition for tuning deep neural net models in practice.
- Develop skills for use in practice, research, etc.

#### How to accomplish this?
- Presentations from week to week.
- Hopefully lecture notes and code to play with on Git service of our choosing.

## Effect of Depth & General Intuitions

### Networks Have Layers
You likely know that the *Deep* in *Deep Learning* is due to the large number of layers in some networks that have performed quite well on modern AI tasks in recent years. For the sake of review and reference, in a nutshell, each layer is either an input, an output, or the result of an element-wise activation function that has been applied to the result of a matrix multiply followed by an addition operation with a *bias vector*. These output vectors are the *layers*, and the weights in the matrices are the connections between them. Layers that aren't the output or input layer are called *hidden* layers.

Image credit: https://en.wikipedia.org/wiki/Artificial_neural_network

### Learning of Meaningful Features
The meaningful *features* that a learning system is meant to grab onto are traditionally designed by human domain experts, resulting in very complicated operations on the input data, and complex functions being fed into each *layer* of the network. The general idea with neural nets is to instead allow a learning system to define its own features as it is trained on the data. Each layer can be seen as a **layer of abstraction**, with the network creating more complicated features from simpler features. This can be seen as building up more complicated concepts from simpler ones. This can be seen in convolutional neural nets, with the learned *filters* getting more complicated as we go from input layer to output layer.

Image credit: (Goodfellow et al, 2016)

### Repeated Kernel Trick (Warp & Slice)
In the example of a 2d data space, and classifying inputs as one of two things, you can think of a neural network as repeatedly stretching, warping, and squashing the space of data to allow for the drawing of a flat plane to separate the data. It's like taking a sheet of rubber and warping it into some weird shape before freezing it and slicing through it with a knife. Each layer results in another warping of the sheet, and the final layer corresponds to the last warping, followed by a slice with a knife. The number of *neurons* type of *activation function* for a given layer will determine the warping type. You can see that warpings generally **get more complex with number of neurons**, and that **adding layers nests these warpings together**, feeding them into one another like Russian nesting dolls.

Image credit: (Karpathy et al, 2016)

This can be seen in this interactive demo from Andrej Karpathy of such a neural net that runs in your browser: http://cs.stanford.edu/people/karpathy/convnetjs/demo/classify2d.html

Explanation of demo:

```python
YouTubeVideo('i94OvYb6noo?t=1h10m45s')
```

### Neural Nets as Universal Function Approximators
Neural Nets can be shown to approximate just about any arbitrary function given non-linear activation functions and enough units. Essentially, if you give neural nets enough capacity to learn and represent complex outputs, then you'll tend towards being able to output whatever arbitrary thing as long as it's a function on the input. See these chapters for much more detailed and rigorous explanations:
http://neuralnetworksanddeeplearning.com/chap4.html
http://www.deeplearningbook.org/contents/mlp.html

### Problems with Depth
The problem is that when you increase depth on a network you also make it considerably harder to train. This is due to the way that the network learns for the network being tied to depth in a way that parts of the network further removed from the output will be less affected by the learning mechanism, which operates on a function of the output error of the network. Modern methods find ways around this with the aforementioned tweaks in our Introduction section to give *Deep Learning*, where we can effectively train very deep neural nets given some caveats (mainly convolutional neural nets it seems).

**I strongly recommend now playing with the aforementioned ConvNetJS two-class neural net classifier with visualization. It will give you intuition about the concepts and ideas discussed in this section**

## Neural Nets as Composed Functions & Computational Graphs
Neural nets can be viewed as nested, or "composed", functions. They are functions of functions of functions of inputs. Looking at the top level of abstraction, they can be unhelpfully viewed as literal boxes of *magic*. This view of (unwitting) data being pulled in to a box of magic to produce (suave) output is a bit to simplistic and doesn't really help us, so let's break it down a bit deeper.

### Computational Graphs
Taking the example of a neural net with one hidden layer, if we break down the magic box into the machines that it's made out of, we have a representation that looks like this:

If it looks like bedlam and chaos, that's because those little workers are computing something important in an inefficient way. We'll come back to that later.

You can see that there's a matrix multiply with bias and activation function to go from input to hidden layer, then another set of matrix multiply with bias and activation function machines to go from hidden layer to output. (On a related note, this YouTube playlist gives an excellent series of intuitive explanations of linear algebra concepts, enjoyable even for the seasoned pro: https://www.youtube.com/playlist?list=PLZHQObOWTQDPD3MizzM2xVFitgF8hE_ab)

If you examine the first machine in the line, you'll see that matrix multiply and bias machines look like this:

Let's clean things up a bit and go back to a more helpful version of *magic* boxes. In the process, we'll also break the operations down into their useful components, or smaller magic boxes. Here's the same matrix multiply and bias operation in terms of magic boxes:

You can see that it's pretty much exactly what it says on the tin. It's the multiplication of some input **x** with some matrix **W1** using *****, followed by the addition of a bias **b1** using **+** to the result. If we keep the activation function interchangeable and leave it as a magic box labelled **f**, we can then represent our neural network as a series of magic boxes chained together like this. When you expand it all out, it looks something like this:

This series of chained boxes that takes an input and spits out some outputs is a **computational graph**. In the case of neural nets, it has the property where you can always find a beginning input that depends only on itself, and also the property where you can't get caught in an infinite loop. This is called **acyclic dependency**, and will be a helpful property later.

### Optimal Substructure & Gradients of Composed Functions with the Chain Rule
You may notice that each box in this graph may depend on other boxes feeding into their input. They are therefore *functions* of these other input boxes. These input boxes are also functions, so we have functions of functions. The end result of the graph is a nested or composed function. If you were to find the change of the output of this graph with respect to the change in some part further back in the graph, this would be the **derivative** of the output with respect to that part. Since these are vector or matrix shape parts, we get vector or matrix-shaped derivatives. These vector or matrix-shaped derivatives would be called our **gradients**.

It is important to note another property of this computational graph. The gradients of the output with respect to each box happen to depend on each other. You can make gradients from other gradients. Solutions from smaller solution pieces. This is called **optimal substructure**, and it is also a helpful property for us. The fact that the whole computational graph is a bunch of functions composed together means that we compute these gradients using the **chain rule**. Borrowing from Wikipedia's chain rule explanation, in short, the derivative of an outer function

$$F(x)=f(g(x))$$

with respect to an inner function's input (the single quote indicates a derivative of F(x)) **F'(x)** is computed by:

$$F'(x) = f'(g(x))g'(x)$$

This means that the derivative of the outside function with respect to the inside function's input is equal to the derivative of the outside function with respect to the inside function multiplied by the derivative of inside function with respect to the inside function's input.

Alternatively, if you set $z=F(x)=f(g(x))=f(y)$ and $y=g(x)$, then you can rewrite this as:

$$\frac{dz}{dx}=\frac{dz}{dy}\frac{dy}{dx}=F'(x) = f'(g(x))g'(x)$$

Where $\frac{dz}{dx}$ is the derivative of z with respect to x, $\frac{dz}{dy}$ is the derivative of z with respect to y, and $\frac{dy}{dx}$ is the derivative of y with respect to x. You can see that the $dy$ numerator and denominator appear to cancel, leaving $\frac{dz}{dx}$ as the result.

The notation of $\frac{dz}{dx}$ for the derivative reflects the fact that it's *like* the ratio between a tiny change in $z$ due to a tiny change in its input $x$ by $dx$

$$dz\approx z(x+dx)-z(x)$$

and that tiny change dx. When $dx$ is *infinitely small* (take the "limit" as is goes to zero) then the derivative is *literally* that ratio and we get:

$$\frac{dz}{dx}=\lim_{dx \to 0}\frac{z(x+dx)-z(x)}{dx}$$

If the function has multiple inputs, then you're taking a *partial derivative* when you take the derivative w.r.t that input while holding everything else constant. The notation for that looks like:

$$\frac{\partial z}{\partial u}=\frac{\partial z}{\partial x}\frac{\partial x}{\partial u},z=f(x,y),x=g(u,v)$$

You can see that we multiply gradients together with other gradients to get our final gradients of the output with respect to each box output or input(e.g. **W1** is a box input, $\boldsymbol{f}(\boldsymbol{W_1 x}+\boldsymbol{b_1})$ is the output of the first **f** box) . Chain rule is described here: https://en.wikipedia.org/wiki/Chain_rule.

If this is your first exposure to calculus and you've never heard of the chain rule before, then this YouTube playlist may also prove useful (The Essence of Calculus): https://www.youtube.com/playlist?list=PLZHQObOWTQDMsr9K-rj53DwVRMYO3t5Yr

The video from that playlist related to the Chain Rule is here:

```python
YouTubeVideo('YG15m2VwSjA')
```

How the gradients pass through split inputs on addition and multiplication is covered here (related to the Backpropagation section):
http://cs231n.github.io/optimization-2/

Now, why do we want the gradient? Well, since that output *J* indicates how bad our neural net is doing on the training data, we want to make that as small as possible. Some parts that go into *J* can't be helped. Some of these bits can be helped, and would be called the **parameters** of our model that are free to change. These would be **W1** **b1** **W2** **b2**, and free to vary during the training process. We use the gradient of that *J* with respect to these parameters to change these parameters during training. This will move them in a direction to minimize that loss, *J* on the training data. This process is Gradient Descent, and is covered in the next section.

## Gradient Descent & Backpropagation

### Gradient Descent
So, you have a neural net that has an associated loss function. To get it to learn, we minimize this loss function with respect to the training data, fitting it to the data. The general way to do this is with any number of modified versions of *Gradient Descent*.

Looking in the  motivation section of Wikipedia page for gradient:
https://en.wikipedia.org/wiki/Gradient
> *Consider a surface whose height above sea level at point (x, y) is H(x, y). The gradient of H at a point is a vector pointing in the direction of the **steepest slope or grade at that point.** The steepness of the slope at that point is given by the magnitude of the gradient vector.*

Image credit: https://en.wikipedia.org/wiki/Gradient_descent

Subtracting the gradient from its associated vector or  function is like heading away from the direction of *steepest ascent*. You are heading in the direction of *steepest descent*, hence **Gradient Descent**. Intuitively, if you're heading towards a direction of steepest descent, eventually you will reach a flat spot or region locally. You will arrive at a *local minimum* of the matrix function. See the Wikipedia page for more info:

https://en.wikipedia.org/wiki/Gradient_descent

The general formula of interest is:
$$u_{t+1}=u_{t}-\alpha \nabla f(u_t)$$

Where $u$ is a parameter of the function $f(u)$, $u_{t+1}$ is the new value of $u$, $u_t$ is the old value of $u$, $\alpha$ is a scalar real number value, and $\nabla f(u_t)$ is the gradient of $f(u_t)$. The important thing to keep in mind here is that $u$ can be any arbitrary shaped matrix, vector, or tensor, but the shapes of $u_{t+1}$, $u_{t}$, and $\nabla f(u_t)$ must be the same for gradient descent to work. That seems a bit obvious, but this will be important later.

### Computing Gradients

The naive way to compute the gradients we need for our parameters is to repeatedly apply the chain rule over and over again. This however, results in use repeating ourselves much more than necessary. Let's look at the example where we need to compute the gradient of *J* w.r.t. (with respect to) **W1** **b1** **W2** **b2** as in our computational graph for a one hidden layer neural net with activation functions on the hidden and output layers.

As for taking the derivative (differentiation) w.r.t a vector, the following video should outline the idea behind it:

```python
YouTubeVideo('iWxY7VdcSH8')
```

Differentiation of a vector $\boldsymbol{f}$ w.r.t to another vector $\boldsymbol{x}$ gives the Jacobian matrix of $\boldsymbol{f}$ w.r.t $\boldsymbol{x}$, $\frac{\partial \boldsymbol{f}}{\partial \boldsymbol{x}}$, which is of the form:

$$
\begin{bmatrix}
\frac{\partial f_1}{\partial x_1} & \dots & \frac{\partial f_1}{\partial x_m} \\
\vdots & \ddots & \vdots \\
\frac{\partial f_n}{\partial x_1} & \dots & \frac{\partial f_n}{\partial x_m}
\end{bmatrix}
$$

This gives us this horrid mess of formulas from the Chain Rule, which we'll stick here for the sake of reference:

$\boldsymbol{x}=$ Inputs

$\boldsymbol{z_1}=\boldsymbol{W_1 x}+\boldsymbol{b_1}=$ Input values to "hidden" activation function

$\boldsymbol{a}=\boldsymbol{f}(\boldsymbol{z_1})=$ Hidden Activations

$\boldsymbol{z_2}=\boldsymbol{W_2 a}+\boldsymbol{b_2}=$ Inputs to "output" activation function

$\boldsymbol{y ̂}=\boldsymbol{f}(\boldsymbol{z_2})=$Output Activations

$$
\frac{\partial J}{\partial \boldsymbol{b_2}}
=
\frac{\partial J}{ \partial \boldsymbol{y ̂ }}
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{b_2} }
$$

$$
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\odot
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
=
\boldsymbol{\delta_2}
$$

Where $\odot$ is **element-wise multiplication**, a.k.a the Hadamard Product: https://en.wikipedia.org/wiki/Hadamard_product_(matrices), and $\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }$ is the derivative of the output activation function w.r.t its inputs.

$$
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{b_2}}=\frac{\partial}{\partial \boldsymbol{b_2}}\left( \boldsymbol{w_2 a}+\boldsymbol{b_2}\right)=\boldsymbol{1}
$$

Where
$\boldsymbol{1}$ is the ones vector. (i.e. $\boldsymbol{1}=\begin{bmatrix}
         1 \\
         ... \\
         1
        \end{bmatrix}$
        for some arbitrary length)
        In the case of
        $\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{b_2}}$
        , the length of the vector is the same as the length of
        $\boldsymbol{b_2}$.

$$
\frac{\partial J}{\partial \boldsymbol{b_2}}
=
\boldsymbol{\delta_2}
\odot
\boldsymbol{1}=\boldsymbol{\delta_2}
$$

$$
\frac{\partial J}{\partial \boldsymbol{ w_2 }}
=
\frac{\partial J}{ \partial \boldsymbol{y ̂ }}
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2} }
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2}}
$$

$$
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2}}
=
\frac{\partial}{\partial \boldsymbol{w_2}}
\left( \boldsymbol{w_2 a}+\boldsymbol{b_2}\right)
=
\boldsymbol{a}^T$$

$$\frac{\partial J}{\partial \boldsymbol{ w_2 }}
=
\boldsymbol{\delta_2}
\otimes
\boldsymbol{a}
=
\boldsymbol{\delta_2}\boldsymbol{a}^T
$$

Where $\otimes$ is the **outer (or tensor) product**: https://en.wikipedia.org/wiki/Outer_product

$$\frac{\partial J}{\partial \boldsymbol{b_1}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1} }
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
$$

Where $\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }$ is the derivative of the hidden activation function w.r.t. its inputs.

$$
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a}}
=
\frac{\partial}{\partial \boldsymbol{a}}
\left( \boldsymbol{w_2 a}+\boldsymbol{b_2}\right)
=
\boldsymbol{w_2}^T
$$

$$
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
=
\frac{\partial}{\partial \boldsymbol{b_1}}
\left( \boldsymbol{w_1 x}+\boldsymbol{b_1}\right)
=
\boldsymbol{1}
$$

$$\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
=
\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle
=
\boldsymbol{w_2} \cdot \boldsymbol{\delta_2}
=
\boldsymbol{w_2}^T\boldsymbol{\delta_2}
$$

Where $\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle$ is the **inner product** (in this case, called the **dot product**) of the matrices $\boldsymbol{w_2}$ and $\boldsymbol{\delta_2}$ :
https://en.wikipedia.org/wiki/Inner_product_space
https://en.wikipedia.org/wiki/Dot_product

$$
\frac{\partial J}{\partial \boldsymbol{b_1}}
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
=
\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle
\odot \frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\odot \boldsymbol{1}
=
\boldsymbol{\delta_1} \odot \boldsymbol{1}
=
\boldsymbol{\delta_1}
$$

$$
\frac{\partial J}{\partial \boldsymbol{ w_1 }}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{w_1}}
=
\boldsymbol{\delta_1}
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{ w_1 }}
$$

$$
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{ w_1 }}
=
\frac{\partial}{\partial \boldsymbol{ w_1 }}
\left( \boldsymbol{w_1 x}+\boldsymbol{b_1}\right)
=
\boldsymbol{x}^T
$$

$$
\frac{\partial J}{\partial \boldsymbol{w_1}}
=
\boldsymbol{\delta_1}
\otimes
\boldsymbol{x}
=
\boldsymbol{\delta_1}
\boldsymbol{x}^T
$$

So, that was most likely a bit overwhelming. We'll go through that in a more intuitive manner in a bit, but now you have the formulas for reference later.

You can see there's a lot of repeated work in these formulas. Terms like
$\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }$
contain other terms, such as
$\frac{\partial J}{ \partial \boldsymbol{y ̂ }}
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }  $.

If you were to simply calculate everything straight-ahead without reusing work, you'd be repeating a lot of derivative calculcations unnecessarily. If we go back to the factory analogy with the workers computing the gradients, you can see it goes right back to bedlam and chaos very quickly if we use the straight-ahead method.

This is where backpropagation comes in.

### The Essence of Backpropagation
Backpropagation takes advantage of two properties of the computational graphs of neural nets to do these calculations without having to recalculate anything. The properties of **acyclic dependency** and **optimal substructure** allow for fancy thing called **Dynamic Programming** to be applied to the problem of calculating gradients. In this case, Dynamic Programming just means that we make sure to start with a calculation that is self contained and doesn't depend on stuff we don't have (the beginnning/end of the graph), then move on to using that result to calculate things that depend on it, then continue onto things that depend on that next result and so on.

We start from the *beginning* to calculate that *initial thing* and work our way through building *things* that depend on that *initial thing*, then building *new things* that depend on those *things* and so on, all the while making sure to compute everything without repeating work unnecessarily.
With this in mind, we can see that:
* The *things* we're building up are the gradients of the loss function output $J$ w.r.t each part.
* Our beginning is at the loss function output $J$.
* We can determine an order to do the calculations in by performing a **topological sort** on the compuational graph, or just keep track of what we've computed and check if we've computed something already before doing it, which is called **memoization**.
* Once we've computed everything that we need to, we're done.

You can see the **acyclic dependency** and **optimal substructure** of the problem in our diagram of the interdependencies of the gradient from earlier:

### Backpropagation from the Top-Down: Keeping Track of Shape
Let's walk through the example with one hidden layer we had before, and go through the formulas in more depth. One thing that tends to trip people up is keeping track of the shapes of all the vectors and matrices.

The shape of the matrices/tensors during feedforward and backprop is important to keep in mind. Things get confusing when you mix it up. It's easy to get lost in the abstract world of formulas, resulting in getting all the parts that you need for computation without knowing how to put them together to make actual gradients. So, let's go through the process *backwards* and figure out how things are suppose to fit together, and what shape everything is before slowly revealing more detail about the parts we're assembling.

Remember that formula for gradient descent?
$$u_{t+1}=u_{t}-\alpha \nabla f(u_t)$$

Well, we need to make sure that $u_{t}$ and $\nabla f(u_t)$ are the same shape. If we look at some operations available for us to play with, we can see some preserve shape while others do not. Let's set up some weight matrices and bias vectors to look at while we go through this example. We'll use the SymPy Python library for its array data structures and operations, and print things out as we go along. We'll use a neural network that looks like the following figure:

This network has 3 input units, 4 hidden units, and 2 output units. If we use column vectors in our matrix multiplications, we'll have two weight matrices and two bias vectors for our input-to-hidden and hidden-to-output mappings. The input-to-hidden weight matrix and bias vector will be $\boldsymbol{w_1}$ and $\boldsymbol{b_1}$, and the hidden-to-output weight matrix and bias vector will be $\boldsymbol{w_2}$ and $\boldsymbol{b_2}$, as before.

#### Non-Square Matrices as Transformations Between Dimensions (Shape Changing)
A matrix can be viewed as encoding a linear function, and non-square matrices can be views as encoding linear functions between dimensions. If you're operating on column vectors, then the number of rows encodes the output dimensionality, and the number of columns is input dimensionality. So a matrix like the following one encodes a transformation from 4 dimensional vectors to 2 dimensional vectors.

$$\begin{bmatrix}
         1 & 1 & 1 & 1\\
         1 & 1 & 1 & 1
        \end{bmatrix}$$

A matrix multiply between a 4D vector and such a matrix will produce a 2D vector.

$$\begin{bmatrix}
         1 & 1 & 1 & 1\\
         2 & 2 & 2 & 2
        \end{bmatrix}\begin{bmatrix}
         2 \\
         2 \\
         2 \\
         2
        \end{bmatrix}=\begin{bmatrix}
         8 \\
         16
        \end{bmatrix}$$

You can see that a non-square matrix multiplication of this kind can be seen as a magic box that takes in an input of one shape, and makes an input of another shape.

The video below gives a more in-depth understanding of how this is the case:

```python
YouTubeVideo('v8VSDg_WQlA')
```

So, looking at that neural net figure again, we'll have a 3D input vector, which must map to a 4D hidden vector, which must in turn map to a 2D output vector. This means we'll need a (4,3) (or $4x3$ depending on your notation) shaped matrix for the input-to-hidden map and a (2,4) shaped matrix for the hidden-to-output map. Our $b_1$ and $b_2$ bias vectors get added in at the hidden an output layers, so they must be 4D and 2D themselves.

Let's make the variables for these in SymPy and go through a bunch of symbolic computations with matrices so we can get an idea of how things interact.

```python
def names_2_sympy_str_list(shape, array_name):
    """Takes a shape tuple or list, and a string for the array name
    and makes a string formatted for making a sympy string of the same
    shape that is filled with symbols of the form:

    {array_name}_{indices of element in matrix}

    Returns:
        A list of strings of the form:
        [{array_name}({rows+1}\,(1:{array.shape[1]})),
        {array_name}({rows+1}\,(1:{array.shape[1]})), ... ]

        To be fed to the sympy.symbols(...) function to create symbols
        to be fed into a symbolic matrix.
  """
    return ['{{{0}}}_{{({1}\,(1:{2}))}}'
            .format(array_name, rows+1, shape[1]+1)
            for rows in range(shape[0])]

def string_list_to_sympy_matrix(sympy_string_list):
    """Takes a list of lists of strings for feeding into sympy.symbols(...)
        and feeds the list to sympy.symbols(...) and sympy.Matrix(...) via
        string_list_to_matrix(...) to create a list of sympy matrices or a
        single sympy matrix depending on the arguments.
    """
    return Matrix(sp.symbols(sympy_string_list))

def sympy_matrices_from_names(shapes, names):
    """Takes a list of matrix shape tuples, and a list of names
    for the arrays (strings) and creates symbolic matrices
    of the form:
    |name_11 name_12|
    |name_21 name_22|
    |name_31 name_32|

    Returns:
        A list of matrices to be unpacked, or a single matrix
        if only one array is given.
  """
    assert(isinstance(shapes,(tuple,list))
           and isinstance(names,(str,tuple,list)))

    if isinstance(names,str):
        string_list_input = names_2_sympy_str_list(arrays, names)
        return string_list_to_sympy_matrix(string_list_input)
    else:
        assert(len(shapes)==len(names))
        string_lists = [names_2_sympy_str_list(arr, nam)
                        for arr, nam in zip(shapes, names)]
        matrices = [string_list_to_sympy_matrix(string_list)
                    for string_list in string_lists]
        return matrices if len(matrices)>1 else matrices[0]

parameter_and_variable_shapes = ((2,1), (2,1), (2,4), (4,1), (4,1), (4,3), (3,1), (4,1),)
parameter_and_variable_names = ('b_2', '\delta_2', 'w_2','b_1', '\delta_1', 'w_1','x','a')

(b_2, delta_2, w_2, b_1, delta_1, w_1,
 input_x, hidden_activations) = sympy_matrices_from_names(parameter_and_variable_shapes,
                                                          parameter_and_variable_names)
display(b_2, w_2, b_1, w_1, input_x, hidden_activations)
```

We'll have activation functions applied to the results of the matrix multiply and biasing on the hidden and output layers, but let's focus on the shape first.

In order to increment the $\boldsymbol{b_2}$ vector, we'll need one of the same size to subtract from it. Same goes for $\boldsymbol{w_2}$, $\boldsymbol{b_1}$, and $\boldsymbol{w_1}$. We want something that looks like this:

$$\boldsymbol{b_2}-\Delta \boldsymbol{b_2}
=
\begin{bmatrix}
         b_{2(1,1)} \\
         b_{2(2,1)}
        \end{bmatrix}
        -
        \begin{bmatrix}
         \Delta b_{2(1,1)} \\
         \Delta b_{2(2,1)}
        \end{bmatrix}
        $$

If we refer to some of the formulas from applying chain rule earlier, we see this needs to depend on the derivative of the loss $J$ w.r.t $\boldsymbol{y ̂}$, $\frac{\partial J}{ \partial \boldsymbol{y ̂ }}$, which will be a vector in the shape of $\boldsymbol{y ̂}$ due to the way that derivatives w.r.t a vector work. Activation functions are element-wise, and thus shape-preserving, so their derivatives also preserve shape. The output activation function derivative w.r.t its input, $\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }$, will therefore be the same shape as $\boldsymbol{b_2}$ too.

$$
\frac{\partial J}{\partial \boldsymbol{b_2}}
=
\frac{\partial J}{ \partial \boldsymbol{y ̂ }}
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{b_2} }
$$

The activation function and its derivative are like magic boxes that operate element-wise on inputs, leaving shapes unchanged.

As for that last piece, from differentiation rules, we can clearly see:

$$
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{b_2}}=\frac{\partial}{\partial \boldsymbol{b_2}}\left( \boldsymbol{w_2 a}+\boldsymbol{b_2}\right)=\boldsymbol{1}
$$

Where $\boldsymbol{1}$ is the same shape of $\boldsymbol{b_2}$. So, we see that we essentially use just the first two pieces.

So, it's quite easy to put a vector together shaped like $\boldsymbol{b_2}$ from these pieces. Everything is already the same shape as $\boldsymbol{b_2}$, so we just multiply $\frac{\partial J}{ \partial \boldsymbol{y ̂ }}$ and $
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }$ together element-wise. The magic box analogy for that would be something like this:

If we multiply everything together, we get this thing, which we can multiply by some $\alpha$ and subtract from $\boldsymbol{b_2}$. It pops up again and ends up backpropagating through the gradients, so we'll call it $\boldsymbol{\delta_2}$.

$$
\frac{\partial J}{\partial \boldsymbol{b_2}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\odot
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
=
\boldsymbol{\delta_2}
$$

$$
\boldsymbol{b_2}
-
\Delta \boldsymbol{b_2}
=
\boldsymbol{b_2}
-
\alpha \boldsymbol{\delta_2}
$$

Where $\odot$ is element-wise multiplication, aka the Hadamard Product: https://en.wikipedia.org/wiki/Hadamard_product_(matrices).

So, everything's been a convenient shape so far, and we've only use shape-preserving operations to assemble the pieces we need and combine them together. What about for the next parameter set in line, $\boldsymbol{w_2}$? If we take a look at the Chain Rule equations again, we see that we need to use this $\boldsymbol{\delta_2}$ to make the gradient $\frac{\partial J}{\partial \boldsymbol{ w_2 }}$ to increment $\boldsymbol{w_2}$.

$$
\frac{\partial J}{\partial \boldsymbol{ w_2 }}
=
\frac{\partial J}{ \partial \boldsymbol{y ̂ }}
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2} }
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2}}
$$

Now, $\boldsymbol{b_2}$ looks like this:

```python
display(b_2)
```

Keeping in mind that $\boldsymbol{\delta_2}$ is the same shape as $\boldsymbol{b_2}$,

$\boldsymbol{w_2}$ looks like this:

```python
display(w_2)
```

How is this supposed to work out? They're not the same shape! We can't hope to get there with shape-preserving operations!

Well, we don't have to preserve shape, we just need to put things together from other things that they depend on. You can have more than one thing in $\boldsymbol{w_2}$ depend on a single item in $\boldsymbol{b_2}$. Specifically, differentiation rules show that we'll be using the *Sum Rule* in addition to the Chain Rule and company. This means we'll need to multiply things together, sum them, and stick them in matrices.

That sounds a lot like matrix multiplication... because it *is* matrix multiplication. We'll specifically be doing a special kind of matrix multiply that's called the *outer product* or *tensor product* (https://en.wikipedia.org/wiki/Outer_product). It will take two vectors and make a matrix out of them. It's like making a transformation between dimensions using two vectors. Like making a function from two vectors. In magic box terms, that looks a bit like this:

**Note: Transpose and Outer Product functions make functions from their inputs. Since having an arrow to another magic box would be confusing, we show the functions being operated on as being enclosed in bubbles. A magic box enters another one as a bubble, and exits as a modified version of itself. A pair of pegs gets combined to make a peg mapping magic box, and exits the magic box in a bubble.
**

If we look at the Chain Rule formulas again, we see that we need to multiply our $\boldsymbol{\delta_2}$ by the derivative $\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2}}$:

$$
\frac{\partial J}{\partial \boldsymbol{ w_2 }}
=
\frac{\partial J}{ \partial \boldsymbol{y ̂ }}
\frac{\partial \boldsymbol{y ̂ }}{\partial \boldsymbol{z_2} }
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2} }
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2}}
$$

Applying differentiation rules, we see that it's equal to the **activations of the hidden layer** $\boldsymbol{a}$.

$$
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{w_2}}
=
\frac{\partial}{\partial \boldsymbol{w_2}}
\left( \boldsymbol{w_2 a}+\boldsymbol{b_2}\right)
=
\boldsymbol{a}$$

Now, $\boldsymbol{a}$ is the same shape, (4,1), as $\boldsymbol{b_1}$ which looks like this:

```python
display(b_1)
```

$\boldsymbol{b_2}$ is shaped like (2,1) and looks like this:

```python
display(b_2)
```

Can we make a (2,4) shape matrix from a (2,1) and a (4,1)? Intuitively, if you have something of the shape output by a matrix multiply, and something of the shape going into a matrix multiply, you should be able to reconstruct a matrix of the same shape used in the multiply. With the outer product, we can do exactly that and make a matrix from two vectors:

```python
display(delta_2, hidden_activations)
display(delta_2*hidden_activations.T)
```

This is the right shape, and actually gives us our gradient for incrementing $\boldsymbol{w_2}$, but let's zoom in a bit, and take a look at why.

 Looking at the forward pass, we can examine what $\boldsymbol{z_2}=\boldsymbol{w_2 a}+\boldsymbol{b_2}$:

```python
w_2*hidden_activations+b_2
```

Hmm, those expressions look very similar. If you *remove the addition symbols*, and *got rid of the biases and $w_2$ factors*, it looks like you could multiply $\boldsymbol{\delta_2}$ by each column to get the same result as the outer product between $\boldsymbol{\delta_2}$ and $\boldsymbol{a}$. You can see that as seen mentioned in the lecture notes for CS231N, the pieces of $\boldsymbol{\delta_2}$ are distributed amongst its dependants in $\boldsymbol{a}$, **splitting along sum gates**.

Now we need to backpropagate our gradients through the hidden layer to the biases and weights on the other side. If we look at a matrix transpose operation as taking a transformation between dimensions and flipping it, then we can use $\boldsymbol{w_2}$ to at least get our gradients in the shape we want. Essentially, with the matrix transpose, we have another magic box that takes in magic boxes, and spits out new magic boxes.

Our equations of interest (again from the Chain Rule formulas):

$$\frac{\partial J}{\partial \boldsymbol{b_1}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1} }
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
$$

$$
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a}}
=
\frac{\partial}{\partial \boldsymbol{a}}
\left( \boldsymbol{w_2 a}+\boldsymbol{b_2}\right)
=
\boldsymbol{w_2}^T
$$

$$
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
=
\frac{\partial}{\partial \boldsymbol{b_1}}
\left( \boldsymbol{w_1 x}+\boldsymbol{b_1}\right)
=
\boldsymbol{1}
$$

$$\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
=
\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle
=
\boldsymbol{w_2} \cdot \boldsymbol{\delta_2}
=
\boldsymbol{w_2}^T\boldsymbol{\delta_2}
$$

Where $\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle$ is the **inner product** (in this case, called the **dot product**) of the matrices $\boldsymbol{w_2}$ and $\boldsymbol{\delta_2}$ :
https://en.wikipedia.org/wiki/Inner_product_space
https://en.wikipedia.org/wiki/Dot_product

We can see that we have $\boldsymbol{w_2}^T$ as a factor, which is (4,2) shaped, and looks like this:

```python
display(w_2.T)
```

$\boldsymbol{\delta_2}$ is (2,1) shaped, and looks like this:

```python
display(delta_2)
```

If we multiply them together as $\boldsymbol{w_2}^T\boldsymbol{\delta_2}$, we get:

```python
w_2.T*delta_2
```

Which is (4,1) shaped, just what we need for incrementing the bias vector $\boldsymbol{b_1}$. Except for one element-wise factor, that is. We need the derivative of the hidden layer's activation w.r.t its input. Once we multiply that through, we'll have our $\boldsymbol{\delta_1}$ which is the gradient that we can use to move our $\boldsymbol{b_1}$ in the direction of *goodness*.

$$
\frac{\partial J}{\partial \boldsymbol{b_1}}
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
=
\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle
\odot \frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\odot \boldsymbol{1}
=
\boldsymbol{\delta_1} \odot \boldsymbol{1}
=
\boldsymbol{\delta_1}
$$

Now we need to compute our $\frac{\partial J}{\partial \boldsymbol{ w_1 }}$ gradient for incrementing our weight matrix $\boldsymbol{ w_1 }$. Another peek at our formulas shows that we have one more shape-changing outer product to go.

$$
\frac{\partial J}{\partial \boldsymbol{ w_1 }}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{w_1}}
=
\boldsymbol{\delta_1}
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{ w_1 }}
$$

$$
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{ w_1 }}
=
\frac{\partial}{\partial \boldsymbol{ w_1 }}
\left( \boldsymbol{w_1 x}+\boldsymbol{b_1}\right)
=
\boldsymbol{x}^T
$$

$$
\frac{\partial J}{\partial \boldsymbol{w_1}}
=
\boldsymbol{\delta_1}
\otimes
\boldsymbol{x}
=
\boldsymbol{\delta_1}
\boldsymbol{x}^T
$$

We'll multiply that out, and you can again see that distribution of gradients through summing operations at work here:

```python
display(delta_1, input_x)
display(delta_1*input_x.T)
```

That last matrix is our gradient $\frac{\partial J}{\partial \boldsymbol{w_1}}$, and we're now done!

Just for reference, here's the corresponding feedforward portion $\boldsymbol{z_1}$ so you can see the distribution of the gradient through sum gates again:

```python
display(w_1*input_x+b_1)
```

That concludes this example, but keep in mind that to backpropagate through more layers simply requires repeating the last few steps until you have all the gradients you need. You're after those $\boldsymbol{\delta}$ vectors, and the rest is rather simple.

Now, we’re missing a few element-wise factors when we look at the shape this way, but let’s fill those in. Chain rule says we need these things for all the derivatives for a one-hidden-layer network. We’re missing these activation function derivatives and this cost function derivative w.r.t to y_approx. We pretty much know those if we know what activation and cost functions we’re using. We'll use sigmoid with MSE for the sake of finishing this example, but keep in mind that you can use ReLU or Softmax activations, and Cross-Entropy loss too:
* https://en.wikipedia.org/wiki/Rectifier_(neural_networks)
* https://en.wikipedia.org/wiki/Softmax_function
* https://en.wikipedia.org/wiki/Cross_entropy

MSE gives the loss function:

$$
\frac{1}{m}
\sum^{m}_{i=1}
(\boldsymbol{y}-\hat{\boldsymbol{y}})^2
$$

Differentiation rules tell us to sum all $m$ derivatives, bring down the power of 2 to cancel the $\frac{1}{2}$ factor, and bring out the negative sign due to the Chain Rule. This results in a derivative that looks like:

$$\frac{\partial J}{\partial \boldsymbol{\hat{\boldsymbol{y}}}}
=
-(\boldsymbol{y}-\hat{\boldsymbol{y}})
=
(\hat{\boldsymbol{y}}-\boldsymbol{y})$$

Sigmoid units have the form:

$$\boldsymbol{\sigma}(\boldsymbol{z})=\frac{1}{1+e^{-\boldsymbol{z}}}$$

Which has the derivative (see http://mathworld.wolfram.com/SigmoidFunction.html):

$$
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z}}
=
\frac{\partial \boldsymbol{\sigma(\boldsymbol{z})}}{\partial \boldsymbol{z}}
=
\boldsymbol{\sigma}(\boldsymbol{z})(1-\boldsymbol{\sigma}(\boldsymbol{z}))
$$

Plug those into your equations and you get:

$$
\frac{\partial J}{\partial \boldsymbol{b_2}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
=
\frac{\partial J}{\partial \boldsymbol{y ̂}}
\odot
\frac{\partial \boldsymbol{y ̂}}{\partial\boldsymbol{z_2}}
=
(\hat{\boldsymbol{y}}-\boldsymbol{y})
\odot
\left[\boldsymbol{\sigma}(\boldsymbol{z})(1-\boldsymbol{\sigma}(\boldsymbol{z}))\right]
=
\boldsymbol{\delta_2}
$$

$$\frac{\partial J}{\partial \boldsymbol{ w_2 }}
=
\boldsymbol{\delta_2}
\otimes
\boldsymbol{a}
=
\boldsymbol{\delta_2}\boldsymbol{a}^T
=
(\hat{\boldsymbol{y}}-\boldsymbol{y})
\odot
\left[\boldsymbol{\sigma}(\boldsymbol{z})(1-\boldsymbol{\sigma}(\boldsymbol{z}))\right]
\otimes
\boldsymbol{a}
$$

$$
\frac{\partial J}{\partial \boldsymbol{b_1}}
=
\boldsymbol{\delta_2}
\frac{\partial \boldsymbol{z_2}}{\partial \boldsymbol{a} }
\frac{\partial \boldsymbol{a}}{\partial \boldsymbol{z_1} }
\frac{\partial \boldsymbol{z_1}}{\partial \boldsymbol{b_1}}
=
\langle \boldsymbol{w_2},\boldsymbol{\delta_2}\rangle
\odot
\left[\boldsymbol{\sigma}(\boldsymbol{z})(1-\boldsymbol{\sigma}(\boldsymbol{z}))\right]
=
\boldsymbol{\delta_1}
$$

$$
\frac{\partial J}{\partial \boldsymbol{w_1}}
=
\boldsymbol{\delta_1}
\otimes
\boldsymbol{x}
=
\boldsymbol{\delta_1}
\boldsymbol{x}^T
$$

That wraps up this example and this notebook! I would highly recommend checking out the code from Andrew Trask, which takes backpropagation and packages it up in an object-oriented fashion, tying into the computational graph structure we discussed, and connecting to the computational graph structure that's actually used by TensorFlow under the hood!

https://iamtrask.github.io/2017/03/21/synthetic-gradients/

We'll be moving onto Optimization and Regularization next!


# O Jupyter Notebook

Este documento é um *Jupyter Notebook*, esta é uma forma exploratória de editar e executar códigos em Python. Uma das grandes vantagens do *Notebook* é ser capaz de apresentar textos formatados lado a lado com códigos em Python.

## As células do *notebook*

A estrutura básica de um *notebook* é a célula. Cada célula tem um objetivo único, que pode ser conter, por exemplo um **texto**, **código**, **metadados** ou muitos outros tipos de dados que não trataremos aqui.

Por exemplo, a próxima célula apresenta um código. Que efetua a seguinte operação

\begin{equation}
5+2 = 7
\end{equation}

Para executar selecione

```python
5+2
```

    7

O código é escrito na lingagem Python e efetua uma operação aritmética básica. Poderíamos também executar um comando Python diretamente.

```python
print("Olá Mundo")
```

    Olá Mundo

Digitar alguma coisa sem sentido em uma célula de código nos da um erro Python

```python
imprime("Olá Mundo")
```

## Modo texto

Uma célula em modo texto (Markdown), não é interpretada pelo Python. Você pode considerar que ela funciona como um comentário. Você pode inserir utilizando a sintaxe do [Markdown](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html). Pode inclusive incluir a notação matemática do LaTex.

\begin{equation}
\sum_{i=0}^n \frac{ (-1)^n f(x)^{(n)}(x-a)}{n!}
\end{equation}

## Estados do notebook

O notebook pode ficar em dois estados

* Edição (caixa verde) Tecla: ENTER
* Comando (caixa azul) Tecla: ESC

No modo de edição as setas e teclas manipulam o conteúdo da célula. No modo de comando as setas movem entre células e as outras teclas representam comandos.

No dia de hoje, iremos aprender Python em conjunto com a manipulação dos **notebooks**.

### Praticando

Pratique adicionando células novas, tanto do tipo **texto**, como **código**, fazendo operações aritméticas simples e texto formatado utilizando a linguagem Markdown.

| Atalho | Função |
|--------|--------|
| ENTER  | Edita a célula |
| SHIFT-ENTER | Executa a célula |
| Setas | Move o cursor |
| a | Adiciona uma célula acima |
| b | Adiciona uma célula abaixo
| y | Muda o tipo de célula para CÓDIGO |
| m | Muda o tipo de célula para TEXTO |
| x | Corta célula |
| c | Copia célula |
| v | Cola célula abaixo |