import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

"""
Explanation: Fully Connected Feed-Forward Network
In this notebook we will play with Feed-Forward FC-NN (Fully Connected Neural Network) for a classification task: 
Image Classification on MNIST Dataset
RECALL
In the FC-NN, the output of each layer is computed using the activations from the previous one, as follows:
$$h_{i} = \sigma(W_i h_{i-1} + b_i)$$
where ${h}_i$ is the activation vector from the $i$-th layer (or the input data for $i=0$), ${W}_i$ and ${b}_i$ are  the weight matrix and the bias vector for the $i$-th layer, respectively. 
<br><rb>
$\sigma(\cdot)$ is the activation function. In our example, we will use the ReLU activation function for the hidden layers and softmax for the last layer.
To regularize the model, we will also insert a Dropout layer between consecutive hidden layers. 
Dropout works by “dropping out” some unit activations in a given layer, that is setting them to zero with a given probability.
Our loss function will be the categorical crossentropy.
Model definition
Keras supports two different kind of models: the Sequential model and the Graph model. The former is used to build linear stacks of layer (so each layer has one input and one output), and the latter supports any kind of connection graph.
In our case we build a Sequential model with three Dense (aka fully connected) layers, with some Dropout. Notice that the output layer has the softmax activation function. 
The resulting model is actually a function of its own inputs implemented using the Keras backend. 
We apply the binary crossentropy loss and choose SGD as the optimizer. 
Please remind that Keras supports a variety of different optimizers and loss functions, which you may want to check out.
End of explanation
"""


from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD

nb_classes = 10

# FC@512+relu -> FC@512+relu -> FC@nb_classes+softmax
# ... your Code Here

# %load ../solutions/sol_321.py

from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dense(512, activation='relu'))
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.001), 
              metrics=['accuracy'])

"""
Explanation: Introducing ReLU
The ReLu function is defined as $f(x) = \max(0, x),$ [1]
A smooth approximation to the rectifier is the analytic function: $f(x) = \ln(1 + e^x)$
which is called the softplus function.
The derivative of softplus is $f'(x) = e^x / (e^x + 1) = 1 / (1 + e^{-x})$, i.e. the logistic function.
[1] http://www.cs.toronto.edu/~fritz/absps/reluICML.pdf by G. E. Hinton 
Note: Keep in mind this function as it is heavily used in CNN
End of explanation
"""


from keras.datasets import mnist
from keras.utils import np_utils

(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train.shape

X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype("float32")
X_test = X_test.astype("float32")

# Put everything on grayscale
X_train /= 255
X_test /= 255

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, 10)
Y_test = np_utils.to_categorical(y_test, 10)

"""
Explanation: Data preparation (keras.dataset)
We will train our model on the MNIST dataset, which consists of 60,000 28x28 grayscale images of the 10 digits, along with a test set of 10,000 images. 

Since this dataset is provided with Keras, we just ask the keras.dataset model for training and test data.
We will:

download the data
reshape data to be in vectorial form (original data are images)
normalize between 0 and 1.

The binary_crossentropy loss expects a one-hot-vector as input, therefore we apply the to_categorical function from keras.utilis to convert integer labels to one-hot-vectors.
End of explanation
"""


from sklearn.model_selection import train_test_split

X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train)

X_train[0].shape

plt.imshow(X_train[0].reshape(28, 28))

print(np.asarray(range(10)))
print(Y_train[0].astype('int'))

plt.imshow(X_val[0].reshape(28, 28))

print(np.asarray(range(10)))
print(Y_val[0].astype('int'))

"""
Explanation: Split Training and Validation Data
End of explanation
"""


network_history = model.fit(X_train, Y_train, batch_size=128, 
                            epochs=2, verbose=1, validation_data=(X_val, Y_val))

"""
Explanation: Training
Having defined and compiled the model, it can be trained using the fit function. We also specify a validation dataset to monitor validation loss and accuracy.
End of explanation
"""


import matplotlib.pyplot as plt
%matplotlib inline

def plot_history(network_history):
    plt.figure()
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.plot(network_history.history['loss'])
    plt.plot(network_history.history['val_loss'])
    plt.legend(['Training', 'Validation'])

    plt.figure()
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.plot(network_history.history['acc'])
    plt.plot(network_history.history['val_acc'])
    plt.legend(['Training', 'Validation'], loc='lower right')
    plt.show()

plot_history(network_history)

"""
Explanation: Plotting Network Performance Trend
The return value of the fit function is a keras.callbacks.History object which contains the entire history of training/validation loss and accuracy, for each epoch. We can therefore plot the behaviour of loss and accuracy during the training phase.
End of explanation
"""


# Your code here
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.001), 
              metrics=['accuracy'])
network_history = model.fit(X_train, Y_train, batch_size=128, 
                            epochs=2, verbose=1, validation_data=(X_val, Y_val))

"""
Explanation: After 2 epochs, we get a ~88% validation accuracy. 

If you increase the number of epochs, you will get definitely better results.

Quick Exercise:
Try increasing the number of epochs (if you're hardware allows to)
End of explanation
"""


from keras.layers.core import Dropout

## Pls note **where** the `K.in_train_phase` is actually called!!
Dropout??

from keras import backend as K

K.in_train_phase?

