# Programming Exercise 4:  Neural Networks Learning

## Introduction

In this exercise, you will implement the backpropagation algorithm for neural networks and apply it to the task of hand-written digit recognition. Before starting on the programming exercise, we strongly recommend watching the video lectures and completing the review questions for the associated topics.

All the information you need for solving this assignment is in this notebook, and all the code you will be implementing will take place within this notebook. The assignment can be promptly submitted to the coursera grader directly from this notebook (code and instructions are included below).

Before we begin with the exercises, we need to import all libraries required for this programming exercise. Throughout the course, we will be using [`numpy`](http://www.numpy.org/) for all arrays and matrix operations, [`matplotlib`](https://matplotlib.org/) for plotting, and [`scipy`](https://docs.scipy.org/doc/scipy/reference/) for scientific and numerical computation functions and tools. You can find instructions on how to install required libraries in the README file in the [github repository](https://github.com/dibgerge/ml-coursera-python-assignments).

```python
# used for manipulating directory paths
import os

# Scientific and vector computation for python
import numpy as np

# Plotting library
from matplotlib import pyplot

# Optimization module in scipy
from scipy import optimize

# will be used to load MATLAB mat datafile format
from scipy.io import loadmat

# library written for this exercise providing additional functions for assignment submission, and others
import utils

# define the submission/grader object for this exercise
grader = utils.Grader()

# tells matplotlib to embed plots within the notebook
%matplotlib inline
```

## Submission and Grading

After completing each part of the assignment, be sure to submit your solutions to the grader. The following is a breakdown of how each part of this exercise is scored.

| Section | Part                                             | Submission function | Points
| :-      |:-                                                | :-                  | :-:
| 1       | [Feedforward and Cost Function](#section1)                    | [`nnCostFunction`](#nnCostFunction)   | 30
| 2       | [Regularized Cost Function](#section2)                        | [`nnCostFunction`](#nnCostFunction)   | 15
| 3       | [Sigmoid Gradient](#section3)                                 | [`sigmoidGradient`](#sigmoidGradient) | 5
| 4       | [Neural Net Gradient Function (Backpropagation)](#section4)   | [`nnCostFunction`](#nnCostFunction)   | 40
| 5       | [Regularized Gradient](#section5)                             | [`nnCostFunction`](#nnCostFunction)   |10
|         | Total Points                                     |    | 100

You are allowed to submit your solutions multiple times, and we will take only the highest score into consideration.

At the end of each section in this notebook, we have a cell which contains code for submitting the solutions thus far to the grader. Execute the cell to see your score up to the current section. For all your work to be submitted properly, you must execute those cells at least once.

## Neural Networks

In the previous exercise, you implemented feedforward propagation for neural networks and used it to predict handwritten digits with the weights we provided. In this exercise, you will implement the backpropagation algorithm to learn the parameters for the neural network.

We start the exercise by first loading the dataset.

```python
#  training data stored in arrays X, y
data = loadmat(os.path.join('Data', 'ex4data1.mat'))
X, y = data['X'], data['y'].ravel()

# set the zero digit to 0, rather than its mapped 10 in this dataset
# This is an artifact due to the fact that this dataset was used in
# MATLAB where there is no index 0
y[y == 10] = 0

# Number of training examples
m = y.size
```

### 1.1 Visualizing the data

You will begin by visualizing a subset of the training set, using the function `displayData`, which is the same function we used in Exercise 3. It is provided in the `utils.py` file for this assignment as well. The dataset is also the same one you used in the previous exercise.

There are 5000 training examples in `ex4data1.mat`, where each training example is a 20 pixel by 20 pixel grayscale image of the digit. Each pixel is represented by a floating point number indicating the grayscale intensity at that location. The 20 by 20 grid of pixels is “unrolled” into a 400-dimensional vector. Each
of these training examples becomes a single row in our data matrix $X$. This gives us a 5000 by 400 matrix $X$ where every row is a training example for a handwritten digit image.

$$ X = \begin{bmatrix} - \left(x^{(1)} \right)^T - \\
- \left(x^{(2)} \right)^T - \\
\vdots \\
- \left(x^{(m)} \right)^T - \\
\end{bmatrix}
$$

The second part of the training set is a 5000-dimensional vector `y` that contains labels for the training set.
The following cell randomly selects 100 images from the dataset and plots them.

```python
# Randomly select 100 data points to display
rand_indices = np.random.choice(m, 100, replace=False)
sel = X[rand_indices, :]

utils.displayData(sel)
```

### 1.2 Model representation

Our neural network is shown in the following figure.

It has 3 layers - an input layer, a hidden layer and an output layer. Recall that our inputs are pixel values
of digit images. Since the images are of size $20 \times 20$, this gives us 400 input layer units (not counting the extra bias unit which always outputs +1). The training data was loaded into the variables `X` and `y` above.

You have been provided with a set of network parameters ($\Theta^{(1)}, \Theta^{(2)}$) already trained by us. These are stored in `ex4weights.mat` and will be loaded in the next cell of this notebook into `Theta1` and `Theta2`. The parameters have dimensions that are sized for a neural network with 25 units in the second layer and 10 output units (corresponding to the 10 digit classes).

```python
# Setup the parameters you will use for this exercise
input_layer_size  = 400  # 20x20 Input Images of Digits
hidden_layer_size = 25   # 25 hidden units
num_labels = 10          # 10 labels, from 0 to 9

# Load the weights into variables Theta1 and Theta2
weights = loadmat(os.path.join('Data', 'ex4weights.mat'))

# Theta1 has size 25 x 401
# Theta2 has size 10 x 26
Theta1, Theta2 = weights['Theta1'], weights['Theta2']

# swap first and last columns of Theta2, due to legacy from MATLAB indexing,
# since the weight file ex3weights.mat was saved based on MATLAB indexing
Theta2 = np.roll(Theta2, 1, axis=0)

# Unroll parameters
nn_params = np.concatenate([Theta1.ravel(), Theta2.ravel()])
```

### 1.3 Feedforward and cost function

Now you will implement the cost function and gradient for the neural network. First, complete the code for the function `nnCostFunction` in the next cell to return the cost.

Recall that the cost function for the neural network (without regularization) is:

$$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m}\sum_{k=1}^{K} \left[ - y_k^{(i)} \log \left( \left( h_\theta \left( x^{(i)} \right) \right)_k \right) - \left( 1 - y_k^{(i)} \right) \log \left( 1 - \left( h_\theta \left( x^{(i)} \right) \right)_k \right) \right]$$

where $h_\theta \left( x^{(i)} \right)$ is computed as shown in the neural network figure above, and K = 10 is the total number of possible labels. Note that $h_\theta(x^{(i)})_k = a_k^{(3)}$ is the activation (output
value) of the $k^{th}$ output unit. Also, recall that whereas the original labels (in the variable y) were 0, 1, ..., 9, for the purpose of training a neural network, we need to encode the labels as vectors containing only values 0 or 1, so that

$$ y =
\begin{bmatrix} 1 \\ 0 \\ 0 \\\vdots \\ 0 \end{bmatrix}, \quad
\begin{bmatrix} 0 \\ 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix}, \quad \cdots  \quad \text{or} \qquad
\begin{bmatrix} 0 \\ 0 \\ 0 \\ \vdots \\ 1 \end{bmatrix}.
$$

For example, if $x^{(i)}$ is an image of the digit 5, then the corresponding $y^{(i)}$ (that you should use with the cost function) should be a 10-dimensional vector with $y_5 = 1$, and the other elements equal to 0.

You should implement the feedforward computation that computes $h_\theta(x^{(i)})$ for every example $i$ and sum the cost over all examples. **Your code should also work for a dataset of any size, with any number of labels** (you can assume that there are always at least $K \ge 3$ labels).

**Implementation Note:** The matrix $X$ contains the examples in rows (i.e., X[i,:] is the i-th training example $x^{(i)}$, expressed as a $n \times 1$ vector.) When you complete the code in `nnCostFunction`, you will need to add the column of 1’s to the X matrix. The parameters for each unit in the neural network is represented in Theta1 and Theta2 as one row. Specifically, the first row of Theta1 corresponds to the first hidden unit in the second layer. You can use a for-loop over the examples to compute the cost.

```python
def nnCostFunction(nn_params,
                   input_layer_size,
                   hidden_layer_size,
                   num_labels,
                   X, y, lambda_=0.0):
    """
    Implements the neural network cost function and gradient for a two layer neural
    network which performs classification.

    Parameters
    ----------
    nn_params : array_like
        The parameters for the neural network which are "unrolled" into
        a vector. This needs to be converted back into the weight matrices Theta1
        and Theta2.

    input_layer_size : int
        Number of features for the input layer.

    hidden_layer_size : int
        Number of hidden units in the second layer.

    num_labels : int
        Total number of labels, or equivalently number of units in output layer.

    X : array_like
        Input dataset. A matrix of shape (m x input_layer_size).

    y : array_like
        Dataset labels. A vector of shape (m,).

    lambda_ : float, optional
        Regularization parameter.

    Returns
    -------
    J : float
        The computed value for the cost function at the current weight values.

    grad : array_like
        An "unrolled" vector of the partial derivatives of the concatenatation of
        neural network weights Theta1 and Theta2.

    Instructions
    ------------
    You should complete the code by working through the following parts.

    - Part 1: Feedforward the neural network and return the cost in the
              variable J. After implementing Part 1, you can verify that your
              cost function computation is correct by verifying the cost
              computed in the following cell.

    - Part 2: Implement the backpropagation algorithm to compute the gradients
              Theta1_grad and Theta2_grad. You should return the partial derivatives of
              the cost function with respect to Theta1 and Theta2 in Theta1_grad and
              Theta2_grad, respectively. After implementing Part 2, you can check
              that your implementation is correct by running checkNNGradients provided
              in the utils.py module.

              Note: The vector y passed into the function is a vector of labels
                    containing values from 0..K-1. You need to map this vector into a
                    binary vector of 1's and 0's to be used with the neural network
                    cost function.

              Hint: We recommend implementing backpropagation using a for-loop
                    over the training examples if you are implementing it for the
                    first time.

    - Part 3: Implement regularization with the cost function and gradients.

              Hint: You can implement this around the code for
                    backpropagation. That is, you can compute the gradients for
                    the regularization separately and then add them to Theta1_grad
                    and Theta2_grad from Part 2.

    Note
    ----
    We have provided an implementation for the sigmoid function in the file
    `utils.py` accompanying this assignment.
    """
    # Reshape nn_params back into the parameters Theta1 and Theta2, the weight matrices
    # for our 2 layer neural network
    Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)],
                        (hidden_layer_size, (input_layer_size + 1)))

    Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):],
                        (num_labels, (hidden_layer_size + 1)))

    # Setup some useful variables
    m = y.size

    # You need to return the following variables correctly
    J = 0
    Theta1_grad = np.zeros(Theta1.shape)
    Theta2_grad = np.zeros(Theta2.shape)

    # ====================== YOUR CODE HERE ======================

    # Forward propagation

    a1 = np.concatenate([np.ones((m, 1)), X], axis=1) # Add ones to the X data matrix, shape (m, input_layer_size+1)

    a2 = utils.sigmoid(a1@Theta1.T) # hidden layer, shape (m, hidden_layer_size)
    a2 = np.concatenate([np.ones((m, 1)), a2], axis=1) # shape (m, hidden_layer_size+1)

    h = utils.sigmoid(a2@Theta2.T) # output layer = h(x) = a3, shape (m, K) = (m, num_labels)

    # Map vector y (of labels 0..K-1) into a binary vector of 1's and 0's, shape (m, K)

    y = (y[:,None] == np.arange(num_labels)).astype(int)

    # Cost function

    ones = np.ones(y.shape)

    J = -(1/m)*np.sum(y * np.log(h) + (ones-y) * np.log(ones-h)) + (lambda_/(2*m)) * (np.sum(Theta1[:,1:]**2) + np.sum(Theta2[:,1:]**2))

    # Backpropagation

    # Error values, lowercase delta matrix

    delta_3 = h - y # delta_layer3, shape (m, num_labels)

    ones = np.ones(a2[:,1:].shape)
    delta_2 = a2[:,1:]*(ones-a2[:,1:]) * (delta_3@Theta2)[:,1:] # delta_layer2, shape (m, hidden_layer_size )

    # Gradients of weights, capital delta matrix

    cap_delta_1 = delta_2.T@a1 # shape (hidden_layer_size, input_layer_size)
    cap_delta_2 = delta_3.T@a2 # shape (num_labels, hidden_layer_size)

    # Regularized gradients of weights, capital D matrix

    Theta1_grad = (1/m)*cap_delta_1
    Theta1_grad[:,1:] += (lambda_/m)*Theta1[:,1:]

    Theta2_grad = (1/m)*cap_delta_2
    Theta2_grad[:,1:] += (lambda_/m)*Theta2[:,1:]

    # ================================================================
    # Unroll gradients
    # grad = np.concatenate([Theta1_grad.ravel(order=order), Theta2_grad.ravel(order=order)])
    grad = np.concatenate([Theta1_grad.ravel(), Theta2_grad.ravel()])

    return J, grad
```

Use the following links to go back to the different parts of this exercise that require to modify the function `nnCostFunction`.

Back to:
- [Feedforward and cost function](#section1)
- [Regularized cost](#section2)
- [Neural Network Gradient (Backpropagation)](#section4)
- [Regularized Gradient](#section5)

Once you are done, call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`. You should see that the cost is about 0.287629.

```python
lambda_ = 0
J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size,
                   num_labels, X, y, lambda_)
print('Cost at parameters (loaded from ex4weights): %.6f ' % J)
print('The cost should be about                   : 0.287629.')
```

    Cost at parameters (loaded from ex4weights): 0.287629
    The cost should be about                   : 0.287629.

*You should now submit your solutions.*

```python
grader = utils.Grader()
grader[1] = nnCostFunction
grader.grade()
```

    Submitting Solutions | Programming Exercise neural-network-learning

                                      Part Name |     Score | Feedback
                                      --------- |     ----- | --------
                  Feedforward and Cost Function |  30 /  30 | Nice work!
                      Regularized Cost Function |   0 /  15 |
                               Sigmoid Gradient |   0 /   5 |
      Neural Network Gradient (Backpropagation) |   0 /  40 |
                           Regularized Gradient |   0 /  10 |
                                      --------------------------------
                                                |  30 / 100 |

### 1.4 Regularized cost function

The cost function for neural networks with regularization is given by:

$$ J(\theta) = \frac{1}{m} \sum_{i=1}^{m}\sum_{k=1}^{K} \left[ - y_k^{(i)} \log \left( \left( h_\theta \left( x^{(i)} \right) \right)_k \right) - \left( 1 - y_k^{(i)} \right) \log \left( 1 - \left( h_\theta \left( x^{(i)} \right) \right)_k \right) \right] + \frac{\lambda}{2 m} \left[ \sum_{j=1}^{25} \sum_{k=1}^{400} \left( \Theta_{j,k}^{(1)} \right)^2 + \sum_{j=1}^{10} \sum_{k=1}^{25} \left( \Theta_{j,k}^{(2)} \right)^2 \right] $$

You can assume that the neural network will only have 3 layers - an input layer, a hidden layer and an output layer. However, your code should work for any number of input units, hidden units and outputs units. While we
have explicitly listed the indices above for $\Theta^{(1)}$ and $\Theta^{(2)}$ for clarity, do note that your code should in general work with $\Theta^{(1)}$ and $\Theta^{(2)}$ of any size. Note that you should not be regularizing the terms that correspond to the bias. For the matrices `Theta1` and `Theta2`, this corresponds to the first column of each matrix. You should now add regularization to your cost function. Notice that you can first compute the unregularized cost function $J$ using your existing `nnCostFunction` and then later add the cost for the regularization terms.

[Click here to go back to `nnCostFunction` for editing.](#nnCostFunction)

Once you are done, the next cell will call your `nnCostFunction` using the loaded set of parameters for `Theta1` and `Theta2`, and $\lambda = 1$. You should see that the cost is about 0.383770.

```python
# Weight regularization parameter (we set this to 1 here).
lambda_ = 1
J, _ = nnCostFunction(nn_params, input_layer_size, hidden_layer_size,
                      num_labels, X, y, lambda_)

print('Cost at parameters (loaded from ex4weights): %.6f' % J)
print('This value should be about                 : 0.383770.')
```

    Cost at parameters (loaded from ex4weights): 0.383770
    This value should be about                 : 0.383770.

*You should now submit your solutions.*

```python
grader[2] = nnCostFunction
grader.grade()
```

    Submitting Solutions | Programming Exercise neural-network-learning

                                      Part Name |     Score | Feedback
                                      --------- |     ----- | --------
                  Feedforward and Cost Function |  30 /  30 | Nice work!
                      Regularized Cost Function |  15 /  15 | Nice work!
                               Sigmoid Gradient |   0 /   5 |
      Neural Network Gradient (Backpropagation) |   0 /  40 |
                           Regularized Gradient |   0 /  10 |
                                      --------------------------------
                                                |  45 / 100 |

## 2 Backpropagation

In this part of the exercise, you will implement the backpropagation algorithm to compute the gradient for the neural network cost function. You will need to update the function `nnCostFunction` so that it returns an appropriate value for `grad`. Once you have computed the gradient, you will be able to train the neural network by minimizing the cost function $J(\theta)$ using an advanced optimizer such as `scipy`'s `optimize.minimize`.
You will first implement the backpropagation algorithm to compute the gradients for the parameters for the (unregularized) neural network. After you have verified that your gradient computation for the unregularized case is correct, you will implement the gradient for the regularized neural network.

### 2.1 Sigmoid Gradient

To help you get started with this part of the exercise, you will first implement
the sigmoid gradient function. The gradient for the sigmoid function can be
computed as

$$ g'(z) = \frac{d}{dz} g(z) = g(z)\left(1-g(z)\right) $$

where

$$ \text{sigmoid}(z) = g(z) = \frac{1}{1 + e^{-z}} $$

Now complete the implementation of `sigmoidGradient` in the next cell.

```python
def sigmoidGradient(z):
    """
    Computes the gradient of the sigmoid function evaluated at z.
    This should work regardless if z is a matrix or a vector.
    In particular, if z is a vector or matrix, you should return
    the gradient for each element.

    Parameters
    ----------
    z : array_like
        A vector or matrix as input to the sigmoid function.

    Returns
    --------
    g : array_like
        Gradient of the sigmoid function. Has the same shape as z.

    Instructions
    ------------
    Compute the gradient of the sigmoid function evaluated at
    each value of z (z can be a matrix, vector or scalar).

    Note
    ----
    We have provided an implementation of the sigmoid function
    in `utils.py` file accompanying this assignment.
    """

    g = np.zeros(z.shape)

    # ====================== YOUR CODE HERE ======================

    ones = np.ones(z.shape)
    g = utils.sigmoid(z)*(ones-utils.sigmoid(z))

    # =============================================================
    return g
```

When you are done, the following cell call `sigmoidGradient` on a given vector `z`. Try testing a few values by calling `sigmoidGradient(z)`. For large values (both positive and negative) of z, the gradient should be close to 0. When $z = 0$, the gradient should be exactly 0.25. Your code should also work with vectors and matrices. For a matrix, your function should perform the sigmoid gradient function on every element.

```python
z = np.array([-1, -0.5, 0, 0.5, 1])
g = sigmoidGradient(z)
print('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\n  ')
print(g)
```

    Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:

    [0.19661193 0.23500371 0.25       0.23500371 0.19661193]

*You should now submit your solutions.*

```python
grader[3] = sigmoidGradient
grader.grade()
```

    Submitting Solutions | Programming Exercise neural-network-learning

                                      Part Name |     Score | Feedback
                                      --------- |     ----- | --------
                  Feedforward and Cost Function |  30 /  30 | Nice work!
                      Regularized Cost Function |  15 /  15 | Nice work!
                               Sigmoid Gradient |   5 /   5 | Nice work!
      Neural Network Gradient (Backpropagation) |   0 /  40 |
                           Regularized Gradient |   0 /  10 |
                                      --------------------------------
                                                |  50 / 100 |

## 2.2 Random Initialization

When training neural networks, it is important to randomly initialize the parameters for symmetry breaking. One effective strategy for random initialization is to randomly select values for $\Theta^{(l)}$ uniformly in the range $[-\epsilon_{init}, \epsilon_{init}]$. You should use $\epsilon_{init} = 0.12$. This range of values ensures that the parameters are kept small and makes the learning more efficient.

One effective strategy for choosing $\epsilon_{init}$ is to base it on the number of units in the network. A good choice of $\epsilon_{init}$ is $\epsilon_{init} = \frac{\sqrt{6}}{\sqrt{L_{in} + L_{out}}}$ where $L_{in} = s_l$ and $L_{out} = s_{l+1}$ are the number of units in the layers adjacent to $\Theta^{l}$.

Your job is to complete the function `randInitializeWeights` to initialize the weights for $\Theta$. Modify the function by filling in the following code:

```python
# Randomly initialize the weights to small values
W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init
```
Note that we give the function an argument for $\epsilon$ with default value `epsilon_init = 0.12`.

```python
def randInitializeWeights(L_in, L_out, epsilon_init=0.12):
    """
    Randomly initialize the weights of a layer in a neural network.

    Parameters
    ----------
    L_in : int
        Number of incomming connections.

    L_out : int
        Number of outgoing connections.

    epsilon_init : float, optional
        Range of values which the weight can take from a uniform
        distribution.

    Returns
    -------
    W : array_like
        The weight initialiatized to random values.  Note that W should
        be set to a matrix of size(L_out, 1 + L_in) as
        the first column of W handles the "bias" terms.

    Instructions
    ------------
    Initialize W randomly so that we break the symmetry while training
    the neural network. Note that the first column of W corresponds
    to the parameters for the bias unit.
    """

    # You need to return the following variables correctly
    W = np.zeros((L_out, 1 + L_in))

    # ====================== YOUR CODE HERE ======================

    # Randomly initialize the weights to small values
    W = np.random.rand(L_out, 1 + L_in) * 2 * epsilon_init - epsilon_init

    # ============================================================
    return W
```

*You do not need to submit any code for this part of the exercise.*

Execute the following cell to initialize the weights for the 2 layers in the neural network using the `randInitializeWeights` function.

```python
print('Initializing Neural Network Parameters ...')

initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size)
initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels)

# Unroll parameters
initial_nn_params = np.concatenate([initial_Theta1.ravel(), initial_Theta2.ravel()], axis=0)
```

    Initializing Neural Network Parameters ...

### 2.4 Backpropagation

Now, you will implement the backpropagation algorithm. Recall that the intuition behind the backpropagation algorithm is as follows. Given a training example $(x^{(t)}, y^{(t)})$, we will first run a “forward pass” to compute all the activations throughout the network, including the output value of the hypothesis $h_\theta(x)$. Then, for each node $j$ in layer $l$, we would like to compute an “error term” $\delta_j^{(l)}$ that measures how much that node was “responsible” for any errors in our output.

For an output node, we can directly measure the difference between the network’s activation and the true target value, and use that to define $\delta_j^{(3)}$ (since layer 3 is the output layer). For the hidden units, you will compute $\delta_j^{(l)}$ based on a weighted average of the error terms of the nodes in layer $(l+1)$. In detail, here is the backpropagation algorithm (also depicted in the figure above). You should implement steps 1 to 4 in a loop that processes one example at a time. Concretely, you should implement a for-loop `for t in range(m)` and place steps 1-4 below inside the for-loop, with the $t^{th}$ iteration performing the calculation on the $t^{th}$ training example $(x^{(t)}, y^{(t)})$. Step 5 will divide the accumulated gradients by $m$ to obtain the gradients for the neural network cost function.

1. Set the input layer’s values $(a^{(1)})$ to the $t^{th }$training example $x^{(t)}$. Perform a feedforward pass, computing the activations $(z^{(2)}, a^{(2)}, z^{(3)}, a^{(3)})$ for layers 2 and 3. Note that you need to add a `+1` term to ensure that the vectors of activations for layers $a^{(1)}$ and $a^{(2)}$ also include the bias unit. In `numpy`, if a 1 is a column matrix, adding one corresponds to `a_1 = np.concatenate([np.ones((m, 1)), a_1], axis=1)`.

1. For each output unit $k$ in layer 3 (the output layer), set
$$\delta_k^{(3)} = \left(a_k^{(3)} - y_k \right)$$
where $y_k \in \{0, 1\}$ indicates whether the current training example belongs to class $k$ $(y_k = 1)$, or if it belongs to a different class $(y_k = 0)$. You may find logical arrays helpful for this task (explained in the previous programming exercise).

1. For the hidden layer $l = 2$, set
$$ \delta^{(2)} = \left( \Theta^{(2)} \right)^T \delta^{(3)} * g'\left(z^{(2)} \right)$$
Note that the symbol $*$ performs element wise multiplication in `numpy`.

1. Accumulate the gradient from this example using the following formula. Note that you should skip or remove $\delta_0^{(2)}$. In `numpy`, removing $\delta_0^{(2)}$ corresponds to `delta_2 = delta_2[1:]`.
$$ \Delta^{(l)} = \Delta^{(l)} + \delta^{(l+1)} (a^{(l)})^{(T)} $$

1. Obtain the (unregularized) gradient for the neural network cost function by dividing the accumulated gradients by $\frac{1}{m}$:
$$ \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)}$$

**Python/Numpy tip**: You should implement the backpropagation algorithm only after you have successfully completed the feedforward and cost functions. While implementing the backpropagation algorithm, it is often useful to use the `shape` function to print out the shapes of the variables you are working with if you run into dimension mismatch errors.

[Click here to go back and update the function `nnCostFunction` with the backpropagation algorithm](#nnCostFunction).

**Note:** If the iterative solution provided above is proving to be difficult to implement, try implementing the vectorized approach which is easier to implement in the opinion of the moderators of this course. You can find the tutorial for the vectorized approach [here](https://www.coursera.org/learn/machine-learning/discussions/all/threads/a8Kce_WxEeS16yIACyoj1Q).

After you have implemented the backpropagation algorithm, we will proceed to run gradient checking on your implementation. The gradient check will allow you to increase your confidence that your code is
computing the gradients correctly.

### 2.4  Gradient checking

In your neural network, you are minimizing the cost function $J(\Theta)$. To perform gradient checking on your parameters, you can imagine “unrolling” the parameters $\Theta^{(1)}$, $\Theta^{(2)}$ into a long vector $\theta$. By doing so, you can think of the cost function being $J(\Theta)$ instead and use the following gradient checking procedure.

Suppose you have a function $f_i(\theta)$ that purportedly computes $\frac{\partial}{\partial \theta_i} J(\theta)$; you’d like to check if $f_i$ is outputting correct derivative values.

$$
\text{Let } \theta^{(i+)} = \theta + \begin{bmatrix} 0 \\ 0 \\ \vdots \\ \epsilon \\ \vdots \\ 0 \end{bmatrix}
\quad \text{and} \quad \theta^{(i-)} = \theta - \begin{bmatrix} 0 \\ 0 \\ \vdots \\ \epsilon \\ \vdots \\ 0 \end{bmatrix}
$$

So, $\theta^{(i+)}$ is the same as $\theta$, except its $i^{th}$ element has been incremented by $\epsilon$. Similarly, $\theta^{(i−)}$ is the corresponding vector with the $i^{th}$ element decreased by $\epsilon$. You can now numerically verify $f_i(\theta)$’s correctness by checking, for each $i$, that:

$$ f_i\left( \theta \right) \approx \frac{J\left( \theta^{(i+)}\right) - J\left( \theta^{(i-)} \right)}{2\epsilon} $$

The degree to which these two values should approximate each other will depend on the details of $J$. But assuming $\epsilon = 10^{-4}$, you’ll usually find that the left- and right-hand sides of the above will agree to at least 4 significant digits (and often many more).

We have implemented the function to compute the numerical gradient for you in `computeNumericalGradient` (within the file `utils.py`). While you are not required to modify the file, we highly encourage you to take a look at the code to understand how it works.

In the next cell we will run the provided function `checkNNGradients` which will create a small neural network and dataset that will be used for checking your gradients. If your backpropagation implementation is correct,
you should see a relative difference that is less than 1e-9.

**Practical Tip**: When performing gradient checking, it is much more efficient to use a small neural network with a relatively small number of input units and hidden units, thus having a relatively small number
of parameters. Each dimension of $\theta$ requires two evaluations of the cost function and this can be expensive. In the function `checkNNGradients`, our code creates a small random model and dataset which is used with `computeNumericalGradient` for gradient checking. Furthermore, after you are confident that your gradient computations are correct, you should turn off gradient checking before running your learning algorithm.

Practical Tip: Gradient checking works for any function where you are computing the cost and the gradient. Concretely, you can use the same `computeNumericalGradient` function to check if your gradient implementations for the other exercises are correct too (e.g., logistic regression’s cost function).

```python
utils.checkNNGradients(nnCostFunction)
```

    [[-9.27825235e-03 -9.27825236e-03]
     [-3.04978709e-06 -3.04978914e-06]
     [-1.75060084e-04 -1.75060082e-04]
     [-9.62660640e-05 -9.62660620e-05]
     [ 8.89911959e-03  8.89911960e-03]
     [ 1.42869450e-05  1.42869443e-05]
     [ 2.33146358e-04  2.33146357e-04]
     [ 1.17982666e-04  1.17982666e-04]
     [-8.36010761e-03 -8.36010762e-03]
     [-2.59383093e-05 -2.59383100e-05]
     [-2.87468729e-04 -2.87468729e-04]
     [-1.37149709e-04 -1.37149706e-04]
     [ 7.62813550e-03  7.62813551e-03]
     [ 3.69883257e-05  3.69883234e-05]
     [ 3.35320351e-04  3.35320347e-04]
     [ 1.53247082e-04  1.53247082e-04]
     [-6.74798369e-03 -6.74798370e-03]
     [-4.68759764e-05 -4.68759769e-05]
     [-3.76215583e-04 -3.76215587e-04]
     [-1.66560294e-04 -1.66560294e-04]
     [ 3.14544970e-01  3.14544970e-01]
     [ 1.64090819e-01  1.64090819e-01]
     [ 1.64567932e-01  1.64567932e-01]
     [ 1.58339334e-01  1.58339334e-01]
     [ 1.51127527e-01  1.51127527e-01]
     [ 1.49568335e-01  1.49568335e-01]
     [ 1.11056588e-01  1.11056588e-01]
     [ 5.75736494e-02  5.75736493e-02]
     [ 5.77867378e-02  5.77867378e-02]
     [ 5.59235296e-02  5.59235296e-02]
     [ 5.36967009e-02  5.36967009e-02]
     [ 5.31542052e-02  5.31542052e-02]
     [ 9.74006970e-02  9.74006970e-02]
     [ 5.04575855e-02  5.04575855e-02]
     [ 5.07530173e-02  5.07530173e-02]
     [ 4.91620841e-02  4.91620841e-02]
     [ 4.71456249e-02  4.71456249e-02]
     [ 4.65597186e-02  4.65597186e-02]]
    The above two columns you get should be very similar.
    (Left-Your Numerical Gradient, Right-Analytical Gradient)

    If your backpropagation implementation is correct, then
    the relative difference will be small (less than 1e-9).
    Relative Difference: 2.33368e-11

*Once your cost function passes the gradient check for the (unregularized) neural network cost function, you should submit the neural network gradient function (backpropagation).*

```python
grader[4] = nnCostFunction
grader.grade()
```

    Submitting Solutions | Programming Exercise neural-network-learning

                                      Part Name |     Score | Feedback
                                      --------- |     ----- | --------
                  Feedforward and Cost Function |  30 /  30 | Nice work!
                      Regularized Cost Function |  15 /  15 | Nice work!
                               Sigmoid Gradient |   5 /   5 | Nice work!
      Neural Network Gradient (Backpropagation) |  40 /  40 | Nice work!
                           Regularized Gradient |   0 /  10 |
                                      --------------------------------
                                                |  90 / 100 |

### 2.5 Regularized Neural Network

After you have successfully implemented the backpropagation algorithm, you will add regularization to the gradient. To account for regularization, it turns out that you can add this as an additional term *after* computing the gradients using backpropagation.

Specifically, after you have computed $\Delta_{ij}^{(l)}$ using backpropagation, you should add regularization using

$$
\begin{align}
& \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)} & \qquad \text{for } j = 0 \\
& \frac{\partial}{\partial \Theta_{ij}^{(l)}} J(\Theta) = D_{ij}^{(l)} = \frac{1}{m} \Delta_{ij}^{(l)} + \frac{\lambda}{m} \Theta_{ij}^{(l)} & \qquad \text{for } j \ge 1
\end{align}
$$

Note that you should *not* be regularizing the first column of $\Theta^{(l)}$ which is used for the bias term. Furthermore, in the parameters $\Theta_{ij}^{(l)}$, $i$ is indexed starting from 1, and $j$ is indexed starting from 0. Thus,

$$
\Theta^{(l)} = \begin{bmatrix}
\Theta_{1,0}^{(i)} & \Theta_{1,1}^{(l)} & \cdots \\
\Theta_{2,0}^{(i)} & \Theta_{2,1}^{(l)} & \cdots \\
\vdots &  ~ & \ddots
\end{bmatrix}
$$

[Now modify your code that computes grad in `nnCostFunction` to account for regularization.](#nnCostFunction)

After you are done, the following cell runs gradient checking on your implementation. If your code is correct, you should expect to see a relative difference that is less than 1e-9.

```python
#  Check gradients by running checkNNGradients
lambda_ = 3
utils.checkNNGradients(nnCostFunction, lambda_)

# Also output the costFunction debugging values
debug_J, _  = nnCostFunction(nn_params, input_layer_size,
                          hidden_layer_size, num_labels, X, y, lambda_)

print('\n\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' % (lambda_, debug_J))
print('(for lambda = 3, this value should be about 0.576051)')
```

    [[-9.27825235e-03 -9.27825236e-03]
     [-1.67679797e-02 -1.67679797e-02]
     [-6.01744725e-02 -6.01744725e-02]
     [-1.73704651e-02 -1.73704651e-02]
     [ 8.89911959e-03  8.89911960e-03]
     [ 3.94334829e-02  3.94334829e-02]
     [-3.19612287e-02 -3.19612287e-02]
     [-5.75658668e-02 -5.75658668e-02]
     [-8.36010761e-03 -8.36010762e-03]
     [ 5.93355565e-02  5.93355565e-02]
     [ 2.49225535e-02  2.49225535e-02]
     [-4.51963845e-02 -4.51963845e-02]
     [ 7.62813550e-03  7.62813551e-03]
     [ 2.47640974e-02  2.47640974e-02]
     [ 5.97717617e-02  5.97717617e-02]
     [ 9.14587966e-03  9.14587966e-03]
     [-6.74798369e-03 -6.74798370e-03]
     [-3.26881426e-02 -3.26881426e-02]
     [ 3.86410548e-02  3.86410548e-02]
     [ 5.46101547e-02  5.46101547e-02]
     [ 3.14544970e-01  3.14544970e-01]
     [ 1.18682669e-01  1.18682669e-01]
     [ 2.03987128e-01  2.03987128e-01]
     [ 1.25698067e-01  1.25698067e-01]
     [ 1.76337550e-01  1.76337550e-01]
     [ 1.32294136e-01  1.32294136e-01]
     [ 1.11056588e-01  1.11056588e-01]
     [ 3.81928689e-05  3.81928696e-05]
     [ 1.17148233e-01  1.17148233e-01]
     [-4.07588279e-03 -4.07588279e-03]
     [ 1.13133142e-01  1.13133142e-01]
     [-4.52964427e-03 -4.52964427e-03]
     [ 9.74006970e-02  9.74006970e-02]
     [ 3.36926556e-02  3.36926556e-02]
     [ 7.54801264e-02  7.54801264e-02]
     [ 1.69677090e-02  1.69677090e-02]
     [ 8.61628953e-02  8.61628953e-02]
     [ 1.50048382e-03  1.50048382e-03]]
    The above two columns you get should be very similar.
    (Left-Your Numerical Gradient, Right-Analytical Gradient)

    If your backpropagation implementation is correct, then
    the relative difference will be small (less than 1e-9).
    Relative Difference: 2.21026e-11

    Cost at (fixed) debugging parameters (w/ lambda = 3.000000): 0.576051
    (for lambda = 3, this value should be about 0.576051)

```python
grader[5] = nnCostFunction
grader.grade()
```

    Submitting Solutions | Programming Exercise neural-network-learning

                                      Part Name |     Score | Feedback
                                      --------- |     ----- | --------
                  Feedforward and Cost Function |  30 /  30 | Nice work!
                      Regularized Cost Function |  15 /  15 | Nice work!
                               Sigmoid Gradient |   5 /   5 | Nice work!
      Neural Network Gradient (Backpropagation) |  40 /  40 | Nice work!
                           Regularized Gradient |  10 /  10 | Nice work!
                                      --------------------------------
                                                | 100 / 100 |

### 2.6 Learning parameters using `scipy.optimize.minimize`

After you have successfully implemented the neural network cost function
and gradient computation, the next step we will use `scipy`'s minimization to learn a good set parameters.

```python
#  After you have completed the assignment, change the maxiter to a larger
#  value to see how more training helps.
options= {'maxiter': 100}

#  You should also try different values of lambda
lambda_ = 1

# Create "short hand" for the cost function to be minimized
costFunction = lambda p: nnCostFunction(p, input_layer_size,
                                        hidden_layer_size,
                                        num_labels, X, y, lambda_)

# Now, costFunction is a function that takes in only one argument
# (the neural network parameters)
res = optimize.minimize(costFunction,
                        initial_nn_params,
                        jac=True,
                        method='TNC',
                        options=options)

# get the solution of the optimization
nn_params = res.x

# Obtain Theta1 and Theta2 back from nn_params
Theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)],
                    (hidden_layer_size, (input_layer_size + 1)))

Theta2 = np.reshape(nn_params[(hidden_layer_size * (input_layer_size + 1)):],
                    (num_labels, (hidden_layer_size + 1)))
```

After the training completes, we will proceed to report the training accuracy of your classifier by computing the percentage of examples it got correct. If your implementation is correct, you should see a reported
training accuracy of about 95.3% (this may vary by about 1% due to the random initialization). It is possible to get higher training accuracies by training the neural network for more iterations. We encourage you to try
training the neural network for more iterations (e.g., set `maxiter` to 400) and also vary the regularization parameter $\lambda$. With the right learning settings, it is possible to get the neural network to perfectly fit the training set.

```python
pred = utils.predict(Theta1, Theta2, X)
print('Training Set Accuracy: %f' % (np.mean(pred == y) * 100))
```

    Training Set Accuracy: 94.800000

## 3 Visualizing the Hidden Layer

One way to understand what your neural network is learning is to visualize what the representations captured by the hidden units. Informally, given a particular hidden unit, one way to visualize what it computes is to find an input $x$ that will cause it to activate (that is, to have an activation value
($a_i^{(l)}$) close to 1). For the neural network you trained, notice that the $i^{th}$ row of $\Theta^{(1)}$ is a 401-dimensional vector that represents the parameter for the $i^{th}$ hidden unit. If we discard the bias term, we get a 400 dimensional vector that represents the weights from each input pixel to the hidden unit.

Thus, one way to visualize the “representation” captured by the hidden unit is to reshape this 400 dimensional vector into a 20 × 20 image and display it (It turns out that this is equivalent to finding the input that gives the highest activation for the hidden unit, given a “norm” constraint on the input (i.e., $||x||_2 \le 1$)).

The next cell does this by using the `displayData` function and it will show you an image with 25 units,
each corresponding to one hidden unit in the network. In your trained network, you should find that the hidden units corresponds roughly to detectors that look for strokes and other patterns in the input.

```python
utils.displayData(Theta1[:, 1:])
```

### 3.1 Optional (ungraded) exercise

In this part of the exercise, you will get to try out different learning settings for the neural network to see how the performance of the neural network varies with the regularization parameter $\lambda$ and number of training steps (the `maxiter` option when using `scipy.optimize.minimize`). Neural networks are very powerful models that can form highly complex decision boundaries. Without regularization, it is possible for a neural network to “overfit” a training set so that it obtains close to 100% accuracy on the training set but does not as well on new examples that it has not seen before. You can set the regularization $\lambda$ to a smaller value and the `maxiter` parameter to a higher number of iterations to see this for youself.


```python
from qiskit_textbook.widgets import plot_bloch_vector_spherical
from numpy import pi
```

## The Simplest Quantum System

The unit of quantum information is represented by a _logical qubit_. A logical qubit is a model of a quantum system that can occupy one of two possible states. There are many possible _physical_ realisations of a qubit, some of which do not necessarily imply 1-1 correspondence (logical-physical). Energy levels of atoms and ions or simultaneous states of arrays of ions, spin states of localised electrons, parity states of Majorana zero modes all provide examples of such realisations. Nevertheless, the unifying feature of the above listed models and other candidates for physical qubits is that, quantum-mechanically, they are characterised as 2-state systems. Therefore, it makes sense to study such systems, which are incidentally the simplest non-trivial ones in quantum mechanics, in some detail. The discussion outlined below is most often presented in the context of a particle spin. The formalism, however, is completely general and, up to a point can be developed without reference to spin as the intrinsic magnetic moment. Instead, we can see how the spin formalism emerges from the description of a 2-state system as the result of spatial quantization.

Consider a quantum system that can exist in one of two states customarily labelled $0$ and $1$, respectively. Such a system is characterised by a two-component state-vector

$$\chi \equiv \begin{bmatrix}\psi(0)\\ \psi(1)\end{bmatrix} = \begin{bmatrix}\alpha \\ \beta \end{bmatrix},$$

where $\alpha$ and $\beta$ are complex numbers. Alternatively, $\chi$ can be written as a superposition of the system being in the states

$$|0\rangle = \begin{bmatrix}1 \\ 0\end{bmatrix}, \quad |1\rangle = \begin{bmatrix}0 \\ 1\end{bmatrix},$$

as follows

$$\chi = \alpha|0\rangle + \beta|1\rangle. \tag{1}\label{qubit}$$

Consequently, the probabilities of the system being found in either $|0\rangle$ or $|1\rangle$ are $|\alpha|^2$ and $|\beta|^2$, respectively, and we must have

$$|\alpha|^2 + |\beta|^2 = 1.$$

The form of the state vector given by \eqref{qubit} is often referred to as the _qubit_. Evolution of our system will be described by a Hamiltonian represented by a $2\times 2$ matrix

$$\mathcal{H}=\begin{bmatrix}H_{00} & H_{01} \\ H_{10} & H_{11}\end{bmatrix}.$$

The hermiticity requirement dictates that we must set $H^{*}_{01} = H_{10} = a_1 + ia_2$ where $a_1$, $a_2$ are real. Furthermore, without loss of generality we can set $H_{00} = a_0 + a_3$ and $H_{11} = a_0 - a_3$ (again, $a_0$, $a_3$ being real numbers).

$$\mathcal{H}=\begin{bmatrix}a_0 + a_3 & a_1 - ia_2 \\ a_1+ia_2 & a_0-a_3\end{bmatrix}=a_0\sigma_0+a_1\sigma_x+a_2\sigma_y+a_3\sigma_z = a_0\sigma_0 + \vec{a}\cdot\vec{\sigma}.$$

Here $\sigma_x, \sigma_y, \sigma_z$ are the standard Pauli matrices

$$
\sigma_x=\begin{bmatrix}0 & 1 \\ 1 & 0\end{bmatrix}, \quad \sigma_y=\begin{bmatrix}0 & -i \\ i & 0\end{bmatrix}, \quad \sigma_z=\begin{bmatrix}1 & 0 \\ 0 & -1\end{bmatrix},
$$

and $\sigma_0$ is the $2\times 2$ identity matrix. Using the identity

$$
(\vec{\sigma}\cdot\vec{a})(\vec{\sigma}\cdot\vec{b}) = \vec{a}\cdot\vec{b} + i\vec{\sigma}\cdot\vec{a}\times\vec{b} \label{eq1}\tag{2}
$$

Setting $\vec{a}=\vec{b}=\vec{n}$ where $\vec{n}$ is a unit vector we find

$$
(\vec{\sigma}\cdot\vec{n})^2 = 1.
$$

The interpretation of this is that the eigenvalues of $\vec{\sigma}\cdot{n}$ are always $\pm 1$. Using the same identity \eqref{eq1} we can find the eigenenergies of the system

$$
\begin{align}
\mathcal{H}|\chi\rangle &= E|\chi\rangle, \\
\vec{\sigma}\cdot\vec{a}|\chi\rangle &= (E-a_0)|\chi\rangle \label{eq2}\tag{3}.
\end{align}
$$

Now multiply both sides by $\vec{\sigma}\cdot\vec{a}$ and observe that $(\vec{\sigma}\cdot\vec{a})^2=\vec{a}\cdot\vec{a}+i\vec{\sigma}\cdot\underbrace{\vec{a}\times \vec{a}}_{=\vec{0}} = |\vec{a}|^2$ to obtain

$$
|\vec{a}|^2|\chi\rangle=(E-a_0)\vec{\sigma}\cdot\vec{a}|\chi\rangle. \label{eq3}\tag{4}
$$

Comparing \eqref{eq2} and \eqref{eq3} we find

$$
E = a_0 \pm |\vec{a}|
$$

## Unitary Geometry

Writing the components of a unit vector $\vec{n}$ in spherical coordinates

$$
\vec{n}=(n_x, n_y, n_z) = (\sin{\theta}\cos{\phi}, \sin{\theta}\sin{\phi}, \cos{\theta}),
$$

we find

$$
\vec{\sigma}\cdot\vec{n} = \begin{bmatrix}\cos{\theta} & \sin{\theta}e^{-i\phi} \\ \sin{\theta}e^{i\phi} & -\cos{\theta}\end{bmatrix} \tag{5}\label{spinor}
$$

The eigenvectors of \eqref{spinor} corresponding to the eigenvalues +1 and -1, respectively are called _spinors_ and can be written as follows

$$
\begin{align}
|\chi^{+}\rangle &= \cos\frac{\theta}{2}|0\rangle + \sin\frac{\theta}{2}e^{i\phi}|1\rangle \\
|\chi^{-}\rangle &= \sin\frac{\theta}{2}|0\rangle - \cos\frac{\theta}{2}e^{i\phi}|1\rangle
\end{align}
$$

Adding a global phase factor $e^{i\gamma}$ the most general form of a spinor is found

$$
|\chi^{+}\rangle = e^{i\gamma}\left(\cos\frac{\theta}{2}|0\rangle + \sin\frac{\theta}{2}e^{i\phi}|1\rangle\right) \tag{6}\label{spinor_gen}
$$

The angles $\theta$ and $\phi$ determine the representation of a spinor on the Bloch sphere. The qubit ([1](#mjx-eqn-qubit)) can be written in the form \eqref{spinor_gen} as follows

$$
|\chi\rangle = \begin{bmatrix}|\alpha|e^{i\phi_{\alpha}} \\ |\beta|e^{i\phi_{\beta}} \end{bmatrix} = e^{i\phi_{\alpha}}\begin{bmatrix}|\alpha| \\ |\beta|e^{i(\phi_{\beta}-\phi_{\alpha})} \end{bmatrix}.
$$

Hence, it suffices to set

$$
\begin{align}
\gamma &= \phi_{\alpha} \\
\theta &= 2\arctan\left(\frac{\sqrt{1-|\alpha|^2}}{|\alpha|}\right)\\
\phi &= \phi_{\alpha} - \phi_{\beta}
\end{align}
$$

In particular states $|0\rangle$ and $|1\rangle$ are identified with the North and South poles of the Bloch sphere

$$
\begin{align}
|0\rangle &= |\chi^{+}(\theta=0, \phi, \gamma)\rangle \\
|1\rangle &= |\chi^{+}(\theta=\pi, \phi, \gamma)\rangle
\end{align}
$$

# Quantum logic gates as rotations

### The Hadamard matrix

The Hadamard matrix $H$ is given by

$$
H=\frac{1}{\sqrt{2}}\begin{bmatrix}1 & 1 \\ 1 & -1 \end{bmatrix}
$$

One of its eigenvectors can be shown to be

$$
|\chi\rangle = \cos\frac{\pi}{8}|0\rangle + \sin\frac{\pi}{8}|1\rangle,
$$

whereby we find that $\theta=\frac{\pi}{4}$ and $\phi=0$. Hence this eigenvector lies in the $xz$ plane and is rotated halfway between the north pole and the point where the positive $x$-axis intersects the Bloch sphere.

```python
coords = [pi/4,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
```

### The Spin Flip Matrix

It is easy to check that the matrix

$$
M = \begin{bmatrix} 0 & -e^{-i\phi} \\ e^{i\phi} & 0 \end{bmatrix}
$$

changes $|\chi^{-}\rangle$ to $|\chi^{+}\rangle$. $M$ can also be written as a product

$$
M = \begin{bmatrix} 1 & 0 \\ 1 & e^{i\phi} \end{bmatrix} \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 1 & 0 \\ 1 & e^{-i\phi} \end{bmatrix} = e^{i\frac{\pi}{2}}P(\phi)\sigma_yP(-\phi),
$$

where

$$
P(\phi) = \begin{bmatrix} 1 & 0 \\ 0 & e^{i\phi} \end{bmatrix}
$$

is the phase-shift matrix. Its special cases frequently used in the design of quantum logic gates are the $S$ matrix

$$
S = \begin{bmatrix} 1 & 0 \\ 0 & i \end{bmatrix}
$$

and the $T$ matrix

$$
T = \begin{bmatrix} 1 & 0 \\ 0 & e^{i\frac{\pi}{4}} \end{bmatrix}
$$

### General rotations about coordinate axes
TODO

### Square-Root-of-Not

TODO

$$
\sqrt{\text{NOT}} = \begin{bmatrix} \frac{1+i}{2} & \frac{1-i}{2} \\ \frac{1-i}{2} & \frac{1+i}{2} \end{bmatrix}
$$


```python
from bokeh.plotting import output_notebook, figure, show
output_notebook()
```

```python
import numpy as np
```

```python
import sympy as sp
```

Next, import some shortcuts:
- `S` turns the argument into a SymPy object. For example, `S("1/3")` evaluates to `1/3` *exactly*, avoiding issues related to Python's meaning of `/`.
- `Eq` creates an equation, but here I abuse it to print definitions of some variables.

```python
from sympy import S, Eq
```

Now initialize printing to get pretty formulas in this notebook:

```python
sp.init_printing()
```

Define variables

Note that $C_0$, etc are defined as SymPy variables to make it easier to inspect formulas defining $H$ and $u$ below (this hides unimportant details).

I'm working on the domain $x \in [0, R_0]$, $z \in [0, h(x)]$, so I assume that all these variables are positive. This allows SymPy to simplify some expressions involving powers.

```python
sp.var("x y z sigma B R_0 H_0 t_0 t s rho_i g C_0 C_1 C_2", positive=True)
h = sp.Function("h")(x)
```

Here I define a few constants in a dictionary. I can supply this dictionary in `expr.subs(...)` to perform substitutions below.

```python
A = 3.1689e-24
constants = {H_0 : 1000, # ice thickness at the center at t_0
             R_0: 750e3, # radius at t_0
             s: 1,       # (t / t_0)^(-1/11), s = 1 means use t_0
             g: 9.81,    # acceleration due to gravity
             rho_i: 910, # ice density
             B: A**(-1.0/3.0)} # ice hardness
constants
```

Next, I define `s0` to hide its details and because I'm not interested in time dependence.

```python
s0 = (t / t_0)**S("-1/11")
c_0 = H_0 * s
Eq(C_0, c_0)
```

```python
c_1 = s / R_0
Eq(C_1, c_1)
```

```python
c_2 = 2 * B**(-3) * (rho_i * g)**3 / 4
Eq(C_2, c_2)
```

```python
# Combine definitions to simplify substitutions
definitions = {C_0: c_0, C_1: c_1, C_2: c_2}
definitions
```

Now it's time to define the Halfar dome profile:

```python
H = C_0 * (1 - (C_1 * x)**S("4/3"))**S("3/7")
Eq(h, H)
```

Sanity check:

```python
xx = np.linspace(0, constants[R_0]-1, 1001)

HH = sp.lambdify(x, H.subs(definitions).subs(constants))

fig = figure(plot_width=750, plot_height=300, title="Halfar dome profile")
fig.line(xx, HH(xx), line_width=2)
show(fig)
```

Now I can define the SIA velocity:

```python
u = sp.Function("u")(x, z)
U = -C_2 * (h**4 - (h - z)**4) * h.diff(x)**3
Eq(u, U)
```

$\displaystyle u{\left(x,z \right)} = - C_{2} \left(- \left(- z + h{\left(x \right)}\right)^{4} + h^{4}{\left(x \right)}\right) \left(\frac{d}{d x} h{\left(x \right)}\right)^{3}$

I prefer to define $u$ as a function of $x, \sigma$ because in these coordinates the domain is a rectangle and it's easy to work with.

```python
u_s = sp.Function("u")(x, sigma)
U_s = U.subs(z, sigma * h).factor()
Eq(u_s, U_s)
```

$\displaystyle u{\left(x,\sigma \right)} = C_{2} \sigma \left(\sigma - 2\right) \left(\sigma^{2} - 2 \sigma + 2\right) h^{4}{\left(x \right)} \left(\frac{d}{d x} h{\left(x \right)}\right)^{3}$

In my tests I saw that the B-P velocity "looks" linear in the *shallow* part of the domain, so I wanted to check if the SIA velocity is.

Here:

```python
U_s.subs(h, H).doit()
```

$\displaystyle - \frac{64 C_{0}^{7} C_{1}^{4} C_{2} \sigma x \left(\sigma - 2\right) \left(\sigma^{2} - 2 \sigma + 2\right)}{343}$

```python
U_s_numpy = sp.lambdify([x, sigma], U_s.subs(h, H).subs(definitions).subs(constants).doit())

fig = figure(plot_width=750, plot_height=400,
             title="SIA velocity at levels of constant sigma")

xx = np.linspace(0, constants[R_0], 101)
for sig in np.linspace(0, 1, 11):
    fig.line(xx, U_s_numpy(xx, sig))
show(fig)
```

Define the Blatter-Pattyn system:

```python
# velocity components
u = sp.Function("u")(x, y, z)
v = sp.Function("v")(x, y, z)

def div(f):
    "Divergence"
    return f[0].diff(x) + f[1].diff(y) + f[2].diff(z)

def grad(f):
    "Gradient"
    return sp.Matrix([f.diff(x), f.diff(y), f.diff(z)])

def second_invariant(u, v):
    """Second invariant of the strain rate tensor"""
    ux = u.diff(x)
    uy = u.diff(y)
    uz = u.diff(z)

    vx = v.diff(x)
    vy = v.diff(y)
    vz = v.diff(z)

    # In the BP approximation we assume that dw/dx << du/dz and dw/dy << dv/dz, so these
    # terms are omitted.
    wx = S(0)
    wy = S(0)

    return ux**2 + vy**2 + ux * vy + S(1) / 4 * ((uy + vx)**2 + (uz + wx)**2 + (vz + wy)**2)

def eta(u, v, n):
    "Ice viscosity"

    n = S(n)

    gamma = second_invariant(u, v)

    return S(1) / 2 * B * gamma**((1 - n) / (2 * n))

def M(u, v):
    "'Effective' strain rate tensor corresponding to the Blatter-Pattyn system"
    return sp.Matrix([[4 * u.diff(x) + 2 * v.diff(y), u.diff(y) + v.diff(x), u.diff(z)],
                      [u.diff(y) + v.diff(x), 2 * u.diff(x) + 4 * v.diff(y), v.diff(z)]])

def source_term(E, u, v):
    "Compute the source term required by a given 'exact' solution."
    # we assume that the system is written in this form:
    #
    # -div(eta*M) + f = 0
    #
    # where eta is ice viscosity and M is the effective strain rate tensor
    #
    # in the "regular" context
    #
    # f = rho * g * grad(s)

    f_u = div(E * M(u, v).row(0))
    f_v = div(E * M(u, v).row(1))

    return f_u, f_v
```

To compute the compensatory term,
define `V` which is a SymPy constant `0` and run the code above.

(SymPy would not know how to take a derivative of Python's `0`.)

```python
V = S(0)
f = source_term(eta(U, V, 3), U, V)[0].subs(z, sigma * h)
```

Next (as a sanity check) I plot this compensatory term and the driving stress term.

The SIA is supposed to be a good approximation of the Stokes equations (and so the B-P equation) in areas of shallow deformational flow, so the compensatory term should be close to the term corresponding to the driving stress.

```python
ff = sp.lambdify([x, sigma], f.subs(h, H).subs(definitions).doit().subs(constants))

# Create a NumPy function evaluating the driving stress term
# from the B-P system (for comparison)
Tau_d = (rho_i * g * H.diff(x)).subs(definitions).subs(constants)
tau_d = sp.lambdify(x, Tau_d)
```

I avoid areas where SIA and B-P approximations differ by a lot ($x$ close to $0$ and $R_0$):

```python
r = constants[R_0]
N = 1001
xx = np.linspace(0.01 * r, 0.99*r, N)
```

The plot below uses $\sigma$ in $[0, 0.5]$. For $\sigma$ in $(0.5, 1]$ the difference is much larger.

```python
fig = figure(plot_width=750, plot_height=500,
             title="Driving stress vs. compensatory term in the bottom half of ice thickness")
for sig in np.linspace(0, 0.5, 11):
    fig.line(xx, ff(xx, sig))
fig.line(xx, tau_d(xx), line_color="red", legend_label="driving stress")
show(fig)
```

Same comparison, but looking at ratios:

```python
T = tau_d(xx)
fig = figure(plot_width=750, plot_height=500,
             title="Ratio of the compensatory term and the driving stress")
for sig in np.linspace(0, 0.5, 11):
    fig.line(xx, ff(xx, sig) / T)
show(fig)
```

To generate C code, I use SymPy's "common sub-expression elimination" (CSE).

The `.doit()` call below forces evaluation of derivatives.

```python
xs, F = sp.cse(f.subs(h, H).subs(definitions).subs(s, 1).doit())
```

This produces a number of intermediate expressions (`xs`) and the list of expressions equivalent to the one supplied (`F`).

Here the number of `xs` is quite large. We could reduce it by being clever about the form of the expression passed to `sp.cse` (hard-wiring constants would help, for example), but it does not seem to be worthwhile.

```python
xs
```

$\displaystyle \left[ \left( x_{0}, \  \frac{1}{R_{0}^{\frac{4}{3}}}\right), \  \left( x_{1}, \  x^{\frac{4}{3}}\right), \  \left( x_{2}, \  - x_{0} x_{1} + 1\right), \  \left( x_{3}, \  H_{0} x_{2}^{\frac{3}{7}}\right), \  \left( x_{4}, \  - \sigma x_{3} + x_{3}\right), \  \left( x_{5}, \  x_{4}^{6}\right), \  \left( x_{6}, \  H_{0}^{6}\right), \  \left( x_{7}, \  \frac{1}{R_{0}^{8}}\right), \  \left( x_{8}, \  \frac{1}{x_{2}^{\frac{24}{7}}}\right), \  \left( x_{9}, \  \frac{g^{6} \rho_{i}^{6}}{B^{6}}\right), \  \left( x_{10}, \  x^{2} x_{6} x_{7} x_{8} x_{9}\right), \  \left( x_{11}, \  H_{0}^{4}\right), \  \left( x_{12}, \  x_{0} x_{11} x_{2}^{\frac{5}{7}}\right), \  \left( x_{13}, \  \sqrt[3]{x}\right), \  \left( x_{14}, \  \frac{16 x_{13}}{7}\right), \  \left( x_{15}, \  x_{4}^{3}\right), \  \left( x_{16}, \  \frac{H_{0} x_{0} x_{15}}{x_{2}^{\frac{4}{7}}}\right), \  \left( x_{17}, \  - x_{12} x_{14} + x_{14} x_{16}\right), \  \left( x_{18}, \  \frac{1}{R_{0}^{4}}\right), \  \left( x_{19}, \  x x_{18}\right), \  \left( x_{20}, \  H_{0}^{3}\right), \  \left( x_{21}, \  x_{2}^{\frac{12}{7}}\right), \  \left( x_{22}, \  \frac{1}{x_{21}}\right), \  \left( x_{23}, \  g^{3}\right), \  \left( x_{24}, \  \rho_{i}^{3}\right), \  \left( x_{25}, \  \frac{x_{23} x_{24}}{B^{3}}\right), \  \left( x_{26}, \  x_{20} x_{22} x_{25}\right), \  \left( x_{27}, \  x_{19} x_{26}\right), \  \left( x_{28}, \  x_{17} x_{27}\right), \  \left( x_{29}, \  x_{26} \left(x_{11} x_{21} - x_{4}^{4}\right)\right), \  \left( x_{30}, \  x_{18} x_{29}\right), \  \left( x_{31}, \  x^{\frac{2}{3}}\right), \  \left( x_{32}, \  \frac{1}{x_{2}}\right), \  \left( x_{33}, \  16 x_{0} x_{31} x_{32} + \frac{7}{x_{31}}\right), \  \left( x_{34}, \  x_{31} x_{33}\right), \  \left( x_{35}, \  x_{30} x_{34}\right), \  \left( x_{36}, \  \frac{32 x_{28}}{343} + \frac{32 x_{35}}{2401}\right), \  \left( x_{37}, \  \frac{4096 x_{10} x_{5}}{117649} + x_{36}^{2}\right), \  \left( x_{38}, \  \frac{1}{\sqrt[3]{x_{37}}}\right), \  \left( x_{39}, \  x_{4}^{2}\right), \  \left( x_{40}, \  \frac{x_{19} x_{20} x_{22} x_{23} x_{24}}{B^{2}}\right), \  \left( x_{41}, \  \frac{1}{x_{37}^{\frac{4}{3}}}\right), \  \left( x_{42}, \  x_{4}^{5}\right), \  \left( x_{43}, \  \frac{x_{36}}{3}\right), \  \left( x_{44}, \  x_{13} x_{30} x_{33}^{2}\right), \  \left( x_{45}, \  x^{\frac{5}{3}}\right), \  \left( x_{46}, \  \frac{1}{R_{0}^{\frac{8}{3}}}\right), \  \left( x_{47}, \  x_{31} x_{46}\right), \  \left( x_{48}, \  x_{29} x_{47} \left(- \frac{49 x_{0}}{x_{45}} + \frac{352 x_{19}}{x_{2}^{2}} + \frac{168 x_{32} x_{46}}{x_{13}}\right)\right), \  \left( x_{49}, \  x_{17} x_{18} x_{26} x_{34}\right), \  \left( x_{50}, \  \frac{192 x_{47}}{49}\right), \  \left( x_{51}, \  \frac{16 x_{33}}{147}\right), \  \left( x_{52}, \  x_{27} \left(- \frac{H_{0}^{2} x_{39} x_{50}}{x_{2}^{\frac{8}{7}}} + \frac{x_{11} x_{50}}{x_{2}^{\frac{2}{7}}} - x_{12} x_{51} + x_{16} x_{51}\right)\right), \  \left( x_{53}, \  \frac{B}{2}\right)\right]$

The final expression looks pretty nasty, but it is not for human consumption, anyway.

```python
F[0]
```

$\displaystyle \frac{64 x_{15} x_{40} x_{41} \left(\frac{8192 x_{10} x_{42}}{117649} - x_{43} \left(\frac{256 x_{15} x_{18} x_{26} x_{34}}{2401} - \frac{3072 x_{1} x_{11} x_{25} x_{39}}{2401 R_{0}^{\frac{16}{3}} x_{2}^{\frac{16}{7}}}\right)\right)}{343} - \frac{192 x_{38} x_{39} x_{40}}{343} + x_{38} x_{53} \left(\frac{256 x_{44}}{50421} + \frac{256 x_{48}}{50421} + \frac{256 x_{49}}{2401} + \frac{128 x_{52}}{343}\right) + x_{41} x_{53} \left(\frac{128 x_{28}}{343} + \frac{128 x_{35}}{2401}\right) \left(\frac{32768 H_{0}^{7} x^{\frac{7}{3}} x_{42} x_{9}}{823543 R_{0}^{\frac{28}{3}} x_{2}^{4}} - \frac{8192 x_{33} x_{45} x_{5} x_{6} x_{7} x_{8} x_{9}}{2470629} - x_{43} \left(\frac{128 x_{44}}{50421} + \frac{128 x_{48}}{50421} + \frac{128 x_{49}}{2401} + \frac{64 x_{52}}{343}\right)\right)$

Now we're ready to generate the C code evaluating the compensatory term:

```python
arguments = [x, sigma, H_0, R_0, rho_i, g, B]
args = ", ".join(["double " + str(variable) for variable in arguments])

print("double source_term({}) {{".format(args))
for v, expr in xs:
    print("  double " + sp.ccode(expr, assign_to=v))
print("  return {};".format(sp.ccode(F[0])))
print("}")
```

    double source_term(double x, double sigma, double H_0, double R_0, double rho_i, double g, double B) {
      double x0 = pow(R_0, -4.0/3.0);
      double x1 = pow(x, 4.0/3.0);
      double x2 = -x0*x1 + 1;
      double x3 = H_0*pow(x2, 3.0/7.0);
      double x4 = -sigma*x3 + x3;
      double x5 = pow(x4, 6);
      double x6 = pow(H_0, 6);
      double x7 = pow(R_0, -8);
      double x8 = pow(x2, -24.0/7.0);
      double x9 = pow(g, 6)*pow(rho_i, 6)/pow(B, 6);
      double x10 = pow(x, 2)*x6*x7*x8*x9;
      double x11 = pow(H_0, 4);
      double x12 = x0*x11*pow(x2, 5.0/7.0);
      double x13 = cbrt(x);
      double x14 = (16.0/7.0)*x13;
      double x15 = pow(x4, 3);
      double x16 = H_0*x0*x15/pow(x2, 4.0/7.0);
      double x17 = -x12*x14 + x14*x16;
      double x18 = pow(R_0, -4);
      double x19 = x*x18;
      double x20 = pow(H_0, 3);
      double x21 = pow(x2, 12.0/7.0);
      double x22 = 1.0/x21;
      double x23 = pow(g, 3);
      double x24 = pow(rho_i, 3);
      double x25 = x23*x24/pow(B, 3);
      double x26 = x20*x22*x25;
      double x27 = x19*x26;
      double x28 = x17*x27;
      double x29 = x26*(x11*x21 - pow(x4, 4));
      double x30 = x18*x29;
      double x31 = pow(x, 2.0/3.0);
      double x32 = 1.0/x2;
      double x33 = 16*x0*x31*x32 + 7/x31;
      double x34 = x31*x33;
      double x35 = x30*x34;
      double x36 = (32.0/343.0)*x28 + (32.0/2401.0)*x35;
      double x37 = (4096.0/117649.0)*x10*x5 + pow(x36, 2);
      double x38 = pow(x37, -1.0/3.0);
      double x39 = pow(x4, 2);
      double x40 = x19*x20*x22*x23*x24/pow(B, 2);
      double x41 = pow(x37, -4.0/3.0);
      double x42 = pow(x4, 5);
      double x43 = (1.0/3.0)*x36;
      double x44 = x13*x30*pow(x33, 2);
      double x45 = pow(x, 5.0/3.0);
      double x46 = pow(R_0, -8.0/3.0);
      double x47 = x31*x46;
      double x48 = x29*x47*(-49*x0/x45 + 352*x19/pow(x2, 2) + 168*x32*x46/x13);
      double x49 = x17*x18*x26*x34;
      double x50 = (192.0/49.0)*x47;
      double x51 = (16.0/147.0)*x33;
      double x52 = x27*(-pow(H_0, 2)*x39*x50/pow(x2, 8.0/7.0) + x11*x50/pow(x2, 2.0/7.0) - x12*x51 + x16*x51);
      double x53 = (1.0/2.0)*B;
      return (64.0/343.0)*x15*x40*x41*((8192.0/117649.0)*x10*x42 - x43*((256.0/2401.0)*x15*x18*x26*x34 - 3072.0/2401.0*x1*x11*x25*x39/(pow(R_0, 16.0/3.0)*pow(x2, 16.0/7.0)))) - 192.0/343.0*x38*x39*x40 + x38*x53*((256.0/50421.0)*x44 + (256.0/50421.0)*x48 + (256.0/2401.0)*x49 + (128.0/343.0)*x52) + x41*x53*((128.0/343.0)*x28 + (128.0/2401.0)*x35)*((32768.0/823543.0)*pow(H_0, 7)*pow(x, 7.0/3.0)*x42*x9/(pow(R_0, 28.0/3.0)*pow(x2, 4)) - 8192.0/2470629.0*x33*x45*x5*x6*x7*x8*x9 - x43*((128.0/50421.0)*x44 + (128.0/50421.0)*x48 + (128.0/2401.0)*x49 + (64.0/343.0)*x52));
    }

```python

```


# Noisy GP Experiments

```python

```

```python
import numpy as np
import numba
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from sklearn.utils import check_random_state, check_array, check_X_y
from sklearn.model_selection import train_test_split
from scipy.spatial.distance import pdist, cdist, squareform
from sklearn.metrics.pairwise import check_pairwise_arrays, euclidean_distances
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import _check_length_scale, WhiteKernel, RBF, ConstantKernel as C
from scipy import interpolate
from sklearn.metrics import mean_absolute_error, mean_squared_error
import warnings
mpl.rcParams['savefig.pad_inches'] = 0

%matplotlib inline
%load_ext autoreload
%autoreload 2
```

    /home/emmanuel/.conda/envs/sci_py36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
      return f(*args, **kwds)
    /home/emmanuel/.conda/envs/sci_py36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
      return f(*args, **kwds)
    /home/emmanuel/.conda/envs/sci_py36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
      return f(*args, **kwds)
    /home/emmanuel/.conda/envs/sci_py36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
      return f(*args, **kwds)

## 1D Toy Example

```python
figure_location = '/home/emmanuel/projects/2018_igarss/figures/noisy_gp/1d_example/'
figure_location = '/Users/eman/Documents/code_projects/gaussian_processes/pkg_sgpuppy/figures/'
figure_location = '/home/emmanuel/projects/gaussian_processes/pkg_sgpuppy/figures/'
```

```python
weights = {}
predictions = {}
variance = {}
mae = {}
mse = {}
rmse = {}
```

### Sample Data

```python
seed = 123
rng = np.random.RandomState(seed=seed)

# sample data parameters
n_train, n_test, n_trial = 60, 100, 100
sigma_y = 0.05
x_cov = 0.3
y_scale = .5
x_min, x_max = -10, 10

# real function
f = lambda x: np.sin(1.0 * np.pi / 1.6 * np.cos(5 + y_scale * x))
# f = lambda x: np.sinc(x)
# f = lambda x: np.sin(2. * x) + np.exp(0.2 * x)

# Training add x, y = f(x)
x = np.linspace(x_min, x_max, n_train + n_test + n_trial)

x, xs, = train_test_split(x, train_size=n_train, random_state=seed)

# add noise
y = f(x)
x_train = x + x_cov * rng.randn(n_train)
y_train = f(x) + sigma_y * rng.randn(n_train)

x_train, y_train = x_train[:, np.newaxis], y_train[:, np.newaxis]

# -----------------
# Testing Data
# -----------------
xs, xt = train_test_split(xs, train_size=n_test, random_state=seed)
xt = np.sort(xt)

ys = f(xs)

# Add noise
x_test = xs + x_cov * rng.randn(n_test)
y_test = ys

x_test, y_test = x_test[:, np.newaxis], y_test[:, np.newaxis]

# -------------------
# Plot Points
# -------------------
x_plot = np.linspace(x_min, x_max, n_test)[:, None]
y_plot = f(x_plot)
```

    /home/emmanuel/.conda/envs/sci_py36/lib/python3.6/site-packages/sklearn/model_selection/_split.py:2026: FutureWarning: From version 0.21, test_size will always complement train_size unless both are specified.
      FutureWarning)

```python
print(x.shape, y.shape)
print(x_train.shape, y_train.shape)
print(x_test.shape, x_test.shape)
```

    (60,) (60,)
    (60, 1) (60, 1)
    (100, 1) (100, 1)

```python
# plot toy data
fig, ax = plt.subplots(figsize=(10, 7))

ax.plot(x_plot, y_plot, linewidth=5, color='k', label='Real Function')
ax.scatter(x_train, y_train, color='r', s=100, label='Training Data')
ax.scatter(x_test, y_test, color='g', s=100, label='Testing Data')

# ax.set_title('Training and Testing Data', fontsize=20)
ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()

save_name = 'training_data.png'

fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)
```

## Naive GP Implementation (to Find Suitable Hyperparameters)

```python
def fit_gp(x_train, y_train, kernel='ard', scale=None,
           length_scale_bounds = (0.001, 100),
           noise_level_bounds = (1e-4, 10),
           n_restarts=3):

    warnings.simplefilter('ignore')
    x_train, y_train = check_X_y(x_train, y_train)
    warnings.simplefilter('default')
    n_train, d_dims = x_train.shape

    if kernel in ['ard', 'ARD']:
        length_scale_init = np.ones(shape=(d_dims))
    elif kernel in ['rbf', 'RBF']:
        length_scale_init = 1.0
    else:
        raise ValueError('Unrecognized kernel function...')

    noise_level_init = 1.0

    gp_kernel = C() * RBF(length_scale=length_scale_init,
                    length_scale_bounds=length_scale_bounds) + \
                WhiteKernel(noise_level=noise_level_init,
                            noise_level_bounds=noise_level_bounds)

    gpr_model = GaussianProcessRegressor(kernel=gp_kernel, random_state=123,
                                         n_restarts_optimizer=n_restarts)

    # Fit the GP Model
    gpr_model.fit(x_train, y_train)

    # the parameters

    constant = gpr_model.kernel_.get_params()['k1__k1__constant_value']
    length_scale = gpr_model.kernel_.get_params()['k1__k2__length_scale']
    sigma = gpr_model.kernel_.get_params()['k2__noise_level']

    return length_scale, sigma, constant
```

```python
length_scale, sigma_y, constant = fit_gp(x_train, y_train, n_restarts=0)
print('Length Scale: {:.3f}'.format(length_scale))
print('Sigma y: {:.3f}'.format(sigma_y))
print('Likelihood Variance: {:.3f}'.format(constant))
```

    Length Scale: 1.854
    Sigma y: 0.013
    Likelihood Variance: 0.656

## Gaussian Covariance Function (ARD/RBF Kernel)

\begin{equation}
    K(x, y) = \nu \cdot \text{exp} \left[ -\frac{1}{2} (x - y)^{\top} \cdot W^{-1} \cdot (x - y) \right]
\end{equation}

* $W^{-1}= \text{diag}\left[ w_1, w_2, \ldots, w_{D} \right]$
* $w_d = \frac{1}{\lambda_d^2}$
* $\nu$ is the signal variance parameter

### GP/KRR Manually

```python
from GaussianProcess import GaussianProcess
from Covariance import GaussianCovariance

%load_ext autoreload
%autoreload 2
```

    The autoreload extension is already loaded. To reload it, use:
      %reload_ext autoreload

```python
w = np.array([length_scale])
v = constant
vt = sigma_y
Sigma = np.array([0.8])
if np.ndim(Sigma) == 1:
    Sigma = Sigma[:, np.newaxis]

# Preparing the parameter vector
theta = np.zeros(2+len(w))
theta[0] = np.log(v)  # We actually use the log of the parameters as it is easier to optimize (no > 0 constraint etc.)
theta[1] = np.log(vt)
theta[2:2+len(w)] = np.log(w)

# Simulating simulation data by drawing data from a random Gaussian process
t = GaussianProcess.get_realisation(x_train, GaussianCovariance(),theta)

# The regression step is pretty easy:
# Input data x (list of input vectors)
# Corresponding simulation output t (just a list of floats of the same length as x)
# Covariance function of your choice (only GaussianCovariance can be used for uncertainty propagation at the moment)
gp_est = GaussianProcess(x_train, y_train,GaussianCovariance());
```

    [-0.44196361 -1.82825797 -4.62977644]
    l_bfgs_b 	 0.0917501449584961 	 [[-14.67484715]] 	 [-0.37193111 -4.30782621 -1.25336646]
    [-0.37193111 -4.30782621 -1.25336646]

```python

```

```python
%%time
# Initialize the GP and Fit the model
gp_model = GaussianProcess(x_train, y_train, GaussianCovariance());

# Predict
predictions['simple'], var = gp_model.estimate_many(x_test);

mae['simple'] = mean_absolute_error(predictions['simple'], y_test)
mse['simple'] = mean_squared_error(predictions['simple'], y_test)
rmse['simple'] = np.mean(np.sqrt(np.mean(predictions['simple'] - y_test, axis=1)**2))

print('\nMAE Score: {:.5f}'.format(mae['simple']))
print('MSE Score: {:.5f}'.format(mse['simple']))
print('RMSE Score: {:.5f}\n'.format(rmse['simple']))
```

    [-0.44196361 -1.82825797 -4.62977644]
    l_bfgs_b 	 0.09655451774597168 	 [[-14.67484715]] 	 [-0.37193111 -4.30782621 -1.25336646]
    [-0.37193111 -4.30782621 -1.25336646]

    MAE Score: 0.11215
    MSE Score: 0.02983
    RMSE Score: 0.11215

    CPU times: user 478 ms, sys: 2.84 s, total: 3.32 s
    Wall time: 106 ms

#### Plot Simple GP Results

```python
# Get Figure for x_plot
predictions['simple'], variance['simple'] = gp_model.estimate_many(x_plot)

# Plot Figure

fig, ax = plt.subplots(figsize=(10, 7))

ax.plot(x_plot, predictions['simple'], linewidth=5, color='k', label='Predictions (GP)')
ax.fill_between(x_plot.squeeze(),
                predictions['simple'].squeeze() - 2*np.sqrt(variance['simple']).squeeze(),
                predictions['simple'].squeeze() + 2*np.sqrt(variance['simple']).squeeze(),
                color = 'red',
                alpha=0.5, label='Standard Deviation')
ax.scatter(x_train, y_train, s=100, color='r', label='Training Data')

ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.patch.set_visible(False)
plt.show()

save_name = 'gp_simple.png'

fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)
```

## Uncertainty Propagation (Approximate)

```python
from UncertaintyPropagation import UncertaintyPropagationApprox
```

```python
%%time

# Initialize GP
gp_approx = UncertaintyPropagationApprox(gp_model)

# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_test)
predictions['approx'] = np.zeros(n_samples)
var = np.zeros(n_samples)
print(x_test.shape)
for i in range(n_samples):
    predictions['approx'][i], var[i] = gp_approx.propagate_GA(x_test[i],Sigma)

mae['approx'] = mean_absolute_error(predictions['approx'], y_test)
mse['approx'] = mean_squared_error(predictions['approx'], y_test)
rmse['approx'] = np.mean(np.sqrt(np.mean(predictions['approx'] - y_test, axis=1)**2))

print('\nMAE Score: {:.5f}'.format(mae['approx']))
print('MSE Score: {:.5f}'.format(mse['approx']))
print('RMSE Score: {:.5f}\n'.format(rmse['approx']))

print(var.min(), var.max())
```

    (100, 1)

    MAE Score: 0.18766
    MSE Score: 0.05959
    RMSE Score: 0.80787

    0.015284983210722691 0.6285197557966403
    CPU times: user 4.3 s, sys: 60.1 ms, total: 4.36 s
    Wall time: 4.35 s

##### Plot Derivative Term Results

```python
# Get Figure for x_plot
# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_plot)
predictions['approx'] = np.zeros(n_samples)
variance['approx'] = np.zeros(n_samples)

for i in range(n_samples):

    predictions['approx'][i], variance['approx'][i] = gp_approx.propagate_GA(x_plot[i],Sigma)

# Plot Figure

fig, ax = plt.subplots(figsize=(10, 7))

ax.plot(x_plot, predictions['approx'], linewidth=5, color='k', label='Predictions (GP + Error)')
ax.scatter(x_train, y_train, s=100, color='r', label='Training Data')
ax.fill_between(x_plot.squeeze(),
                predictions['approx'].squeeze() - 2*np.sqrt(variance['approx']).squeeze(),
                predictions['approx'].squeeze() + 2*np.sqrt(variance['approx']).squeeze(),
                color = 'red',
                alpha=0.5, label='Standard Deviation')

ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.patch.set_visible(False)
plt.show()

save_name = 'gp_approx.png'

fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)
```

## Exact Uncertainty

```python
from UncertaintyPropagation import UncertaintyPropagationExact
```

```python
%%time
# Initialize GP
gp_exact = UncertaintyPropagationExact(gp_model)

# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_test)
predictions['exact'] = np.zeros(n_samples)
var = np.zeros(n_samples)

for i in range(n_samples):

    predictions['exact'][i], var[i] = gp_exact.propagate_GA(x_test[i],Sigma)

mae['exact'] = mean_absolute_error(predictions['exact'], y_test)
mse['exact'] = mean_squared_error(predictions['exact'], y_test)
rmse['exact'] = np.mean(np.sqrt(np.mean(predictions['exact'] - y_test, axis=1)**2))

print('\nMAE Score: {:.5f}'.format(mae['exact']))
print('MSE Score: {:.5f}'.format(mse['exact']))
print('RMSE Score: {:.5f}\n'.format(rmse['exact']))
print(var.min(), var.max())
```

    MAE Score: 0.16662
    MSE Score: 0.04913
    RMSE Score: 0.80781

    0.019294667862848225 0.36629936589818823
    CPU times: user 4.82 s, sys: 119 ms, total: 4.94 s
    Wall time: 4.84 s

```python
# Get Figure for x_plot
# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_plot)
predictions['exact'] = np.zeros(n_samples)
variance['exact'] = np.zeros(n_samples)

for i in range(n_samples):

    predictions['exact'][i], variance['exact'][i] = gp_exact.propagate_GA(x_plot[i],Sigma)

