# Neuro-Fuzzy Classification of MNIST
In this notebook a neuro-fuzzy classifier will be trained and evaluated on the MNIST dataset. No feature reductions techniques will be used, the intent is to provide a baseline performance to compare to other techniques.

```python
import gzip
import numpy as np

def load_data(filename, dims):
    with gzip.open(filename, "rb") as infile:
        # consume magic number
        infile.read(4)
        # consume dimensions data
        infile.read(4 * len(dims))

        return np.frombuffer(infile.read(np.prod(dims)), dtype=np.uint8).reshape(dims)

# training data
train_images = load_data("data/train-images-idx3-ubyte.gz", [60000, 28, 28])
train_labels = load_data("data/train-labels-idx1-ubyte.gz", [60000])

# testing data
test_images = load_data("data/t10k-images-idx3-ubyte.gz", [10000, 28, 28])
test_labels = load_data("data/t10k-labels-idx1-ubyte.gz", [10000])
```

The MNIST data is loaded into memory as NumPy arrays.

```python
import matplotlib.pyplot as plt

%matplotlib inline
fig, ax_array = plt.subplots(10, 20, figsize=(16, 8))
axes = ax_array.flatten()
for i, ax in enumerate(axes):
    ax.imshow(train_images[i,:,:], cmap="Greys", interpolation="none")

plt.setp(axes, xticks=[], yticks=[], frame_on=False)
plt.tight_layout(h_pad=0, w_pad=0)
```

Samples from the training images are displayed above to ensure the data was loaded correctly.

```python
import os
import pickle
import skfuzzy as skf

_cache_dir = "cache/params.pickle"
_ignore_cache = False

# compute sigma parameter
def compute_sigmas(data, memberships, centers):
    mask = np.any(memberships >= 1.0, axis=0)
    data = data[:,~mask]
    memberships = memberships[:,~mask]

    data = np.expand_dims(data, axis=0)
    memberships = np.expand_dims(memberships, axis=1)
    centers = np.expand_dims(centers, axis=2)

    return np.mean(np.sqrt(-np.square(data - centers) / (2 * np.log(memberships))), axis=2)

# generate the parameters for the fuzzy classifier
def gen_params(data, c, m):
    if not os.path.isfile(_cache_dir) or _ignore_cache:
        centers, memberships, u0, d, jm, p, fpc = skf.cmeans(
            data.T, 10, 1.1, 1e-8, 1000, seed=0)
        sigmas = compute_sigmas(data.T, memberships, centers)
        pickle.dump((centers, sigmas), open(_cache_dir, "wb"))

    else:
        centers, sigmas = pickle.load(open(_cache_dir, "rb"))

    return centers, sigmas

# initial parameters for use in model
init_mu, init_sigma = gen_params(train_images.reshape(-1, 784), 10, 1.1)

plt.figure(figsize=(16, 4))
plt.title("Initial Mu")
plt.boxplot(init_mu.reshape(-1), vert=False)

plt.figure(figsize=(16, 4))
plt.title("Initial Sigma")
plt.boxplot(init_sigma.reshape(-1), vert=False)
```

The initial values for mu and sigma are generated (or loaded from the disk) and boxplots are displayed above.

```python
def processed_data():
    train_x = train_images.astype(np.float) / 255
    train_y = np.zeros((60000,10))
    train_y[np.arange(60000), train_labels] = 1

    test_x = test_images.astype(np.float) / 255
    test_y = np.zeros((10000,10))
    test_y[np.arange(10000), test_labels] = 1

    return (train_x, train_y), (test_x, test_y)

(train_x, train_y), (test_x, test_y) = processed_data()
```

This function formats the training data by rescaling the images and creating one-hot vectors for the target data.

## Building the Network
The code that defines the network structure written below. A custom layer was created for the gaussian membership function. Additionally, the product t-norm is computed and normalized in special way to prevent numerical underflow.

The product t-norm and normalization layer.
\begin{align}
\ f_i & = \frac{1}{f_{max}}\prod_{j=1}^N m_{i,j} \\
\ f_i & = exp\Big({ln\Big(\frac{1}{f_{max}}\prod_{j=1}^N m_{i,j}\Big)}\Big) \\
\ f_i & = exp\Big({\sum_{j=1}^N ln(m_{i,j})} - ln(f_{max})\Big) \\
\end{align}

```python
import keras
import keras.layers as layers
import keras.models as models
from keras import backend as K

# custom layer for gauss membership function
class GaussMembership(layers.Layer):

    def __init__(self, num_rules, epsilon=1e-8, **kwargs):
        self.epsilon = epsilon
        self.num_rules = num_rules
        super(GaussMembership, self).__init__(**kwargs)

    def build(self, input_shape):
        self.mu = self.add_weight(
            name="mu",
            shape=(self.num_rules, input_shape[1]),
            initializer=keras.initializers.Zeros(),
            trainable=True)
        self.sigma = self.add_weight(
            name="sigma",
            shape=(self.num_rules, input_shape[1]),
            initializer=keras.initializers.Ones(),
            constraint=keras.constraints.NonNeg(),
            trainable=True)
        super(GaussMembership, self).build(input_shape)

    def call(self, x):
        x = K.expand_dims(x, axis=1)
        x = K.square((x - self.mu) / (self.sigma + self.epsilon))
        return K.exp(-0.5 * x)

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.num_rules, input_shape[1])

# create the model with the given parameters
def create_model(init_mu, init_sigma, num_rules=10):
    # define the models input
    inputs = layers.Input(shape=(28, 28,))
    reshaped = layers.Reshape((784,))(inputs)

    # apply the membership function
    membership = GaussMembership(
        num_rules, weights=[init_mu, init_sigma])(reshaped)

    def log_prod(x):
        x = K.sum(K.log(x + 1e-8), axis=2)
        x = x - K.max(x, axis=1, keepdims=True)
        return K.exp(x)

    fstrength = layers.Lambda(lambda x:
        log_prod(x))(membership)

    outputs = layers.Dense(10, activation="sigmoid")(fstrength)
    return models.Model(inputs=inputs, outputs=outputs)
```

    Using TensorFlow backend.

This code defines the model in keras.

```python
import tensorflow as tf

def plot_activations(model, inputs):
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for layer in model.layers:
            activation_val = sess.run(
                layer.output,
                feed_dict={model.input:inputs})

            plt.figure(figsize=(16, 4))
            plt.title(layer)
            plt.boxplot(activation_val.reshape(-1), vert=False)

def plot_gradients(model, inputs):
    gradient_fn = K.gradients(model.output, model.trainable_weights)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        gradients = sess.run(
            gradient_fn,
            feed_dict={model.input:inputs})

    for param, gradient in zip(model.trainable_weights, gradients):
        plt.figure(figsize=(16, 4))
        plt.title(param)
        plt.boxplot(gradient.reshape(-1), vert=False)
```

The functions above are written using tensorflow in order to view the intermediate activations and gradients in a model.

```python
fcm_model = create_model(init_mu, init_sigma)
fcm_model.compile(loss="binary_crossentropy", optimizer="sgd")

#plot_activations(fcm_model, train_x[:64])
```

```python
def plot_prod_layer(model, inputs):
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        membership_val = sess.run(
            model.layers[2].output,
            feed_dict={model.input:inputs})

    plt.figure(figsize=(16, 4))
    plt.title("Memberships")
    plt.boxplot(membership_val.reshape(-1), vert=False)

    logsum = np.sum(np.log(membership_val + 1e-8), axis=2)

    plt.figure(figsize=(16, 4))
    plt.title("Log-Sum")
    plt.boxplot(logsum.reshape(-1), vert=False)

    normalized = logsum - np.max(logsum, axis=1, keepdims=True)

    plt.figure(figsize=(16, 4))
    plt.title("Normalized Log-Sum")
    plt.boxplot(normalized.reshape(-1), vert=False)

    fstrength = np.exp(normalized)

    plt.figure(figsize=(16, 4))
    plt.title("Firing Strength")
    plt.boxplot(fstrength.reshape(-1), vert=False)

#plot_prod_layer(fcm_model, train_x[:64])
```

The activations of each layer are shown in the boxplots above. The firing strength of the rules seem to be exclusively ones. I am unsure as to why this is, but it will likely cause a problem with training.

```python
#plot_gradients(fcm_model, train_x[:128])
```

Plotted above are the models gradients.

```python
def plot_history(history):
    plt.figure(figsize=(16, 8))
    plt.title("Loss")
    plt.plot(history.history["loss"], c="b")
    plt.plot(history.history["val_loss"], c="r")

    plt.figure(figsize=(16, 8))
    plt.title("Accuracy")
    plt.plot(history.history["categorical_accuracy"], c="b")
    plt.plot(history.history["val_categorical_accuracy"], c="r")

# fcm_model.compile(
#     optimizer="sgd",
#     loss="binary_crossentropy",
#     metrics=[keras.metrics.categorical_accuracy])

# fcm_history = fcm_model.fit(
#     x=train_x,
#     y=train_y,
#     batch_size=64,
#     epochs=100,
#     validation_data=(test_x, test_y),
#     verbose=0)

# plot_history(fcm_history)
```

When initialized using the parameters from FCM, the model does not seem to learn at all. Both accuracy and loss seem to completely plateau. This is most likely due to numerous small values in the sigma parameters but will need to be investigated in more depth later.

```python
centers_model = create_model(init_mu, np.ones((10,784)))

# centers_model.compile(
#     optimizer="adam",
#     loss="binary_crossentropy",
#     metrics=[keras.metrics.categorical_accuracy])

# centers_history = centers_model.fit(
#     x=train_x,
#     y=train_y,
#     batch_size=64,
#     epochs=50,
#     validation_data=(test_x, test_y),
#     verbose=1)

# plot_history(centers_history)
```

Using an array of ones in place of the initial sigma values allows the network to train and reach an accuracy of around 70%. Extrapolating from the graph, better performance can be achieved by letting it train longer.

```python
sigmas_model = create_model(np.zeros((10,784)), init_sigma)

# sigmas_model.compile(
#     optimizer="sgd",
#     loss="binary_crossentropy",
#     metrics=[keras.metrics.categorical_accuracy])

# sigmas_history = sigmas_model.fit(
#     x=train_x,
#     y=train_y,
#     batch_size=64,
#     epochs=100,
#     validation_data=(test_x, test_y),
#     verbose=0)

# plot_history(sigmas_history)
```

Using the zeros for the mu values, and the initial sigma values the network encounters the same problem where it is unable to train.