"""
Explanation: Introducing the Dropout Layer
The dropout layers have the very specific function to drop out a random set of activations in that layers by setting them to zero in the forward pass. Simple as that. 
It allows to avoid overfitting but has to be used only at training time and not at test time. 
```python
keras.layers.core.Dropout(rate, noise_shape=None, seed=None)
```
Applies Dropout to the input.
Dropout consists in randomly setting a fraction rate of input units to 0 at each update during training time, which helps prevent overfitting.
Arguments

rate: float between 0 and 1. Fraction of the input units to drop.
noise_shape: 1D integer tensor representing the shape of the binary dropout mask that will be multiplied with the input. For instance, if your inputs have shape  (batch_size, timesteps, features) and you want the dropout mask to be the same for all timesteps, you can use noise_shape=(batch_size, 1, features).
seed: A Python integer to use as random seed.

Note Keras guarantess automatically that this layer is not used in Inference (i.e. Prediction) phase
(thus only used in training as it should be!)
See keras.backend.in_train_phase function
End of explanation
"""


from keras.layers.core import Dropout

# FC@512+relu -> DropOut(0.2) -> FC@512+relu -> DropOut(0.2) -> FC@nb_classes+softmax
# ... your Code Here

# %load ../solutions/sol_312.py

network_history = model.fit(X_train, Y_train, batch_size=128, 
                            epochs=4, verbose=1, validation_data=(X_val, Y_val))
plot_history(network_history)

"""
Explanation: Exercise:
Try modifying the previous example network adding a Dropout layer:
End of explanation
"""


# %load solutions/sol23.py
from keras.callbacks import EarlyStopping

early_stop = EarlyStopping(monitor='val_loss', patience=4, verbose=1)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer=SGD(), 
              metrics=['accuracy'])
    
model.fit(X_train, Y_train, validation_data = (X_test, Y_test), epochs=100, 
          batch_size=128, verbose=True, callbacks=[early_stop]) 

"""
Explanation: If you continue training, at some point the validation loss will start to increase: that is when the model starts to overfit. 

It is always necessary to monitor training and validation loss during the training of any kind of Neural Network, either to detect overfitting or to evaluate the behaviour of the model (any clue on how to do it??)
End of explanation
"""


# We already used `summary`
model.summary()

"""
Explanation: Inspecting Layers
End of explanation
"""


print('Model Input Tensors: ', model.input, end='\n\n')
print('Layers - Network Configuration:', end='\n\n')
for layer in model.layers:
    print(layer.name, layer.trainable)
    print('Layer Configuration:')
    print(layer.get_config(), end='\n{}\n'.format('----'*10))
print('Model Output Tensors: ', model.output)

"""
Explanation: model.layers is iterable
End of explanation
"""


model_truncated = Sequential()
model_truncated.add(Dense(512, activation='relu', input_shape=(784,)))
model_truncated.add(Dropout(0.2))
model_truncated.add(Dense(512, activation='relu'))

for i, layer in enumerate(model_truncated.layers):
    layer.set_weights(model.layers[i].get_weights())

model_truncated.compile(loss='categorical_crossentropy', optimizer=SGD(), 
              metrics=['accuracy'])

# Check
np.all(model_truncated.layers[0].get_weights()[0] == model.layers[0].get_weights()[0])

hidden_features = model_truncated.predict(X_train)

hidden_features.shape

X_train.shape

"""
Explanation: Extract hidden layer representation of the given data
One simple way to do it is to use the weights of your model to build a new model that's truncated at the layer you want to read. 
Then you can run the ._predict(X_batch) method to get the activations for a batch of inputs.
End of explanation
"""


from sklearn.manifold import TSNE

tsne = TSNE(n_components=2)
X_tsne = tsne.fit_transform(hidden_features[:1000]) ## Reduced for computational issues

colors_map = np.argmax(Y_train, axis=1)

X_tsne.shape

nb_classes

np.where(colors_map==6)

colors = np.array([x for x in 'b-g-r-c-m-y-k-purple-coral-lime'.split('-')])
colors_map = colors_map[:1000]
plt.figure(figsize=(10,10))
for cl in range(nb_classes):
    indices = np.where(colors_map==cl)
    plt.scatter(X_tsne[indices,0], X_tsne[indices, 1], c=colors[cl], label=cl)
plt.legend()
plt.show()

"""
Explanation: Hint: Alternative Method to get activations
(Using keras.backend function on Tensors)
python
def get_activations(model, layer, X_batch):
    activations_f = K.function([model.layers[0].input, K.learning_phase()], [layer.output,])
    activations = activations_f((X_batch, False))
    return activations

Generate the Embedding of Hidden Features
End of explanation
"""


from bokeh.plotting import figure, output_notebook, show

output_notebook()

p = figure(plot_width=600, plot_height=600)

colors = [x for x in 'blue-green-red-cyan-magenta-yellow-black-purple-coral-lime'.split('-')]
colors_map = colors_map[:1000]
for cl in range(nb_classes):
    indices = np.where(colors_map==cl)
    p.circle(X_tsne[indices, 0].ravel(), X_tsne[indices, 1].ravel(), size=7, 
             color=colors[cl], alpha=0.4, legend=str(cl))

# show the results
p.legend.location = 'bottom_right'
show(p)

"""
Explanation: Using Bokeh (Interactive Chart)
End of explanation
"""


from sklearn.manifold import MDS

## Your code here

"""
Explanation: Note: We used default TSNE parameters. Better results can be achieved by tuning TSNE Hyper-parameters
Exercise 1:
Try with a different algorithm to create the manifold
End of explanation
"""


## Your code here

## Try using the `get_activations` function relying on keras backend
def get_activations(model, layer, X_batch):
    activations_f = K.function([model.layers[0].input, K.learning_phase()], [layer.output,])
    activations = activations_f((X_batch, False))
    return activations

"""
Explanation: Exercise 2:
Try extracting the Hidden features of the First and the Last layer of the model
End of explanation
"""