# Plot Figure

fig, ax = plt.subplots(figsize=(10, 7))

ax.plot(x_plot, predictions['exact'], linewidth=5, color='k', label='Predictions (GP + Error)')
ax.scatter(x_train, y_train, s=100, color='r', label='Training Data')
ax.fill_between(x_plot.squeeze(),
                predictions['exact'].squeeze() - 2*np.sqrt(variance['exact']).squeeze(),
                predictions['exact'].squeeze() + 2*np.sqrt(variance['exact']).squeeze(),
                color = 'red',
                alpha=0.5, label='Standard Deviation')

ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.patch.set_visible(False)
plt.show()

save_name = 'gp_exact.png'

fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)
```

## Exact Numerical Uncertainty MCMC

```python
from UncertaintyPropagation import UncertaintyPropagationMC
```

```python
%%time
# Initialize GP
gp_stat = UncertaintyPropagationMC(gp_model)

# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_test)
predictions['stat'] = np.zeros(n_samples)
var = np.zeros(n_samples)

for i in range(n_samples):

    predictions['stat'][i], var[i] = gp_stat.propagate_GA(x_test[i],Sigma)

mae['stat'] = mean_absolute_error(predictions['stat'], y_test)
mse['stat'] = mean_squared_error(predictions['stat'], y_test)
rmse['stat'] = np.mean(np.sqrt(np.mean(predictions['stat'] - y_test, axis=1)**2))