```python
ones_zeros_model = create_model(np.zeros((10,784)), np.ones((10,784)))

# ones_zeros_model.compile(
#     optimizer="sgd",
#     loss="binary_crossentropy",
#     metrics=[keras.metrics.categorical_accuracy])

# ones_zeros_history = ones_zeros_model.fit(
#     x=train_x,
#     y=train_y,
#     batch_size=64,
#     epochs=100,
#     validation_data=(test_x, test_y),
#     verbose=0)

# plot_history(ones_zeros_history)
```

Surprisingly, using zeros for mu and ones for sigma as initial values seems to give the best results so far. The network exceeds 80% accuracy and shows no signs of overfitting. The network does seem to take a very long time to train, taking 100 epochs to reach ~85% accuracy.

```python
model = create_model(init_mu, np.ones((10,784)))

model.compile(
    optimizer="adam",
    loss="binary_crossentropy",
    metrics=[keras.metrics.categorical_accuracy])

history = model.fit(
    x=train_x,
    y=train_y,
    batch_size=64,
    epochs=50,
    validation_data=(test_x, test_y),
    verbose=1)
```

    Train on 60000 samples, validate on 10000 samples
    Epoch 1/50
    60000/60000 [==============================] - 3s 58us/step - loss: 0.4104 - categorical_accuracy: 0.2533 - val_loss: 0.2905 - val_categorical_accuracy: 0.3845
    Epoch 2/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.2640 - categorical_accuracy: 0.4919 - val_loss: 0.2387 - val_categorical_accuracy: 0.6201
    Epoch 3/50
    60000/60000 [==============================] - 3s 49us/step - loss: 0.2158 - categorical_accuracy: 0.6862 - val_loss: 0.1858 - val_categorical_accuracy: 0.7500
    Epoch 4/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.1694 - categorical_accuracy: 0.7865 - val_loss: 0.1544 - val_categorical_accuracy: 0.8402
    Epoch 5/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.1449 - categorical_accuracy: 0.8441 - val_loss: 0.1359 - val_categorical_accuracy: 0.8509
    Epoch 6/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.1283 - categorical_accuracy: 0.8575 - val_loss: 0.1225 - val_categorical_accuracy: 0.8509
    Epoch 7/50
    60000/60000 [==============================] - 3s 51us/step - loss: 0.1159 - categorical_accuracy: 0.8662 - val_loss: 0.1129 - val_categorical_accuracy: 0.8645
    Epoch 8/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.1070 - categorical_accuracy: 0.8725 - val_loss: 0.1048 - val_categorical_accuracy: 0.8749
    Epoch 9/50
    60000/60000 [==============================] - 3s 51us/step - loss: 0.1007 - categorical_accuracy: 0.8788 - val_loss: 0.1000 - val_categorical_accuracy: 0.8771
    Epoch 10/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.0960 - categorical_accuracy: 0.8838 - val_loss: 0.0971 - val_categorical_accuracy: 0.8807
    Epoch 11/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.0923 - categorical_accuracy: 0.8881 - val_loss: 0.0935 - val_categorical_accuracy: 0.8821
    Epoch 12/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.0892 - categorical_accuracy: 0.8907 - val_loss: 0.0921 - val_categorical_accuracy: 0.8822
    Epoch 13/50
    60000/60000 [==============================] - 3s 49us/step - loss: 0.0868 - categorical_accuracy: 0.8933 - val_loss: 0.0893 - val_categorical_accuracy: 0.8880
    Epoch 14/50
    60000/60000 [==============================] - 3s 52us/step - loss: 0.0847 - categorical_accuracy: 0.8950 - val_loss: 0.0891 - val_categorical_accuracy: 0.8830
    Epoch 15/50
    60000/60000 [==============================] - 3s 51us/step - loss: 0.0828 - categorical_accuracy: 0.8968 - val_loss: 0.0866 - val_categorical_accuracy: 0.8898
    Epoch 16/50
    60000/60000 [==============================] - 3s 51us/step - loss: 0.0810 - categorical_accuracy: 0.8984 - val_loss: 0.0848 - val_categorical_accuracy: 0.8905
    Epoch 17/50
    60000/60000 [==============================] - 3s 51us/step - loss: 0.0798 - categorical_accuracy: 0.8992 - val_loss: 0.0846 - val_categorical_accuracy: 0.8905
    Epoch 18/50
    60000/60000 [==============================] - 3s 50us/step - loss: 0.0782 - categorical_accuracy: 0.9016 - val_loss: 0.0824 - val_categorical_accuracy: 0.8916
    Epoch 19/50
    60000/60000 [==============================] - 3s 53us/step - loss: 0.0770 - categorical_accuracy: 0.9032 - val_loss: 0.0820 - val_categorical_accuracy: 0.8908
    Epoch 20/50
    60000/60000 [==============================] - 3s 53us/step - loss: 0.0757 - categorical_accuracy: 0.9040 - val_loss: 0.0808 - val_categorical_accuracy: 0.8935
    Epoch 21/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0742 - categorical_accuracy: 0.9061 - val_loss: 0.0795 - val_categorical_accuracy: 0.8917
    Epoch 22/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0698 - categorical_accuracy: 0.9113 - val_loss: 0.0731 - val_categorical_accuracy: 0.9089
    Epoch 23/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0662 - categorical_accuracy: 0.9170 - val_loss: 0.0712 - val_categorical_accuracy: 0.9072
    Epoch 24/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0642 - categorical_accuracy: 0.9195 - val_loss: 0.0703 - val_categorical_accuracy: 0.9103
    Epoch 25/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0624 - categorical_accuracy: 0.9211 - val_loss: 0.0675 - val_categorical_accuracy: 0.9119
    Epoch 26/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0608 - categorical_accuracy: 0.9229 - val_loss: 0.0667 - val_categorical_accuracy: 0.9101
    Epoch 27/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0594 - categorical_accuracy: 0.9238 - val_loss: 0.0654 - val_categorical_accuracy: 0.9156
    Epoch 28/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0581 - categorical_accuracy: 0.9249 - val_loss: 0.0652 - val_categorical_accuracy: 0.9151
    Epoch 29/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0569 - categorical_accuracy: 0.9261 - val_loss: 0.0639 - val_categorical_accuracy: 0.9171
    Epoch 30/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0557 - categorical_accuracy: 0.9267 - val_loss: 0.0627 - val_categorical_accuracy: 0.9143
    Epoch 31/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0543 - categorical_accuracy: 0.9285 - val_loss: 0.0614 - val_categorical_accuracy: 0.9152
    Epoch 32/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0533 - categorical_accuracy: 0.9304 - val_loss: 0.0609 - val_categorical_accuracy: 0.9182
    Epoch 33/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0524 - categorical_accuracy: 0.9308 - val_loss: 0.0597 - val_categorical_accuracy: 0.9187
    Epoch 34/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0516 - categorical_accuracy: 0.9321 - val_loss: 0.0590 - val_categorical_accuracy: 0.9219
    Epoch 35/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0508 - categorical_accuracy: 0.9331 - val_loss: 0.0582 - val_categorical_accuracy: 0.9199
    Epoch 36/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0500 - categorical_accuracy: 0.9345 - val_loss: 0.0586 - val_categorical_accuracy: 0.9222
    Epoch 37/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0497 - categorical_accuracy: 0.9344 - val_loss: 0.0580 - val_categorical_accuracy: 0.9206
    Epoch 38/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0492 - categorical_accuracy: 0.9343 - val_loss: 0.0582 - val_categorical_accuracy: 0.9173
    Epoch 39/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0486 - categorical_accuracy: 0.9366 - val_loss: 0.0568 - val_categorical_accuracy: 0.9229
    Epoch 40/50
    60000/60000 [==============================] - 3s 49us/step - loss: 0.0479 - categorical_accuracy: 0.9366 - val_loss: 0.0564 - val_categorical_accuracy: 0.9234
    Epoch 41/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0474 - categorical_accuracy: 0.9371 - val_loss: 0.0547 - val_categorical_accuracy: 0.9254
    Epoch 42/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0471 - categorical_accuracy: 0.9373 - val_loss: 0.0565 - val_categorical_accuracy: 0.9224
    Epoch 43/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0466 - categorical_accuracy: 0.9392 - val_loss: 0.0545 - val_categorical_accuracy: 0.9243
    Epoch 44/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0462 - categorical_accuracy: 0.9387 - val_loss: 0.0566 - val_categorical_accuracy: 0.9227
    Epoch 45/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0460 - categorical_accuracy: 0.9389 - val_loss: 0.0543 - val_categorical_accuracy: 0.9257
    Epoch 46/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0455 - categorical_accuracy: 0.9395 - val_loss: 0.0552 - val_categorical_accuracy: 0.9252
    Epoch 47/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0454 - categorical_accuracy: 0.9396 - val_loss: 0.0543 - val_categorical_accuracy: 0.9224
    Epoch 48/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0449 - categorical_accuracy: 0.9403 - val_loss: 0.0542 - val_categorical_accuracy: 0.9221
    Epoch 49/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0447 - categorical_accuracy: 0.9403 - val_loss: 0.0547 - val_categorical_accuracy: 0.9221
    Epoch 50/50
    60000/60000 [==============================] - 3s 48us/step - loss: 0.0445 - categorical_accuracy: 0.9406 - val_loss: 0.0545 - val_categorical_accuracy: 0.9201

```python
def summarize_history(history):
    print("Training Accuracy: {:.2%}".format(np.max(history.history["categorical_accuracy"])))
    print("Validation Accuracy: {:.2%}".format(np.max(history.history["val_categorical_accuracy"])))

fig, axes = plt.subplots(1, 2, figsize=(8, 4), squeeze=True)
axes[0].set_title("Loss")
axes[0].plot(history.history["loss"], c="b")
axes[0].plot(history.history["val_loss"], c="r")

axes[1].set_title("Accuracy")
axes[1].set_ylim((0.8, 1))
axes[1].plot(history.history["categorical_accuracy"], c="b")
axes[1].plot(history.history["val_categorical_accuracy"], c="r")

summarize_history(history)
```

Using the adam optimizer gives the best training results so far. The network starts to overfit somewhere between 10-20 epochs. This means the network won't have to be trained for hundreds of epochs.

