# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: PySpark
#     language: ''
#     name: pysparkkernel
# ---

# ## maggy - MNIST Example
# ---
# Created: 24/04/2019

# This notebook illustrates the usage of the maggy framework for asynchronous hyperparameter optimization on the famous MNIST dataset.  
#
# In this specific example we are using random search over three parameters and we are deploying the median early stopping rule in order to make use of the asynchrony of the framework. The Median Stopping Rule implements the simple strategy of stopping a trial if its performance falls below the median of other trials at similar points in time.
#
# We are using Keras for this example. This notebook works with any Spark cluster given that you are using maggy 0.1. In future versions we will add functionality that relies on Hopsworks.
#
# This notebook has been tested with TensorFlow 1.11.0 and Spark 2.4.0.  
# Requires Python 3.6 or higher.

# ### 1. Spark Session

# Make sure you have a running Spark Session/Context available. On Hopsworks just execute a simple command to start the spark application.

print("Hello World!")

# ### 2. Searchspace definition
#
#

# We want to conduct random search for the MNIST example on three hyperparameters: Kernel size, pooling size and dropout rate. Hence, we have two continuous integer valued parameters and one double valued parameter.

# +
from maggy import Searchspace

# The searchspace can be instantiated with parameters
sp = Searchspace(kernel=('INTEGER', [2, 8]), pool=('INTEGER', [2, 8]))

# Or additional parameters can be added one by one
sp.add('dropout', ('DOUBLE', [0.01, 0.99]))
# -

# ### 3. Model training definition
#
# The programming model is that you wrap the code containing the model training inside a wrapper function. Inside that wrapper function provide all imports and parts that make up your experiment.
#
# There are several requirements for this wrapper function:
#
# 1. The function should take the hyperparameters as arguments, plus one additional parameter `reporter` which is needed for reporting the current metric to the experiment driver.
# 2. The function should return the metric that you want to optimize for. This should coincide with the metric being reported in the Keras callback (see next point).
# 3. In order to leverage on the early stopping capabilities of maggy, you need to make use of the maggy reporter API. By including the reporter in your training loop, you are telling maggy which metric to report back to the experiment driver for optimization and to check for early stopping. It is as easy as adding `reporter.broadcast(metric=YOUR_METRIC)` for example at the end of your epoch or batch training step and adding a `reporter` argument to your function signature. If you are not writing your own training loop you can use the pre-written Keras callbacks:
#     - KerasBatchEnd
#     - KerasEpochEnd  
# (Please see documentation for a detailed explanation.)
#
# We are going to use the `KerasBatchEnd` callback to report back the accuracy after each batch. However, note that in the BatchEnd callback we have only access to training accuracy since validation after each batch would be too expensive.
#

from maggy import experiment
from maggy.callbacks import KerasBatchEnd


# Definition of the training wrapper function:
# (maggy specific parts are highlighted with comments and correspond to the three points described above.)

#########
### maggy: hyperparameters as arguments and including the reporter
#########
def keras(kernel, pool, dropout, reporter):
    from tensorflow.python import keras
    import tensorflow as tf
    from tensorflow.python.keras.datasets import mnist
    from tensorflow.python.keras.models import Sequential
    from tensorflow.python.keras.layers import Dense, Dropout, Flatten
    from tensorflow.python.keras.layers import Conv2D, MaxPooling2D
    from tensorflow.python.keras.callbacks import TensorBoard

    from tensorflow.python.keras import backend as K
    import math

    batch_size = 512
    num_classes = 10
    epochs = 1

    # Input image dimensions
    img_rows, img_cols = 28, 28

    # The data, shuffled and split between train and test sets
    (x_train, y_train), (x_test, y_test) = mnist.load_data()

    if K.image_data_format() == 'channels_first':
        x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
        x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
        input_shape = (1, img_rows, img_cols)
    else:
        x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
        x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
        input_shape = (img_rows, img_cols, 1)

    x_train = x_train.astype('float32')
    x_test = x_test.astype('float32')
    x_train /= 255
    x_test /= 255
    print('x_train shape:', x_train.shape)
    print(x_train.shape[0], 'train samples')
    print(x_test.shape[0], 'test samples')

    # Convert class vectors to binary class matrices
    y_train = keras.utils.to_categorical(y_train, num_classes)
    y_test = keras.utils.to_categorical(y_test, num_classes)

    model = Sequential()
    model.add(Conv2D(32, kernel_size=(kernel, kernel),
                     activation='relu',
                     input_shape=input_shape))
    model.add(Conv2D(64, (kernel, kernel), activation='relu'))
    model.add(MaxPooling2D(pool_size=(pool, pool)))
    model.add(Dropout(dropout))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(dropout))
    model.add(Dense(num_classes, activation='softmax'))

    opt = keras.optimizers.Adadelta(1.0)

    model.compile(loss=keras.losses.categorical_crossentropy,
                  optimizer=opt,
                  metrics=['accuracy'])
    #########
    ### maggy: REPORTER API through keras callback
    #########
    callbacks = [KerasBatchEnd(reporter, metric='acc')]

    model.fit(x_train, y_train,
              batch_size=batch_size,
              callbacks=callbacks, # add callback
              epochs=epochs,
              verbose=1,
              validation_data=(x_test, y_test))
    score = model.evaluate(x_test, y_test, verbose=0)
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])
    
    #########
    ### maggy: return the metric to be optimized, test accuracy in this case
    #########
    return score[1]


# ### 4. Launching the experiment
#
# Finally, we are ready to launch the maggy experiment.
# There are a variety of parameters to specify, some of which are optional:
# 1. `map_fun`: your previously specified training wrapper function
# 2. `searchspace`: the searchspace object
# 3. `optimizer`: the optimization algorithm to be used (only 'randomsearch' available at the moment)
# 4. `direction`: maximize or minimize the specified metric
# 5. `num_trials`: number of different parameter combinations to be evaluated
# 6. `name`: an experiment name
# 7. `hb_interval`: Time in seconds between the heartbeat messages with the metric to the experiment driver. A sensible value is not much smaller than the frequency in which your training loop updates the metric. So using the KerasBatchEnd reporter callback, it does not make sense having a much smaller interval than the amount of time a batch takes to be processed.
# 8. `es_interval`: Interval in seconds, specifying how often the currently running trials should be checked for early stopping. Should be bigger than the `hb_interval`.
# 9. `es_min`: Minimum number of trials to be finished before starting to check for early stopping. For example, the median stopping rule implements the simple strategy of stopping a trial if its performance falls below the median of finished trials at similar points in time. We only want to start comparing to the median once there are several trials finished.

result = experiment.lagom(map_fun=keras, 
                           searchspace=sp, 
                           optimizer='randomsearch', 
                           direction='max', 
                           num_trials=15, 
                           name='MNIST', 
                           hb_interval=5, 
                           es_interval=300,
                           es_min=5
                          )

# To observe the progress, you can check the sterr of the spark executors. TensorBoard support is added in the coming version.

StarcoderdataJupyterScriptsDedupFiltered