print('\nMAE Score: {:.5f}'.format(mae['stat']))
print('MSE Score: {:.5f}'.format(mse['stat']))
print('RMSE Score: {:.5f}\n'.format(rmse['stat']))

print(var.min(), var.max())
```

    MAE Score: 0.16529
    MSE Score: 0.04861
    RMSE Score: 0.80781

    0.013551970045903805 0.37502451279481397
    CPU times: user 32.9 s, sys: 342 ms, total: 33.3 s
    Wall time: 33.3 s

```python
# Get Figure for x_plot
# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_plot)
predictions['stat'] = np.zeros(n_samples)
variance['stat'] = np.zeros(n_samples)

for i in range(n_samples):

    predictions['stat'][i], variance['stat'][i] = gp_stat.propagate_GA(x_plot[i],Sigma)

# Plot Figure

fig, ax = plt.subplots(figsize=(10, 7))

ax.plot(x_plot, predictions['stat'], linewidth=5, color='k', label='Predictions (GP + Error)')
ax.scatter(x_train, y_train, s=100, color='r', label='Training Data')
ax.fill_between(x_plot.squeeze(),
                predictions['stat'].squeeze() - 2*np.sqrt(variance['stat']).squeeze(),
                predictions['stat'].squeeze() + 2*np.sqrt(variance['stat']).squeeze(),
                color = 'red',
                alpha=0.5, label='Standard Deviation')

ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.patch.set_visible(False)
plt.show()