```python
# ones_zeros_model = create_model(np.zeros((10,784)), np.ones((10,784)))

# ones_zeros_model.compile(
#     optimizer="adam",
#     loss="binary_crossentropy",
#     metrics=[keras.metrics.categorical_accuracy])

# adam_history = ones_zeros_model.fit(
#     x=train_x,
#     y=train_y,
#     batch_size=64,
#     epochs=20,
#     validation_data=(test_x, test_y),
#     verbose=0)

# summarize_history(adam_history)
# plot_history(adam_history)
```

Using the Adam optimizer, good results are achieved in only 20 epochs.

## Other Parameters
This investigates the model's performance with different numbers of rules.

```python
# for n in [20, 50, 100]:
#     model = create_model(np.zeros((n,784)), np.ones((n,784)), num_rules=n)

#     model.compile(
#         optimizer="adam",
#         loss="binary_crossentropy",
#         metrics=[keras.metrics.categorical_accuracy])

#     history = model.fit(
#         x=train_x,
#         y=train_y,
#         batch_size=64,
#         epochs=20,
#         validation_data=(test_x, test_y),
#         verbose=0)

#     print("{} Rules:".format(n))
#     summarize_history(history)
#     plot_history(history)
```


# CSE 330 Numerical Analysis Lab

### Lab 5

### Instructions
---

Todays assignment is to:
1. Implement Richardson Extrapolation method using Python

### Richardson Extrapolation:
We used central difference method to calculate derivatives of functions last week. Thise week we will use Richardson extrapolation to get a more accurate result.
Let,
$$ D_h = \frac{f(x_1+h) -f(x_1-h)}{2h}\tag{5.1}$$
Using Taylor's theorem to expand we get,

\begin{align}
f(x_1+h) &= f(x_1) + f^{\prime}(x_1)h + \frac{f^{\prime \prime}(x_1)}{2}h^2 + \frac{f^{\prime \prime \prime}(x_1)}{3!}h^3 + \frac{f^{(4)}(x_1)}{4!}h^4 + \frac{f^{(5)}(x_1)}{5!}h^5 + O(h^6)\tag{5.2} \\
f(x_1-h) &= f(x_1) - f^{\prime}(x_1)h + \frac{f^{\prime \prime}(x_1)}{2}h^2 - \frac{f^{\prime \prime \prime}(x_1)}{3!}h^3 + \frac{f^{(4)}(x_1)}{4!}h^4 - \frac{f^{(5)}(x_1)}{5!}h^5 + O(h^6)\tag{5.3}
\end{align}
Subtracting $5.3$ from $5.2$ we get,
$$ f(x_1+h) - f(x_1-h) = 2f^{\prime}(x_1)h + 2\frac{f^{\prime \prime \prime}(x_1)}{3!}h^3 + 2\frac{f^{(5)}(x_1)}{5!}h^5 + O(h^6)\tag{5.4}$$
So,
\begin{align}
D_h &= \frac{f(x_1+h) - f(x_1-h)}{2h} \\
&= \frac{1}{2h} \left( 2f^{\prime}(x_1)h + 2\frac{f^{\prime \prime \prime}(x_1)}{3!}h^3 + 2\frac{f^{(5)}(x_1)}{5!}h^5 + O(h^6) \right) \\
&= f^{\prime}(x_1) + \frac{f^{\prime \prime \prime}(x_1)}{6}h^2 + \frac{f^{(5)}(x_1)}{120}h^4 + O(h^6) \tag{5.5}
\end{align}
If we use $h, \text{and} \frac{h}{2}$ as step size in $5.5$, we get,
\begin{align}
D_h &= f^{\prime}(x_1) + f^{\prime \prime \prime}(x_1)\frac{h^2}{6} + f^{(5)}(x_1) \frac{h^4}{120} + O(h^6) \tag{5.6} \\
D_{h/2} &= f^{\prime}(x_1) + f^{\prime \prime \prime}(x_1)\frac{h^2}{2^2 . 6} + f^{(5)}(x_1) \frac{h^4}{2^4 . 120} + O(h^6) \tag{5.7}
\end{align}
Multiplying $5.7$ by $4$ and subtracting from $5.6$ we get,
\begin{align}
D_h - 4D_{h/2} &= -3f^{\prime} + f^{(5)}(x_1) \frac{h^4}{160} + O(h^6)\\
\Longrightarrow D^{(1)}_h = \frac{4D_{h/2} - D_h}{3} &= f^{\prime} - f^{(5)}(x_1) \frac{h^4}{480} + O(h^6) \tag{5.8}
\end{align}
Let's calculate the derivative using $5.8$

#### A. Let's import the necessary headers

```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy.polynomial import Polynomial

```

#### B. Let's create a function named `dh`
function `dh` takes three parameters as input: a function (`f`), a value `h` and a set of values `x`. It returns the derivatives of the function at each elements of array `x`.

```
def dh(f, h, x):
    '''
    Input:
        f: np.polynomial.Polynonimial type data.
        h: floating point data.
        x: np.array type data.
    Output:
        return np.array type data of slope at each point x.
    '''
    return (f(x+h)-f(x-h))/(2*h);

```

####C. Let's create another funtion `dh1`.
`dh1` takes the same type of values as `dh` as input. It calculates the derivative using previously defined `dh` function and using equation $5.8$ and returns the values.

```
def dh1(f, h, x):
    '''
    Input:
        f: np.polynomial.Polynonimial type data.
        h: floating point data.
        x: np.array type data.
    Output:
        return np.array type data of slope at each point x.
    '''
    return (4*dh(f,h/2,x) - dh(f,h,x))/3
```

####D. Now let's create an `error` function
`error` function takes a function `f` as input. It also takes a list of different values of h as `hs` and a specific value as `x_i` as input. It calculates the derivatives as point `x_i` using both functions described in **A** and **B**.

```
def error(f, hs, x_i):
    '''
    Input:
        f  : np.polynomial.Polynonimial type data.
        hs : np.array type data. list of h.
        x_i: floating point data. single value of x.
    Output:
        return two np.array type data of errors by two methods..
    '''
    f_prime = f.deriv(1)
    Y_actual = f_prime(x_i)

    diff_error = []
    diff2_error = []

    for h in hs:
        # for each values of hs calculate the error using both methods
        # and append those values into diff_error and diff2_error list.

        # write your code here
        diff_error.append(Y_actual - dh(f, h, x_i))
        diff2_error.append(Y_actual - dh1(f, h, x_i))

    print(pd.DataFrame({"h": hs, "Diff": diff_error, "Diff2": diff2_error}))

    return diff_error, diff2_error
```

####E. Finally let's run some tests

```
def draw_graph(f, ax, domain=[-10, 10], label=None):
    data = f.linspace(domain=domain)
    ax.plot(data[0], data[1], label='Function')

########
# Draw the graph and it's derivative
#######
fig, ax = plt.subplots()
ax.axhline(y=0, color='k')

p = Polynomial([2.0, 1.0, -6.0, -2.0, 2.5, 1.0])
p_prime = p.deriv(1)
draw_graph(p, ax, [-2.4, 1.5], 'Function')
draw_graph(p_prime, ax, [-2.4, 1.5], 'Derivative')

ax.legend()

########
# Draw the actual derivative and richardson derivative using
# h=1 and h=-0.1 as step size.
#######
fig, ax = plt.subplots()
ax.axhline(y=0, color='k')

draw_graph(p_prime, ax, [-2.4, 1.5], 'actual')

h = 1
x = np.linspace(-2.4, 1.5, 50, endpoint=True)
y = dh1(p, h, x)
ax.plot(x, y, label='Richardson; h=1')

h = 0.1
x = np.linspace(-2.4, 1.5, 50, endpoint=True)
y = dh1(p, h, x)
ax.plot(x, y, label='Richardson; h=0.1')

ax.legend()

########
# Draw h-vs-error cuve
#######
fig, ax = plt.subplots()
ax.axhline(y=0, color='k')
hs = np.array([1., 0.55, 0.3, .17, 0.1, 0.055, 0.03, 0.017, 0.01])
e1, e2 = error(p, hs, 2.0)
ax.plot(hs, e1, label='e1')
ax.plot(hs, e2, label='e2')

ax.legend()

```


# Chapter 4
`Original content created by Cam Davidson-Pilon`

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

______

## The greatest theorem never told

This chapter focuses on an idea that is always bouncing around our minds, but is rarely made explicit outside books devoted to statistics. In fact, we've been using this simple idea in every example thus far.

### The Law of Large Numbers

Let $Z_i$ be $N$ independent samples from some probability distribution. According to *the Law of Large numbers*,  so long as the expected value $E[Z]$ is finite, the following holds,

$$\frac{1}{N} \sum_{i=1}^N Z_i \rightarrow E[ Z ],  \;\;\; N \rightarrow \infty.$$

In words:

>   The average of a sequence of random variables from the same distribution converges to the expected value of that distribution.

This may seem like a boring result, but it will be the most useful tool you use.

### Intuition

If the above Law is somewhat surprising,  it can be made more clear by examining a simple example.

Consider a random variable $Z$ that can take only two values, $c_1$ and $c_2$. Suppose we have a large number of samples of $Z$, denoting a specific sample $Z_i$. The Law says that we can approximate the expected value of $Z$ by averaging over all samples. Consider the average:

$$ \frac{1}{N} \sum_{i=1}^N \;Z_i $$

By construction, $Z_i$ can only take on $c_1$ or $c_2$, hence we can partition the sum over these two values:

\begin{align}
\frac{1}{N} \sum_{i=1}^N \;Z_i
& =\frac{1}{N} \big(  \sum_{ Z_i = c_1}c_1 + \sum_{Z_i=c_2}c_2 \big) \\\\[5pt]
& = c_1 \sum_{ Z_i = c_1}\frac{1}{N} + c_2 \sum_{ Z_i = c_2}\frac{1}{N} \\\\[5pt]
& = c_1 \times \text{ (approximate frequency of $c_1$) } \\\\
& \;\;\;\;\;\;\;\;\; + c_2 \times \text{ (approximate frequency of $c_2$) } \\\\[5pt]
& \approx c_1 \times P(Z = c_1) + c_2 \times P(Z = c_2 ) \\\\[5pt]
& = E[Z]
\end{align}

Equality holds in the limit, but we can get closer and closer by using more and more samples in the average. This Law holds for almost *any distribution*, minus some important cases we will encounter later.

##### Example
____

Below is a diagram of the Law of Large numbers in action for three different sequences of Poisson random variables.

 We sample `sample_size = 100000` Poisson random variables with parameter $\lambda = 4.5$. (Recall the expected value of a Poisson random variable is equal to its parameter.) We calculate the average for the first $n$ samples, for $n=1$ to `sample_size`.