save_name = 'gp_stat.png'

fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)
```

## Numerical

```python
from UncertaintyPropagation import UncertaintyPropagationNumericalHG
```

```python
%%time
# Initialize GP
gp_numerical = UncertaintyPropagationNumericalHG(gp_model)

# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_test)
predictions['numerical'] = np.zeros(n_samples)
var = np.zeros(n_samples)

for i in range(n_samples):

    predictions['numerical'][i], var[i] = gp_numerical.propagate_GA(x_test[i],Sigma)

mae['numerical'] = mean_absolute_error(predictions['numerical'], y_test)
mse['numerical'] = mean_squared_error(predictions['numerical'], y_test)
rmse['numerical'] = np.mean(np.sqrt(np.mean(predictions['numerical'] - y_test, axis=1)**2))

print('\nMAE Score: {:.5f}'.format(mae['numerical']))
print('MSE Score: {:.5f}'.format(mse['numerical']))
print('RMSE Score: {:.5f}\n'.format(rmse['numerical']))
print(var.min(), var.max())
```

    MAE Score: 0.16682
    MSE Score: 0.04925
    RMSE Score: 0.80781

    0.01748124606422652 0.37874630878991117
    CPU times: user 385 ms, sys: 1.66 ms, total: 387 ms
    Wall time: 384 ms

```python
# Get Figure for x_plot
# print(x_new.shape, mean.shape, Sigma.shape)
n_samples = len(x_plot)
predictions['numerical'] = np.zeros(n_samples)
variance['numerical'] = np.zeros(n_samples)