```python
%matplotlib inline
import numpy as np
from IPython.core.pylabtools import figsize
import matplotlib.pyplot as plt

figsize( 12.5, 5 )

sample_size = 100000
expected_value = lambda_ = 4.5
poi = np.random.poisson
N_samples = range(1,sample_size,100)

for k in range(3):

    samples = poi( lambda_, sample_size )

    partial_average = [ samples[:i].mean() for i in N_samples ]

    plt.plot( N_samples, partial_average, lw=1.5,label="average \
of  $n$ samples; seq. %d"%k)

plt.plot( N_samples, expected_value*np.ones_like( partial_average),
    ls = "--", label = "true expected value", c = "k" )

plt.ylim( 4.35, 4.65)
plt.title( "Convergence of the average of \n random variables to its \
expected value" )
plt.ylabel( "average of $n$ samples" )
plt.xlabel( "# of samples, $n$")
plt.legend();
```

Looking at the above plot, it is clear that when the sample size is small, there is greater variation in the average (compare how *jagged and jumpy* the average is initially, then *smooths* out). All three paths *approach* the value 4.5, but just flirt with it as $N$ gets large. Mathematicians and statistician have another name for *flirting*: convergence.

Another very relevant question we can ask is *how quickly am I converging to the expected value?* Let's plot something new. For a specific $N$, let's do the above trials thousands of times and compute how far away we are from the true expected value, on average. But wait — *compute on average*? This is simply the law of large numbers again! For example, we are interested in, for a specific $N$, the quantity:

$$D(N) = \sqrt{ \;E\left[\;\; \left( \frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \;\right)^2 \;\;\right] \;\;}$$

The above formulae is interpretable as a distance away from the true value (on average), for some $N$. (We take the square root so the dimensions of the above quantity and our random variables are the same). As the above is an expected value, it can be approximated using the law of large numbers: instead of averaging $Z_i$, we calculate the following multiple times and average them:

$$ Y_k = \left( \;\frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \; \right)^2 $$

By computing the above many, $N_y$, times (remember, it is random), and averaging them:

$$ \frac{1}{N_Y} \sum_{k=1}^{N_Y} Y_k \rightarrow E[ Y_k ] = E\;\left[\;\; \left( \frac{1}{N}\sum_{i=1}^NZ_i  - 4.5 \;\right)^2 \right]$$

Finally, taking the square root:

$$ \sqrt{\frac{1}{N_Y} \sum_{k=1}^{N_Y} Y_k} \approx D(N) $$

```python
figsize( 12.5, 4)

N_Y = 250 #use this many to approximate D(N)
N_array = np.arange( 1000, 50000, 2500 ) #use this many samples in the approx. to the variance.
D_N_results = np.zeros( len( N_array ) )

lambda_ = 4.5
expected_value = lambda_ #for X ~ Poi(lambda) , E[ X ] = lambda

def D_N( n ):
    """
    This function approx. D_n, the average variance of using n samples.
    """
    Z = poi( lambda_, (n, N_Y) )
    average_Z = Z.mean(axis=0)
    return np.sqrt( (  (average_Z - expected_value)**2  ).mean() )

for i,n in enumerate(N_array):
    D_N_results[i] =  D_N(n)

plt.xlabel( "$N$" )
plt.ylabel( "expected squared-distance from true value" )
plt.plot(N_array, D_N_results, lw = 3,
            label="expected distance between\n\
expected value and \naverage of $N$ random variables.")
plt.plot( N_array, np.sqrt(expected_value)/np.sqrt(N_array), lw = 2, ls = "--",
        label = r"$\frac{\sqrt{\lambda}}{\sqrt{N}}$" )
plt.legend()
plt.title( "How 'fast' is the sample average converging? " );
```

As expected, the expected distance between our sample average and the actual expected value shrinks as $N$ grows large. But also notice that the *rate* of convergence decreases, that is, we need only 10 000 additional samples to move from 0.020 to 0.015, a difference of 0.005, but *20 000* more samples to again decrease from 0.015  to 0.010, again only a 0.005 decrease.

It turns out we can measure this rate of convergence. Above I have plotted a second line, the function $\sqrt{\lambda}/\sqrt{N}$. This was not chosen arbitrarily. In most cases, given a sequence of random variable distributed like $Z$, the rate of convergence to $E[Z]$ of the Law of Large Numbers is

$$ \frac{ \sqrt{ \; Var(Z) \; } }{\sqrt{N} }$$

This is useful to know: for a given large $N$, we know (on average) how far away we are from the estimate. On the other hand, in a Bayesian setting, this can seem like a useless result: Bayesian analysis is OK with uncertainty so what's the *statistical* point of adding extra precise digits? Though drawing samples can be so computationally cheap that having a *larger* $N$ is fine too.

### How do we compute $Var(Z)$ though?

The variance is simply another expected value that can be approximated! Consider the following, once we have the expected value (by using the Law of Large Numbers to estimate it, denote it $\mu$), we can estimate the variance:

$$ \frac{1}{N}\sum_{i=1}^N \;(Z_i - \mu)^2 \rightarrow E[ \;( Z - \mu)^2 \;] = Var( Z )$$

### Expected values and probabilities
There is an even less explicit relationship between expected value and estimating probabilities. Define the *indicator function*

$$\mathbb{1}_A(x) =
\begin{cases} 1 &  x \in A \\\\
              0 &  else
\end{cases}
$$
Then, by the law of large numbers, if we have many samples $X_i$, we can estimate the probability of an event $A$, denoted $P(A)$, by:

$$ \frac{1}{N} \sum_{i=1}^N \mathbb{1}_A(X_i) \rightarrow E[\mathbb{1}_A(X)] =  P(A) $$

Again, this is fairly obvious after a moments thought: the indicator function is only 1 if the event occurs, so we are summing only the times the event occurs and dividing by the total number of trials  (consider how we usually approximate probabilities using frequencies). For example, suppose we wish to estimate the probability that a $Z \sim Exp(.5)$ is greater than 5, and we have many samples from a $Exp(.5)$ distribution.

$$ P( Z > 5 ) =  \frac{1}{N}\sum_{i=1}^N \mathbb{1}_{z > 5 }(Z_i) $$

```python
N = 10000
print( np.mean( [ np.random.exponential( 0.5 ) > 5 for i in range(N) ] ) )
```

    0.0001

### What does this all have to do with Bayesian statistics?

*Point estimates*, to be introduced in the next chapter, in Bayesian inference are computed using expected values. In more analytical Bayesian inference, we would have been required to evaluate complicated expected values represented as multi-dimensional integrals. No longer. If we can sample from the posterior distribution directly, we simply need to evaluate averages. Much easier. If accuracy is a priority, plots like the ones above show how fast you are converging. And if further accuracy is  desired, just take more samples from the posterior.

When is enough enough? When can you stop drawing samples from the posterior? That is the practitioners decision, and also dependent on the variance of the samples (recall from above a high variance means the average will converge slower).

We also should understand when the Law of Large Numbers fails. As the name implies, and comparing the graphs above for small $N$, the Law is only true for large sample sizes. Without this, the asymptotic result is not reliable. Knowing in what situations the Law fails can give us *confidence in how unconfident we should be*. The next section deals with this issue.

## The Disorder of Small Numbers

The Law of Large Numbers is only valid as $N$ gets *infinitely* large: never truly attainable.  While the law is a powerful tool, it is foolhardy to apply it liberally. Our next example illustrates this.

##### Example: Aggregated geographic data

Often data comes in aggregated form. For instance, data may be grouped by state, county, or city level. Of course, the population numbers vary per geographic area. If the data is an average of some characteristic of each the geographic areas, we must be conscious of the Law of Large Numbers and how it can *fail* for areas with small populations.

We will observe this on a toy dataset. Suppose there are five thousand counties in our dataset. Furthermore,  population number in each state are uniformly distributed between 100 and 1500. The way the population numbers are generated is irrelevant to the discussion, so we do not justify this. We are interested in measuring the average height of individuals per county. Unbeknownst to us, height does **not** vary across county, and each individual, regardless of the county he or she is currently living in, has the same distribution of what their height may be:

$$ \text{height} \sim \text{Normal}(150, 15 ) $$

We aggregate the individuals at the county level, so we only have data for the *average in the county*. What might our dataset look like?

```python
figsize( 12.5, 4)
std_height = 15
mean_height = 150

n_counties = 5000
pop_generator = np.random.randint
norm = np.random.normal

#generate some artificial population numbers
population = pop_generator(100, 1500, n_counties )

average_across_county = np.zeros( n_counties )
for i in range( n_counties ):
    #generate some individuals and take the mean
    average_across_county[i] = norm(mean_height, 1./std_height,
                                        population[i] ).mean()

#located the counties with the apparently most extreme average heights.
i_min = np.argmin( average_across_county )
i_max = np.argmax( average_across_county )

#plot population size vs. recorded average
plt.scatter( population, average_across_county, alpha = 0.5, c="#7A68A6")
plt.scatter( [ population[i_min], population[i_max] ],
           [average_across_county[i_min], average_across_county[i_max] ],
           s = 60, marker = "o", facecolors = "none",
           edgecolors = "#A60628", linewidths = 1.5,
            label="extreme heights")

plt.xlim( 100, 1500 )
plt.title( "Average height vs. County Population")
plt.xlabel("County Population")
plt.ylabel("Average height in county")
plt.plot( [100, 1500], [150, 150], color = "k", label = "true expected \
height", ls="--" )
plt.legend(scatterpoints = 1);
```

What do we observe? *Without accounting for population sizes* we run the risk of making an enormous inference error: if we ignored population size, we would say that the county with the shortest and tallest individuals have been correctly circled. But this inference is wrong for the following reason. These two counties do *not* necessarily have the most extreme heights. The error results from the calculated average of smaller populations not being a good reflection of the true expected value of the population (which in truth should be $\mu =150$). The sample size/population size/$N$, whatever you wish to call it,  is simply too small to invoke the Law of Large Numbers effectively.

We provide more damning evidence against this inference. Recall the population numbers were uniformly distributed over 100 to 1500. Our intuition should tell us that the counties with the most extreme population heights should also be uniformly spread over 100 to 1500, and certainly independent of the county's population. Not so. Below are the population sizes of the counties with the most extreme heights.