for i in range(n_samples):

    predictions['numerical'][i], variance['numerical'][i] = gp_numerical.propagate_GA(x_plot[i],Sigma)

# Plot Figure

fig, ax = plt.subplots(figsize=(10, 7))

ax.plot(x_plot, predictions['numerical'], linewidth=5, color='k', label='Predictions (GP + Error)')
ax.scatter(x_train, y_train, s=100, color='r', label='Training Data')
ax.fill_between(x_plot.squeeze(),
                predictions['numerical'].squeeze() - 2*np.sqrt(variance['numerical']).squeeze(),
                predictions['numerical'].squeeze() + 2*np.sqrt(variance['numerical']).squeeze(),
                color = 'red',
                alpha=0.5, label='Standard Deviation')

ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
ax.patch.set_visible(False)
plt.show()

save_name = 'gp_numerical.png'

fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)
```

## Empirical Variance Comparison

### Calculate the Empirical Variance (Get Scores)

```python
%%time

from sklearn.metrics import mean_absolute_error, mean_squared_error
rng = np.random.RandomState(None)
n_trials = 20

mae_score = {
    'simple': list(),
    'approx': list(),
    'exact': list(),
    'stat': list(),
    'numerical': list()
}

mse_score = {
    'simple': list(),
    'approx': list(),
    'exact': list(),
    'stat': list(),
    'numerical': list()
}