```python
print("Population sizes of 10 'shortest' counties: ")
print(population[ np.argsort( average_across_county )[:10] ], '\n')
print("Population sizes of 10 'tallest' counties: ")
print(population[ np.argsort( -average_across_county )[:10] ])
```

    Population sizes of 10 'shortest' counties:
    [260 161 137 136 277 104 298 133 155 456]

    Population sizes of 10 'tallest' counties:
    [137 108 186 101 217 139 241 294 138 245]

Not at all uniform over 100 to 1500. This is an absolute failure of the Law of Large Numbers.

##### Example:  Kaggle's *U.S. Census Return Rate Challenge*

Below is data from the 2010 US census, which partitions populations beyond counties to the level of block groups (which are aggregates of city blocks or equivalents). The dataset is from a Kaggle machine learning competition some colleagues and I participated in. The objective was to predict the census letter mail-back rate of a group block, measured between 0 and 100, using census variables (median income, number of females in the block-group, number of trailer parks, average number of children etc.). Below we plot the census mail-back rate versus block group population:

```python
figsize( 12.5, 6.5 )
data = np.genfromtxt( "./data/census_data.csv", skip_header=1,
                        delimiter= ",")
plt.scatter( data[:,1], data[:,0], alpha = 0.5, c="#7A68A6")
plt.title("Census mail-back rate vs Population")
plt.ylabel("Mail-back rate")
plt.xlabel("population of block-group")
plt.xlim(-100, 15e3 )
plt.ylim( -5, 105)

i_min = np.argmin(  data[:,0] )
i_max = np.argmax(  data[:,0] )

plt.scatter( [ data[i_min,1], data[i_max, 1] ],
             [ data[i_min,0],  data[i_max,0] ],
             s = 60, marker = "o", facecolors = "none",
             edgecolors = "#A60628", linewidths = 1.5,
             label="most extreme points")

plt.legend(scatterpoints = 1);
```

The above is a classic phenomenon in statistics. I say *classic* referring to the "shape" of the scatter plot above. It follows a classic triangular form, that tightens as we increase the sample size (as the Law of Large Numbers becomes more exact).

I am perhaps overstressing the point and maybe I should have titled the book *"You don't have big data problems!"*, but here again is an example of the trouble with *small datasets*, not big ones. Simply, small datasets cannot be processed using the Law of Large Numbers. Compare with applying the Law without hassle to big datasets (ex. big data). I mentioned earlier that paradoxically big data prediction problems are solved by relatively simple algorithms. The paradox is partially resolved by understanding that the Law of Large Numbers creates solutions that are *stable*, i.e. adding or subtracting a few data points will not affect the solution much. On the other hand, adding or removing data points to a small dataset can create very different results.

For further reading on the hidden dangers of the Law of Large Numbers, I would highly recommend the excellent manuscript [The Most Dangerous Equation](http://nsm.uh.edu/~dgraur/niv/TheMostDangerousEquation.pdf).

##### Example: How to order Reddit submissions

You may have disagreed with the original statement that the Law of Large numbers is known to everyone, but only implicitly in our subconscious decision making. Consider ratings on online products: how often do you trust an average 5-star rating if there is only 1 reviewer? 2 reviewers? 3 reviewers? We implicitly understand that with such few reviewers that the average rating is **not** a good reflection of the true value of the product.

This has created flaws in how we sort items, and more generally, how we compare items. Many people have realized that sorting online search results by their rating, whether the objects be books, videos, or online comments, return poor results. Often the seemingly top videos or comments have perfect ratings only from a few enthusiastic fans, and truly more quality videos or comments are hidden in later pages with *falsely-substandard* ratings of around 4.8. How can we correct this?

Consider the popular site Reddit (I purposefully did not link to the website as you would never come back). The site hosts links to stories or images, called submissions, for people to comment on. Redditors can vote up or down on each submission (called upvotes and downvotes). Reddit, by default, will sort submissions to a given subreddit by Hot, that is, the submissions that have the most upvotes recently.

How would you determine which submissions are the best? There are a number of ways to achieve this:

1. *Popularity*: A submission is considered good if it has many upvotes. A problem with this model is that a submission with hundreds of upvotes, but thousands of downvotes. While being very *popular*, the submission is likely more controversial than best.
2. *Difference*: Using the *difference* of upvotes and downvotes. This solves the above problem, but fails when we consider the temporal nature of submission. Depending on when a submission is posted, the website may be experiencing high or low traffic. The difference method will bias the *Top* submissions to be the those made during high traffic periods, which have accumulated more upvotes than submissions that were not so graced, but are not necessarily the best.
3. *Time adjusted*:  Consider using Difference divided by the age of the submission. This creates a *rate*, something like *difference per second*, or *per minute*. An immediate counter-example is, if we use per second, a 1 second old submission with 1 upvote would be better than a 100 second old submission with 99 upvotes. One can avoid this by only considering at least t second old submission. But what is a good t value? Does this mean no submission younger than t is good? We end up comparing unstable quantities with stable quantities (young vs. old submissions).
3. *Ratio*: Rank submissions by the ratio of upvotes to total number of votes (upvotes plus downvotes). This solves the temporal issue, such that new submissions who score well can be considered Top just as likely as older submissions, provided they have many upvotes to total votes. The problem here is that a submission with a single upvote (ratio = 1.0) will beat a submission with 999 upvotes and 1 downvote (ratio = 0.999), but clearly the latter submission is *more likely* to be better.

I used the phrase *more likely* for good reason. It is possible that the former submission, with a single upvote, is in fact a better submission than the later with 999 upvotes. The hesitation to agree with this is because we have not seen the other 999 potential votes the former submission might get. Perhaps it will achieve an additional 999 upvotes and 0 downvotes and be considered better than the latter, though not likely.

What we really want is an estimate of the *true upvote ratio*. Note that the true upvote ratio is not the same as the observed upvote ratio: the true upvote ratio is hidden, and we only observe upvotes vs. downvotes (one can think of the true upvote ratio as "what is the underlying probability someone gives this submission a upvote, versus a downvote"). So the 999 upvote/1 downvote submission probably has a true upvote ratio close to 1, which we can assert with confidence thanks to the Law of Large Numbers, but on the other hand we are much less certain about the true upvote ratio of the submission with only a single upvote. Sounds like a Bayesian problem to me.

One way to determine a prior on the upvote ratio is to look at the historical distribution of upvote ratios. This can be accomplished by scraping Reddit's submissions and determining a distribution. There are a few problems with this technique though:

1. Skewed data:  The vast majority of submissions have very few votes, hence there will be many submissions with ratios near the extremes (see the "triangular plot" in the above Kaggle dataset), effectively skewing our distribution to the extremes. One could try to only use submissions with votes greater than some threshold. Again, problems are encountered. There is a tradeoff between number of submissions available to use and a higher threshold with associated ratio precision.
2. Biased data: Reddit is composed of different subpages, called subreddits. Two examples are *r/aww*, which posts pics of cute animals, and *r/politics*. It is very likely that the user behaviour towards submissions of these two subreddits are very different: visitors are likely friendly and affectionate in the former, and would therefore upvote submissions more, compared to the latter, where submissions are likely to be controversial and disagreed upon. Therefore not all submissions are the same.

In light of these, I think it is better to use a `Uniform` prior.

With our prior in place, we can find the posterior of the true upvote ratio. The Python script `top_showerthoughts_submissions.py` will scrape the best posts from the `showerthoughts` community on Reddit. This is a text-only community so the title of each post *is* the post. Below is the top post as well as some other sample posts:

```python
#adding a number to the end of the %run call will get the ith top post.
%run top_showerthoughts_submissions.py 2

print("Post contents: \n")
print(top_post)
```

    Post contents:

    Toilet paper should be free and have advertising printed on it.

```python
"""
contents: an array of the text from the last 100 top submissions to a subreddit
votes: a 2d numpy array of upvotes, downvotes for each submission.
"""
n_submissions = len(votes)
submissions = np.random.randint( n_submissions, size=4)
print("Some Submissions (out of %d total) \n-----------"%n_submissions)
for i in submissions:
    print('"' + contents[i] + '"')
    print("upvotes/downvotes: ",votes[i,:], "\n")
```

    Some Submissions (out of 98 total)
    -----------
    "Rappers from the 90's used guns when they had beef rappers today use Twitter."
    upvotes/downvotes:  [32  3]

    "All polls are biased towards people who are willing to take polls"
    upvotes/downvotes:  [1918  101]

    "Taco Bell should give customers an extra tortilla so they can make a burrito out of all the stuff that spilled out of the other burritos they ate."
    upvotes/downvotes:  [79 17]

    "There should be an /r/alanismorissette where it's just examples of people using "ironic" incorrectly"
    upvotes/downvotes:  [33  6]

 For a given true upvote ratio $p$ and $N$ votes, the number of upvotes will look like a Binomial random variable with parameters $p$ and $N$. (This is because of the equivalence between upvote ratio and probability of upvoting versus downvoting, out of $N$ possible votes/trials). We create a function that performs Bayesian inference on $p$, for a particular submission's upvote/downvote pair.

```python
import pymc3 as pm

def posterior_upvote_ratio( upvotes, downvotes, samples = 20000):
    """
    This function accepts the number of upvotes and downvotes a particular submission recieved,
    and the number of posterior samples to return to the user. Assumes a uniform prior.
    """
    N = upvotes + downvotes
    with pm.Model() as model:
        upvote_ratio = pm.Uniform("upvote_ratio", 0, 1)
        observations = pm.Binomial( "obs",  N, upvote_ratio, observed=upvotes)

        trace = pm.sample(samples, step=pm.Metropolis())

    burned_trace = trace[int(samples/4):]
    return burned_trace["upvote_ratio"]

```

Below are the resulting posterior distributions.

```python
figsize( 11., 8)
posteriors = []
colours = ["#348ABD", "#A60628", "#7A68A6", "#467821", "#CF4457"]
for i in range(len(submissions)):
    j = submissions[i]
    posteriors.append( posterior_upvote_ratio( votes[j, 0], votes[j,1] ) )
    plt.hist( posteriors[i], bins = 10, normed = True, alpha = .9,
            histtype="step",color = colours[i%5], lw = 3,
            label = '(%d up:%d down)\n%s...'%(votes[j, 0], votes[j,1], contents[j][:50]) )
    plt.hist( posteriors[i], bins = 10, normed = True, alpha = .2,
            histtype="stepfilled",color = colours[i], lw = 3, )

plt.legend(loc="upper left")
plt.xlim( 0, 1)
plt.title("Posterior distributions of upvote ratios on different submissions");
```

Some distributions are very tight, others have very long tails (relatively speaking), expressing our uncertainty with what the true upvote ratio might be.

### Sorting!

We have been ignoring the goal of this exercise: how do we sort the submissions from *best to worst*? Of course, we cannot sort distributions, we must sort scalar numbers. There are many ways to distill a distribution down to a scalar: expressing the distribution through its expected value, or mean, is one way. Choosing the mean is a bad choice though. This is because the mean does not take into account the uncertainty of distributions.

I  suggest using the *95% least plausible value*, defined as the value such that there is only a 5% chance the true parameter is lower (think of the lower bound on the 95% credible region). Below are the posterior distributions with the 95% least-plausible value plotted:

```python
N = posteriors[0].shape[0]
lower_limits = []

for i in range(len(submissions)):
    j = submissions[i]
    plt.hist( posteriors[i], bins = 20, normed = True, alpha = .9,
            histtype="step",color = colours[i], lw = 3,
            label = '(%d up:%d down)\n%s...'%(votes[j, 0], votes[j,1], contents[j][:50]) )
    plt.hist( posteriors[i], bins = 20, normed = True, alpha = .2,
            histtype="stepfilled",color = colours[i], lw = 3, )
    v = np.sort( posteriors[i] )[ int(0.05*N) ]
    #plt.vlines( v, 0, 15 , color = "k", alpha = 1, linewidths=3 )
    plt.vlines( v, 0, 10 , color = colours[i], linestyles = "--",  linewidths=3  )
    lower_limits.append(v)
    plt.legend(loc="upper left")

plt.legend(loc="upper left")
plt.title("Posterior distributions of upvote ratios on different submissions");
order = np.argsort( -np.array( lower_limits ) )
print(order, lower_limits)
```

The best submissions, according to our procedure, are the submissions that are *most-likely* to score a high percentage of upvotes. Visually those are the submissions with the 95% least plausible value close to 1.

Why is sorting based on this quantity a good idea? By ordering by the 95% least plausible value, we are being the most conservative with what we think is best.  When using the lower-bound of the 95% credible interval, we believe with high certainty that the 'true upvote ratio' is at the very least equal to this value (or greater), thereby ensuring that the best submissions are still on top. Under this ordering, we impose the following very natural properties:

1. given two submissions with the same observed upvote ratio, we will assign the submission with more votes as better (since we are more confident it has a higher ratio).
2. given two submissions with the same number of votes, we still assign the submission with more upvotes as *better*.

### But this is too slow for real-time!

I agree, computing the posterior of every submission takes a long time, and by the time you have computed it, likely the data has changed. I delay the mathematics to the appendix, but I suggest using the following formula to compute the lower bound very fast.

$$ \frac{a}{a + b} - 1.65\sqrt{ \frac{ab}{ (a+b)^2(a + b +1 ) } }$$

where
\begin{align}
& a = 1 + u \\\\
& b = 1 + d \\\\
\end{align}

$u$ is the number of upvotes, and $d$ is the number of downvotes. The formula is a shortcut in Bayesian inference, which will be further explained in Chapter 6 when we discuss priors in more detail.

```python
def intervals(u,d):
    a = 1. + u
    b = 1. + d
    mu = a/(a+b)
    std_err = 1.65*np.sqrt( (a*b)/( (a+b)**2*(a+b+1.) ) )
    return ( mu, std_err )

print("Approximate lower bounds:")
posterior_mean, std_err  = intervals(votes[:,0],votes[:,1])
lb = posterior_mean - std_err
print(lb)
print("\n")
print("Top 40 Sorted according to approximate lower bounds:")
print("\n")
order = np.argsort( -lb )
ordered_contents = []
for i in order[:40]:
    ordered_contents.append( contents[i] )
    print(votes[i,0], votes[i,1], contents[i])
    print("-------------")
```

    Approximate lower bounds:
    [ 0.93349005  0.9532194   0.94149718  0.90859764  0.88705356  0.8558795
      0.85644927  0.93752679  0.95767101  0.91131012  0.910073    0.915999
      0.9140058   0.83276025  0.87593961  0.87436674  0.92830849  0.90642832
      0.89187973  0.89950891  0.91295322  0.78607629  0.90250203  0.79950031
      0.85219422  0.83703439  0.7619808   0.81301134  0.7313114   0.79137561
      0.82701445  0.85542404  0.82309334  0.75211374  0.82934814  0.82674958
      0.80933194  0.87448152  0.85350205  0.75460106  0.82934814  0.74417233
      0.79924258  0.8189683   0.75460106  0.90744016  0.83838023  0.78802791
      0.78400654  0.64638659  0.62047936  0.76137738  0.81365241  0.83838023
      0.78457533  0.84980627  0.79249393  0.69020315  0.69593922  0.70758151
      0.70268831  0.91620627  0.73346864  0.86382644  0.80877728  0.72708753
      0.79822085  0.68333632  0.81699014  0.65100453  0.79809005  0.74702492
      0.77318569  0.83221179  0.66500492  0.68134548  0.7249286   0.59412132
      0.58191312  0.73142963  0.73142963  0.66251028  0.87152685  0.74107856
      0.60935684  0.87152685  0.77484517  0.88783675  0.81814153  0.54569789
      0.6122496   0.75613569  0.53511973  0.74556767  0.81814153  0.85773646
      0.6122496   0.64814153]

    Top 40 Sorted according to approximate lower bounds:

    596 18 Someone should develop an AI specifically for reading Terms & Conditions and flagging dubious parts.
    -------------
    2360 98 Porn is the only industry where it is not only acceptable but standard to separate people based on race, sex and sexual preference.
    -------------
    1918 101 All polls are biased towards people who are willing to take polls
    -------------
    948 50 They should charge less for drinks in the drive-thru because you can't refill them.
    -------------
    3740 239 When I was in elementary school and going through the DARE program, I was positive a gang of older kids was going to corner me and force me to smoke pot. Then I became an adult and realized nobody is giving free drugs to somebody that doesn't want them.
    -------------
    166 7 "Noted" is the professional way of saying "K".
    -------------
    29 0 Rewatching Mr. Bean, I've realised that the character is an eccentric genius and not a blithering idiot.
    -------------
    289 18 You've been doing weird cameos in your friends' dreams since kindergarten.
    -------------
    269 17 At some point every parent has stopped wiping their child's butt and hoped for the best.
    -------------
    121 6 Is it really fair to say a person over 85 has heart failure? Technically, that heart has done exceptionally well.
    -------------
    535 40 It's surreal to think that the sun and moon and stars we gaze up at are the same objects that have been observed for millenia, by everyone in the history of humanity from cavemen to Aristotle to Jesus to George Washington.
    -------------
    527 40 I wonder if America's internet is censored in a similar way that North Korea's is, but we have no idea of it happening.
    -------------
    1510 131 Kenny's family is poor because they're always paying for his funeral.
    -------------
    43 1 If I was as careful with my whole paycheck as I am with my last $20 I'd be a whole lot better off
    -------------
    162 10 Black hair ties are probably the most popular bracelets in the world.
    -------------
    107 6 The best answer to the interview question "What is your greatest weakness?" is "interviews".
    -------------
    127 8 Surfing the internet without ads feels like a summer evening without mosquitoes
    -------------
    159 12 I wonder if Superman ever put a pair of glasses on Lois Lane's dog, and she was like "what's this Clark? Did you get me a new dog?"
    -------------
    21 0 Sitting on a cold toilet seat or a warm toilet seat both suck for different reasons.
    -------------
    1414 157 My life is really like Rihanna's song, "just work work work work work" and the rest of it I can't really understand.
    -------------
    222 22 I'm honestly slightly concerned how often Reddit commenters make me laugh compared to my real life friends.
    -------------
    52 3 The world must have been a spookier place altogether when candles and gas lamps were the only sources of light at night besides the moon and the stars.
    -------------
    194 19 I have not been thankful enough in the last few years that the Black Eyed Peas are no longer ever on the radio
    -------------
    18 0 Living on the coast is having the window seat of the land you live on.
    -------------
    18 0 Binoculars are like walkie talkies for the deaf.
    -------------
    28 1 Now that I am a parent of multiple children I have realized that my parents were lying through their teeth when they said they didn't have a favorite.
    -------------
    16 0 I sneer at people who read tabloids, but every time I look someone up on Wikipedia the first thing I look for is what controversies they've been involved in.
    -------------
    1559 233 Kid's menus at restaurants should be smaller portions of the same adult dishes at lower prices and not the junk food that they usually offer.
    -------------
    1426 213 Eventually once all phones are waterproof we'll be able to push people into pools again
    -------------
    61 5 Myspace is so outdated that jokes about it being outdated has become outdated
    -------------
    52 4 As a kid, seeing someone step on a banana peel and not slip was a disappointment.
    -------------
    90 9 Yahoo!® is the RadioShack® of the Internet.
    -------------
    34 2 People who "tell it like it is" rarely do so to say something nice
    -------------
    39 3 Closing your eyes after turning off your alarm is a very dangerous game.
    -------------
    39 3 Your known 'first word' is the first word your parents heard you speak. In reality, it may have been a completely different word you said when you were alone.
    -------------
    87 10 "Smells Like Teen Spirit" is as old to listeners of today as "Yellow Submarine" was to listeners of 1991.
    -------------
    239 36 if an ocean didnt stop immigrants from coming to America what makes us think a wall will?
    -------------
    22 1 The phonebook was the biggest invasion of privacy that everyone was oddly ok with.
    -------------
    57 6 I'm actually the most productive when I procrastinate because I'm doing everything I possibly can to avoid the main task at hand.
    -------------
    57 6 You will never feel how long time is until you have allergies and snot slowly dripping out of your nostrils, while sitting in a classroom with no tissues.
    -------------

We can view the ordering visually by plotting the posterior mean and bounds, and sorting by the lower bound. In the plot below, notice that the left error-bar is sorted (as we suggested this is the best way to determine an ordering), so the means, indicated by dots, do not follow any strong pattern.

```python
r_order = order[::-1][-40:]
plt.errorbar( posterior_mean[r_order], np.arange( len(r_order) ),
               xerr=std_err[r_order], capsize=0, fmt="o",
                color = "#7A68A6")
plt.xlim( 0.3, 1)
plt.yticks( np.arange( len(r_order)-1,-1,-1 ), map( lambda x: x[:30].replace("\n",""), ordered_contents) );
```

In the graphic above, you can see why sorting by mean would be sub-optimal.

### Extension to Starred rating systems

The above procedure works well for upvote-downvotes schemes, but what about systems that use star ratings, e.g. 5 star rating systems. Similar problems apply with simply taking the average: an item with two perfect ratings would beat an item with thousands of perfect ratings, but a single sub-perfect rating.

We can consider the upvote-downvote problem above as binary: 0 is a downvote, 1 if an upvote. A $N$-star rating system can be seen as a more continuous version of above, and we can set $n$ stars rewarded is equivalent to rewarding $\frac{n}{N}$. For example, in a 5-star system, a 2 star rating corresponds to 0.4. A perfect rating is a 1. We can use the same formula as before, but with $a,b$ defined differently:

$$ \frac{a}{a + b} - 1.65\sqrt{ \frac{ab}{ (a+b)^2(a + b +1 ) } }$$

where

\begin{align}
& a = 1 + S \\\\
& b = 1 + N - S \\\\
\end{align}

where $N$ is the number of users who rated, and $S$ is the sum of all the ratings, under the equivalence scheme mentioned above.

##### Example: Counting Github stars

What is the average number of stars a Github repository has? How would you calculate this? There are over 6 million respositories, so there is more than enough data to invoke the Law of Large numbers. Let's start pulling some data. TODO

### Conclusion

While the Law of Large Numbers is cool, it is only true so much as its name implies: with large sample sizes only. We have seen how our inference can be affected by not considering *how the data is shaped*.

1. By (cheaply) drawing many samples from the posterior distributions, we can ensure that the Law of Large Number applies as we approximate expected values (which we will do in the next chapter).

2. Bayesian inference understands that with small sample sizes, we can observe wild randomness. Our posterior distribution will reflect this by being more spread rather than tightly concentrated. Thus, our inference should be correctable.

3. There are major implications of not considering the sample size, and trying to sort objects that are unstable leads to pathological orderings. The method provided above solves this problem.

### Appendix

##### Derivation of sorting submissions formula

Basically what we are doing is using a Beta prior (with parameters $a=1, b=1$, which is a uniform distribution), and using a Binomial likelihood with observations $u, N = u+d$. This means our posterior is a Beta distribution with parameters $a' = 1 + u, b' = 1 + (N - u) = 1+d$. We then need to find the value, $x$, such that 0.05 probability is less than $x$. This is usually done by inverting the CDF ([Cumulative Distribution Function](http://en.wikipedia.org/wiki/Cumulative_Distribution_Function)), but the CDF of the beta, for integer parameters, is known but is a large sum [3].

We instead use a Normal approximation. The mean of the Beta is $\mu = a'/(a'+b')$ and the variance is

$$\sigma^2 = \frac{a'b'}{ (a' + b')^2(a'+b'+1) }$$

Hence we solve the following equation for $x$ and have an approximate lower bound.

$$ 0.05 = \Phi\left( \frac{(x - \mu)}{\sigma}\right) $$

$\Phi$ being the [cumulative distribution for the normal distribution](http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution)

##### Exercises

1\. How would you estimate the quantity $E\left[ \cos{X} \right]$, where $X \sim \text{Exp}(4)$? What about $E\left[ \cos{X} | X \lt 1\right]$, i.e. the expected value *given* we know $X$ is less than 1? Would you need more samples than the original samples size to be equally accurate?

```python
## Enter code here
import scipy.stats as stats
exp = stats.expon( scale=4 )
N = 1e5
X = exp.rvs( int(N) )
```

```python
print(np.cos(X).mean(),np.cos(X[X<1]).mean())
```

    0.05460716184561273 0.8510206510440685

```python
# to check how many more samples are required, calculate var for each then look at sqr
```

2\. The following table was located in the paper "Going for Three: Predicting the Likelihood of Field Goal Success with Logistic Regression" [2]. The table ranks football field-goal kickers by their percent of non-misses. What mistake have the researchers made?

-----

####  Kicker Careers Ranked by Make Percentage
<table><tbody><tr><th>Rank </th><th>Kicker </th><th>Make % </th><th>Number  of Kicks</th></tr><tr><td>1 </td><td>Garrett Hartley </td><td>87.7 </td><td>57</td></tr><tr><td>2</td><td> Matt Stover </td><td>86.8 </td><td>335</td></tr><tr><td>3 </td><td>Robbie Gould </td><td>86.2 </td><td>224</td></tr><tr><td>4 </td><td>Rob Bironas </td><td>86.1 </td><td>223</td></tr><tr><td>5</td><td> Shayne Graham </td><td>85.4 </td><td>254</td></tr><tr><td>… </td><td>… </td><td>…</td><td> </td></tr><tr><td>51</td><td> Dave Rayner </td><td>72.2 </td><td>90</td></tr><tr><td>52</td><td> Nick Novak </td><td>71.9 </td><td>64</td></tr><tr><td>53 </td><td>Tim Seder </td><td>71.0 </td><td>62</td></tr><tr><td>54 </td><td>Jose Cortez </td><td>70.7</td><td> 75</td></tr><tr><td>55 </td><td>Wade Richey </td><td>66.1</td><td> 56</td></tr></tbody></table>

In August 2013, [a popular post](http://bpodgursky.wordpress.com/2013/08/21/average-income-per-programming-language/) on the average income per programmer of different languages was trending. Here's the summary chart: (reproduced without permission, cause when you lie with stats, you gunna get the hammer). What do you notice about the extremes?

------

#### Average household income by programming language

<table >
 <tr><td>Language</td><td>Average Household Income ($)</td><td>Data Points</td></tr>
 <tr><td>Puppet</td><td>87,589.29</td><td>112</td></tr>
 <tr><td>Haskell</td><td>89,973.82</td><td>191</td></tr>
 <tr><td>PHP</td><td>94,031.19</td><td>978</td></tr>
 <tr><td>CoffeeScript</td><td>94,890.80</td><td>435</td></tr>
 <tr><td>VimL</td><td>94,967.11</td><td>532</td></tr>
 <tr><td>Shell</td><td>96,930.54</td><td>979</td></tr>
 <tr><td>Lua</td><td>96,930.69</td><td>101</td></tr>
 <tr><td>Erlang</td><td>97,306.55</td><td>168</td></tr>
 <tr><td>Clojure</td><td>97,500.00</td><td>269</td></tr>
 <tr><td>Python</td><td>97,578.87</td><td>2314</td></tr>
 <tr><td>JavaScript</td><td>97,598.75</td><td>3443</td></tr>
 <tr><td>Emacs Lisp</td><td>97,774.65</td><td>355</td></tr>
 <tr><td>C#</td><td>97,823.31</td><td>665</td></tr>
 <tr><td>Ruby</td><td>98,238.74</td><td>3242</td></tr>
 <tr><td>C++</td><td>99,147.93</td><td>845</td></tr>
 <tr><td>CSS</td><td>99,881.40</td><td>527</td></tr>
 <tr><td>Perl</td><td>100,295.45</td><td>990</td></tr>
 <tr><td>C</td><td>100,766.51</td><td>2120</td></tr>
 <tr><td>Go</td><td>101,158.01</td><td>231</td></tr>
 <tr><td>Scala</td><td>101,460.91</td><td>243</td></tr>
 <tr><td>ColdFusion</td><td>101,536.70</td><td>109</td></tr>
 <tr><td>Objective-C</td><td>101,801.60</td><td>562</td></tr>
 <tr><td>Groovy</td><td>102,650.86</td><td>116</td></tr>
 <tr><td>Java</td><td>103,179.39</td><td>1402</td></tr>
 <tr><td>XSLT</td><td>106,199.19</td><td>123</td></tr>
 <tr><td>ActionScript</td><td>108,119.47</td><td>113</td></tr>
</table>

### References

1. Wainer, Howard. *The Most Dangerous Equation*. American Scientist, Volume 95.
2. Clarck, Torin K., Aaron W. Johnson, and Alexander J. Stimpson. "Going for Three: Predicting the Likelihood of Field Goal Success with Logistic Regression." (2013): n. page. [Web](http://www.sloansportsconference.com/wp-content/uploads/2013/Going%20for%20Three%20Predicting%20the%20Likelihood%20of%20Field%20Goal%20Success%20with%20Logistic%20Regression.pdf). 20 Feb. 2013.
3. http://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function

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

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

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

<style>
    img{
        max-width:800px}
</style>


# Exercise: beam bending with the Galerkin method

The differential equation for beam bending

$$
(EI w'')'' - q = 0 \text{ with } q = 0
$$

can be integrated analytically by specifying the boundary conditions

$$
w(0) = 0\\
w'(0) = 0\\
EIw''(L)=M_0\\
EIw'''(L) = -F_0
$$

to yield the deflection solution ("Biegelinie"):

$$
w(x) = \frac{F_0L^3}{3EI} \left[ 1 - \frac{3}{2}\frac{L-x}{L} + \frac{1}{2} \left( \frac{L-x}{L}\right)^3 \right] + \frac{M_0L^2}{2EI} \left[1 - 2\frac{L-x}{L} + \left( \frac{L-x}{L}\right)^2 \right]
$$

Or you simply take the solutions for a force-loaded and a moment-loaded beam from a table and add them up. We now seek to approximate this solution numerically using Galerkin's method.

Additionally, for simplicity we assume proportionality between $F_0$ and $M_0$:

$$
M_0 = c F_0 L \text{ with } c = \text{const.}
$$

```python
import numpy as np #numerical methods
import sympy as sp #symbolic operations
import matplotlib.pyplot as plt #plotting
sp.init_printing(use_latex='mathjax') #makes sympy output look nice

#Some plot settings
plt.style.use('seaborn-deep')
plt.rcParams['lines.linewidth']= 2.0
plt.rcParams['lines.color']= 'black'
plt.rcParams['legend.frameon']=True
plt.rcParams['figure.figsize'] = (8, 6)
plt.rcParams['font.family'] = 'serif'
plt.rcParams['legend.fontsize']=14
plt.rcParams['font.size'] = 14
plt.rcParams['axes.spines.right'] = False
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.left'] = True
plt.rcParams['axes.spines.bottom'] = True
plt.rcParams['axes.axisbelow'] = True
```

```python
#Defining the geometric an material characteristics as symbolic quantities
L,F,c,EI,x = sp.symbols('L F_0 c EI x')
```

```python
#Analytical solution to deflection
def deflection_analytical():
    a = (L-x)/L
    f = F*L**3/EI
    force_contribution = f/3 * (1 - 3*a/2 + a**3/2)
    moment_contribution = c*f/2 * (1 - 2*a + a**2)
    return force_contribution + moment_contribution
```

```python
deflection_analytical()#check definition
```

$$\frac{F_{0} L^{3} c}{2 EI} \left(1 - \frac{2}{L} \left(L - x\right) + \frac{1}{L^{2}} \left(L - x\right)^{2}\right) + \frac{F_{0} L^{3}}{3 EI} \left(1 - \frac{3 \left(L - x\right)}{2 L} + \frac{\left(L - x\right)^{3}}{2 L^{3}}\right)$$

Now, let's plot the analytical solution. For that purpose, we use some Python magic ("lambdify"). We sample the analytical solution for $x \in [0,L]$ at 100 points and plot the dimensionless deflection over the dimensionless length.

```python
defl_c0 = sp.lambdify(x, deflection_analytical().subs(c,0), modules=['numpy'])#c=0
defl_c1 = sp.lambdify(x, deflection_analytical().subs(c,1), modules=['numpy'])#c=1
#For the variable x the function deflection_analytical() will obtain something

x_vals = np.linspace(0, 1, 100)*L #This something is x going from 0 to L
analytical_c0 = defl_c0(x_vals) #We calculate the solution by passing x = [0,...,L] to deflection_analytical
analytical_c1 = defl_c1(x_vals) #We calculate the solution by passing x = [0,...,L] to deflection_analytical

plt.plot(x_vals/L, analytical_c0/(L**3*F)*EI,label='$c=0$: $M_0 = 0$')
plt.plot(x_vals/L, analytical_c1/(L**3*F)*EI,label='$c=1$: $M_0 = F_0 L$')
plt.xlabel('$x\ /\ L$')
plt.ylabel('$w\ /\ L^3 F_0  EI^{-1}$')
plt.legend()
```

## Trigonometric Ansatz

Let's try the approximation

$$
    \tilde{w} = a \left[ 1 - \cos \left(\frac{\pi x}{4L}\right) \right]
$$

of the Ansatz function and the same expression but with a different coefficient for the test function (Bubnov-Galerkin)

$$
    \eta = b \left[ 1 - \cos \left(\frac{\pi x}{4L}\right) \right]
$$

Note, that in contrast to all previous examples we will only determine one value, since by definition the weak form has to hold for arbitrary $b$.

```python
a, b = sp.symbols('a b')#Defining the free values as new symbols
```

```python
def ansatz_function(): #\phi or \psi
    return (1-sp.cos(sp.pi/4*x/L))

def deflection_ansatz():
    return a*ansatz_function() #defining the approximate solution with the unknown coefficients

def test_ansatz():
    return b*ansatz_function()
```

The Galerkin scheme starts from the orthogonality condition / weighted-average formulation

$$
    0 = \int \limits_0^L \eta(x) \left[(EI\tilde{w}'')''\right]\,\text{d}x
$$
and proceeds with a two-fold partial integration and the use of the essential boundary conditions to arrive at (compare lecture notes for details):

$$
0 = \int \limits_0^L \left( EIw'' \eta''\right) \,\text{d} x -F_0 \eta(L) - M_0 \eta'(L)
$$

Generally, we had $\eta(x) = \sum \limits_{i=1}^n b_i \psi_i(x)$. Here we have $n=1$, and therefore

$$
    \eta = b\psi\, , \text{ with   } \psi = \left[ 1 - \cos \left(\frac{\pi x}{4L}\right) \right]
$$

Substitution into the weak form yields

$$
0 = b \left[ \int \limits_0^L \left( EIw'' \psi''\right) \,\text{d} x -F_0 \psi(L) - M_0 \psi'(L) \right] \ \forall b \neq 0
$$

Hence, we only solve one equation in this case!

```python
weak_form = sp.integrate(EI * deflection_ansatz().diff(x,2) * ansatz_function().diff(x,2) , (x,0,L))
weak_form -= F * ansatz_function().subs(x,L)
weak_form -= c*F*L*ansatz_function().diff(x,1).subs(x,L)
```

We can simply solve this equation for the free coefficient $a$:

```python
coefficients = sp.solve(weak_form,a)
```

```python
coefficients[0]
```

$$\begin{cases} \frac{32 F_{0} L^{3}}{\pi^{4} EI} \left(\sqrt{2} \pi c - 4 \sqrt{2} + 8\right) & \text{for}\: \frac{\pi}{4 L} = 0 \\\frac{64 F_{0} L^{3}}{\pi^{3} EI \left(2 + \pi\right)} \left(\sqrt{2} \pi c - 4 \sqrt{2} + 8\right) & \text{otherwise} \end{cases}$$

```python
solution = deflection_ansatz().subs(a,coefficients[0]).simplify()
solution
```

$$\begin{cases} \frac{32 F_{0} L^{3}}{\pi^{4} EI} \left(- \cos{\left (\frac{\pi x}{4 L} \right )} + 1\right) \left(\sqrt{2} \pi c - 4 \sqrt{2} + 8\right) & \text{for}\: \frac{\pi}{4 L} = 0 \\\frac{64 F_{0} L^{3}}{\pi^{3} EI \left(2 + \pi\right)} \left(- \cos{\left (\frac{\pi x}{4 L} \right )} + 1\right) \left(\sqrt{2} \pi c - 4 \sqrt{2} + 8\right) & \text{otherwise} \end{cases}$$

Now we're ready to plot the result and compare it to the analytical solution.

```python
#We first substite the now known Ansatz free values into our Ansatz
z = sp.symbols('z')
w_numerical_c0 = solution.subs([(c,0),(x,z*L)])
w_numerical_c1 = solution.subs([(c,1),(x,z*L)])
#We also made the coordinate dimensionless (x/L --> z) because of sympy problems

lam_x_num_c0 = sp.lambdify(z, w_numerical_c0, modules=['numpy'])
lam_x_num_c1 = sp.lambdify(z, w_numerical_c1, modules=['numpy'])
#For the variable x the expression w_numerical will be given something
z_vals = np.linspace(0, 1,100) #This something is z from 0 to 1
numerical_c0 = lam_x_num_c0(z_vals) #We calculate the solution by passing x = [0,...,L] to deflection_analytical
numerical_c1 = lam_x_num_c1(z_vals) #We calculate the solution by passing x = [0,...,L] to deflection_analytical

plt.plot(x_vals/L, analytical_c0/(L**3*F)*EI,label='$c=0$: $M_0 = 0$, analytical')
plt.plot(x_vals/L, analytical_c1/(L**3*F)*EI,label='$c=1$: $M_0 = F_0 L$, analytical')
plt.plot(z_vals, numerical_c0/(L**3*F)*EI,label='$c=0$: $M_0 = 0$, numerical',ls='--')
plt.plot(z_vals, numerical_c1/(L**3*F)*EI,label='$c=1$: $M_0 = F_0 L$, numerical',ls='--')
plt.legend()
plt.xlabel('$x\ /\ L$')
plt.ylabel('$w\ /\ L^3 F_0  EI^{-1}$')
plt.tight_layout()
plt.savefig('beam_galerkin.pdf')
```

```python
print("Maximum absolute error for c=0: ", np.max(np.abs(analytical_c0/(L**3*F)*EI - numerical_c0/(L**3*F)*EI)))
print("Maximum absolute error for c=1: ", np.max(np.abs(analytical_c1/(L**3*F)*EI - numerical_c1/(L**3*F)*EI)))
```

    Maximum absolute error for c=0:  0.0584504403529307
    Maximum absolute error for c=1:  0.0358657946638069

We can also plot and compare the bending moment. Let's first find the analytical expression by symbolically differentiating the deflection expression twice to obtain $M(x) = -EI w''(x)$:

```python
#analytical bending moment
moment_analytical = -deflection_analytical().diff(x,2)*EI
#numerical bending moment
moment_numerical = -solution.diff(x,2)*EI

#create lambdas for plotting along dimensionless length z
lam_x_analyt_c0 = sp.lambdify(z, moment_analytical.subs([(x,z*L),(c,0)]), modules=['numpy'])
lam_x_num_c0 = sp.lambdify(z, moment_numerical.subs([(x,z*L),(c,0)]), modules=['numpy'])
lam_x_analyt_c1 = sp.lambdify(z, moment_analytical.subs([(x,z*L),(c,1)]), modules=['numpy'])
lam_x_num_c1 = sp.lambdify(z, moment_numerical.subs([(x,z*L),(c,1)]), modules=['numpy'])

z_vals = np.linspace(0, 1,100)
analytical_c0 = lam_x_analyt_c0(z_vals)
numerical_c0 = lam_x_num_c0(z_vals)
analytical_c1 = lam_x_analyt_c1(z_vals)
numerical_c1 = lam_x_num_c1(z_vals)

#plot
plt.plot(x_vals/L, analytical_c0/(L*F),label='$c=0$: $M_0 = 0$, analytical')
plt.plot(z_vals, numerical_c0/(L*F),label='$c=0$: $M_0 = 0$, numerical',ls='--')
plt.plot(x_vals/L, analytical_c1/(L*F),label='$c=1$: $M_0 = F_0L$, analytical')
plt.plot(z_vals, numerical_c1/(L*F),label='$c=1$: $M_0 = F_0L$, numerical',ls='--')
plt.xlabel('$x\ /\ L$')
plt.ylabel('$M\ /\ F_0 L$')
plt.legend()
plt.tight_layout()
plt.savefig('beam_galerkin_moment.pdf')
```

```python
print("Maximum absolute error in bending moment for c=0: ", np.max(np.abs(analytical_c0/(L*F) - numerical_c0/(L*F))))
print("Maximum absolute error in bending moment for c=1: ", np.max(np.abs(analytical_c1/(L*F) - numerical_c1/(L*F))))
```

    Maximum absolute error in bending moment for c=0:  0.419754533346493
    Maximum absolute error in bending moment for c=1:  0.319540138582482

*Tasks:*
- Why to the moment predictions seem worse compared to the other examples?
- What is the physical significance of the terms in the weak form?
- What happens with a full polynomial Ansatz containing orders 3 and 5?

```python
work_balance=sp.integrate(-moment_numerical.subs(c,1)*ansatz_function().diff(x,2),(x,0,L))- F * ansatz_function().subs(x,L) - F*L*ansatz_function().diff(x,1).subs(x,L)
```

```python
work_balance.simplify()
```

$$0$$