abs_error = {
    'simple': list(),
    'approx': list(),
    'exact': list(),
    'stat': list(),
    'numerical': list()
}
squared_error = {
    'simple': list(),
    'approx': list(),
    'exact': list(),
    'stat': list(),
    'numerical': list()
}

# testing set (noise-less)
ys = f(xt)
y_test = ys.squeeze()
y_test = np.atleast_2d(y_test).T
xt
# fig, ax = plt.subplots()

for itrial in range(n_trials):

    # Generate x samples with random error
    x_test = xt + 0.3 * rng.randn(n_trial)
    x_test = x_test[:, np.newaxis]
    n_samples = len(x_test)
#     ax.scatter(x_test, y_test)

    # -------------------
    # Model I - Simple GP
    # -------------------
    mean, _ = gp_model.estimate_many(x_test)

    abs_error['simple'].append(np.abs(mean.squeeze() - y_test.squeeze()))
    squared_error['simple'].append((mean.squeeze() - y_test.squeeze())**2)
    mae_score['simple'].append(mean_absolute_error(mean.squeeze(), y_test.squeeze()))
    mse_score['simple'].append(mean_squared_error(mean.squeeze(), y_test.squeeze()))

    # -------------------
    # Model II - Approx
    # -------------------
    mean = np.zeros(n_samples)
    for i in range(n_samples):

        mean[i], _ = gp_approx.propagate_GA(x_test[i],Sigma)

    abs_error['approx'].append(np.abs(mean.squeeze() - y_test.squeeze()))
    squared_error['approx'].append((mean.squeeze() - y_test.squeeze())**2)
    mae_score['approx'].append(mean_absolute_error(mean.squeeze(), y_test.squeeze()))
    mse_score['approx'].append(mean_squared_error(mean.squeeze(), y_test.squeeze()))

    # -------------------
    # Model III - Exact
    # -------------------
    mean = np.zeros(n_samples)
    for i in range(n_samples):

        mean[i], _ = gp_exact.propagate_GA(x_test[i],Sigma)

    abs_error['exact'].append(np.abs(mean.squeeze() - y_test.squeeze()))
    squared_error['exact'].append((mean.squeeze() - y_test.squeeze())**2)
    mae_score['exact'].append(mean_absolute_error(mean.squeeze(), y_test.squeeze()))
    mse_score['exact'].append(mean_squared_error(mean.squeeze(), y_test.squeeze()))

    # -------------------
    # Model IV - Numerical
    # -------------------
    mean = np.zeros(n_samples)
    for i in range(n_samples):

        mean[i], _ = gp_stat.propagate_GA(x_test[i],Sigma)

    abs_error['stat'].append(np.abs(mean.squeeze() - y_test.squeeze()))
    squared_error['stat'].append((mean.squeeze() - y_test.squeeze())**2)
    mae_score['stat'].append(mean_absolute_error(mean.squeeze(), y_test.squeeze()))
    mse_score['stat'].append(mean_squared_error(mean.squeeze(), y_test.squeeze()))

    # -------------------
    # Model IV - Numerical
    # -------------------
    mean = np.zeros(n_samples)
    for i in range(n_samples):

        mean[i], _ = gp_numerical.propagate_GA(x_test[i],Sigma)

    abs_error['numerical'].append(np.abs(mean.squeeze() - y_test.squeeze()))
    squared_error['numerical'].append((mean.squeeze() - y_test.squeeze())**2)
    mae_score['numerical'].append(mean_absolute_error(mean.squeeze(), y_test.squeeze()))
    mse_score['numerical'].append(mean_squared_error(mean.squeeze(), y_test.squeeze()))

```

    CPU times: user 13min 44s, sys: 1.91 s, total: 13min 45s
    Wall time: 13min 44s

```python
abs_error['simple'] = np.mean(np.array(abs_error['simple']).squeeze(), axis=0)
squared_error['simple'] = np.mean(np.array(squared_error['simple']).squeeze(), axis=0)
mae_score['simple'] = np.mean(np.array(mae_score['simple']))
mse_score['simple'] = np.mean(np.array(mse_score['simple']))

abs_error['approx'] = np.mean(np.array(abs_error['approx']).squeeze(), axis=0)
squared_error['approx'] = np.mean(np.array(squared_error['approx']).squeeze(), axis=0)
mae_score['approx'] = np.mean(np.array(mae_score['approx']))
mse_score['approx'] = np.mean(np.array(mse_score['approx']))

abs_error['exact'] = np.mean(np.array(abs_error['exact']).squeeze(), axis=0)
squared_error['exact'] = np.mean(np.array(squared_error['exact']).squeeze(), axis=0)
mae_score['exact'] = np.mean(np.array(mae_score['exact']))
mse_score['exact'] = np.mean(np.array(mse_score['exact']))

abs_error['stat'] = np.mean(np.array(abs_error['stat']).squeeze(), axis=0)
squared_error['stat'] = np.mean(np.array(squared_error['stat']).squeeze(), axis=0)
mae_score['stat'] = np.mean(np.array(mae_score['stat']))
mse_score['stat'] = np.mean(np.array(mse_score['stat']))

abs_error['numerical'] = np.mean(np.array(abs_error['numerical']).squeeze(), axis=0)
squared_error['numerical'] = np.mean(np.array(squared_error['numerical']).squeeze(), axis=0)
mae_score['numerical'] = np.mean(np.array(mae_score['numerical']))
mse_score['numerical'] = np.mean(np.array(mse_score['numerical']))
```

```python
fig, ax = plt.subplots()

ax.scatter(x_train, y_train, label='training samples')
ax.plot(x_plot, f(x_plot), color='black', label='real function')
ax.legend()
plt.show()
# ax.scatter(xs, abs_error['simple'], color='green', label='Empirical Absolute Error (Points)')
```

### No Uncertainty

```python
xnew = np.linspace(xt.min(), xt.max(), 1000)

# Interpolation function for squared error
squared_error_line = interpolate.interp1d(xt, squared_error['simple'], kind='slinear')(xnew)

print('MSE: {:.5f}'.format(mse_score['simple']))
print('MAE: {:.5f}'.format(mae_score['simple']))

pred, var = gp_model.estimate_many(xt[:, np.newaxis])

# pred, var = gp_simple.predict(xt[:, np.newaxis], return_variance=True)

fig, ax = plt.subplots(nrows=1, figsize=(10, 7))

ax.scatter(xt, squared_error['simple'])
ax.plot(xnew, squared_error_line, linewidth=3, color='r', label='Empirical Squared Error')
ax.plot(xt, var-0.013, linewidth=4, color='k', label='GP: Variance')

# ax.set_title('Squared Error, Variance')
ax.grid(True)
ax.legend(fontsize=14)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()

save_name = 'exp_empirical_simple_var.png'
fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)

```

## Approximate Uncertainty

```python
xnew = np.linspace(xt.min(), xt.max(), 1000)

abs_error_line = interpolate.interp1d(xt, abs_error['approx'], kind='quadratic')(xnew)

# Interpolation function for squared error
squared_error_line = interpolate.interp1d(xt, squared_error['approx'], kind='quadratic')(xnew)

n_samples = len(xt)
pred = np.zeros(n_samples)
var = np.zeros(n_samples)
xt_ = xt[:, np.newaxis]

for i in range(n_samples):
    pred[i], var[i] = gp_approx.propagate_GA(xt_[i], Sigma)
# pred, var = gp_derivative_full.predict(xt[:, np.newaxis], return_variance=True)

print('MSE: {:.5f}'.format(mse_score['approx']))
print('MAE: {:.5f}'.format(mae_score['approx']))

fig, ax = plt.subplots(nrows=1, figsize=(10, 7))

ax.plot(xnew, squared_error_line, linewidth=3, color='r', label='Empirical Squared Error')
ax.plot(xt, var-0.013, linewidth=4, color='k', label='GP: Error Variance')

# ax.set_title('Squared Error, Variance')
ax.legend(fontsize=14)
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
ax.grid(True)
plt.show()

save_name = 'exp_empirical_approx_var.png'
fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)

```

### Exact Uncertainty

```python
xnew = np.linspace(xt.min(), xt.max(), 1000)

abs_error_line = interpolate.interp1d(xt, abs_error['exact'], kind='quadratic')(xnew)

# Interpolation function for squared error
squared_error_line = interpolate.interp1d(xt, squared_error['exact'], kind='quadratic')(xnew)

n_samples = len(xt)
pred = np.zeros(n_samples)
var = np.zeros(n_samples)
xt_ = xt[:, np.newaxis]

for i in range(n_samples):
    pred[i], var[i] = gp_exact.propagate_GA(xt_[i], Sigma)
# pred, var = gp_derivative_full.predict(xt[:, np.newaxis], return_variance=True)

print('MSE: {:.5f}'.format(mse_score['exact']))
print('MAE: {:.5f}'.format(mae_score['exact']))

fig, ax = plt.subplots(nrows=1, figsize=(10, 7))

ax.plot(xnew, squared_error_line, linewidth=3, color='r', label='Empirical Squared Error')
ax.plot(xt, var-0.013, linewidth=4, color='k', label='GP: Error Variance')

# ax.set_title('Squared Error, Variance')
ax.legend(fontsize=14)
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
ax.grid(True)
plt.show()

save_name = 'exp_empirical_exact_var.png'
fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)

```

## Numcerical Uncertainty (MC)

```python
xnew = np.linspace(xt.min(), xt.max(), 1000)

abs_error_line = interpolate.interp1d(xt, abs_error['stat'], kind='quadratic')(xnew)

# Interpolation function for squared error
squared_error_line = interpolate.interp1d(xt, squared_error['stat'], kind='quadratic')(xnew)

n_samples = len(xt)
pred = np.zeros(n_samples)
var = np.zeros(n_samples)
xt_ = xt[:, np.newaxis]

for i in range(n_samples):
    pred[i], var[i] = gp_stat.propagate_GA(xt_[i], Sigma)
# pred, var = gp_derivative_full.predict(xt[:, np.newaxis], return_variance=True)

print('MSE: {:.5f}'.format(mse_score['stat']))
print('MAE: {:.5f}'.format(mae_score['stat']))

fig, ax = plt.subplots(nrows=1, figsize=(10, 7))

ax.plot(xnew, squared_error_line, linewidth=3, color='r', label='Empirical Squared Error')
ax.plot(xt, var-0.013, linewidth=4, color='k', label='GP: Error Variance')

# ax.set_title('Squared Error, Variance')
ax.legend(fontsize=14)
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
ax.grid(True)
plt.show()

save_name = 'exp_empirical_stat_var.png'
fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)

```

### Numerical Uncertainty

```python
xnew = np.linspace(xt.min(), xt.max(), 1000)

abs_error_line = interpolate.interp1d(xt, abs_error['numerical'], kind='linear')(xnew)

# Interpolation function for squared error
squared_error_line = interpolate.interp1d(xt, squared_error['numerical'], kind='linear')(xnew)

n_samples = len(xt)
pred = np.zeros(n_samples)
var = np.zeros(n_samples)
xt_ = xt[:, np.newaxis]

for i in range(n_samples):
    pred[i], var[i] = gp_numerical.propagate_GA(xt_[i], Sigma)
# pred, var = gp_derivative_full.predict(xt[:, np.newaxis], return_variance=True)

print('MSE: {:.5f}'.format(mse_score['numerical']))
print('MAE: {:.5f}'.format(mae_score['numerical']))

fig, ax = plt.subplots(nrows=1, figsize=(10, 7))

ax.plot(xnew, squared_error_line, linewidth=3, color='r', label='Empirical Squared Error')
ax.plot(xt, var-0.013, linewidth=4, color='k', label='GP: Error Variance')

# ax.set_title('Squared Error, Variance')
ax.legend(fontsize=14)
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
ax.grid(True)
plt.show()

save_name = 'exp_empirical_numerical_var.png'
fig.savefig(figure_location + save_name, bbox_inhces='tight',
            dpi=100, transparent=True, frameon=None)

```

### Q Matrix Optimization

```python
xtrain = np.array([1, 5, 3])[:, np.newaxis]
xtest = np.array([1])[:, np.newaxis]
print(xtrain.shape, xtest.shape)
n_samples = xtrain.shape[0]
d_dimensions = xtrain.shape[1]
```

    (3, 1) (1, 1)

```python
xrow = xtrain[:, np.newaxis, :]
xrow = np.tile(xrow, [1, n_samples, d_dimensions])
print(xrow)
print(xrow.shape)
```

    [[[1]
      [1]
      [1]]

     [[5]
      [5]
      [5]]

     [[3]
      [3]
      [3]]]
    (3, 3, 1)

```python
def zterm_matrix(xtrain):
    n_samples, d_dimensions = xtrain.shape

    xrow = xtrain[:, np.newaxis, :]
    xrow = np.tile(xrow, [1, n_samples, d_dimensions])
    zterm = 0.5 * (xrow + np.transpose(xrow, axes=(1,0, 2)))
    return zterm
```

```python
xcol = xrow.copy() #xtrain[:, np.newaxis, :]
xcol = np.transpose(xcol, axes=(1,0, 2))
print(xcol)
print(xcol.shape)

```

    [[[1]
      [5]
      [3]]

     [[1]
      [5]
      [3]]

     [[1]
      [5]
      [3]]]
    (3, 3, 1)

```python
zterm = 0.5 * (xrow + xcol)
zterm = zterm_matrix(xtrain)
print(zterm == zterm2)
print(zterm.shape)
```

```python
zterm = zterm_matrix(xtrain)
zterm = zterm - xtest
print(zterm.shape, zterm.T.shape)
```

    (3, 3, 1) (1, 3, 3)

```python
diag_term = np.array([1.0])
print(zterm.shape, diag_term.shape)
exp_term = zterm.dot(diag_term).dot(zterm.T)
print(exp_term.shape)
```

    (3, 3, 1) (1,)
    (3, 1, 3)

```python

```