# imports
import h2o 
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.grid.grid_search import H2OGridSearch

# display matplotlib graphics in notebook
%matplotlib inline

# start and connect to h2o server
h2o.init()

"""
Explanation: License

Copyright (C) 2017 J. Patrick Hall, jphall@gwu.edu
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

MLP Starter Kit for Kaggle Digit Recognizer
Imports and inits
End of explanation
"""


# load clean data
path = '../data/'

# define input variable measurement levels 
# strings automatically parsed as enums (nominal)
# numbers automatically parsed as numeric
col_types = {'label': 'enum'}

train = h2o.import_file(path=path + 'train.csv', col_types=col_types) # multi-threaded import
test = h2o.import_file(path=path + 'test.csv')

train.describe()

# split into 40% training, 30% validation, and 30% test
train, valid = train.split_frame([0.8])

# assign target and inputs
y = 'label'
X = [name for name in train.columns if name != y]
print(y)
print(X)

# set target to factor - for multinomial classification
train[y] = train[y].asfactor()
valid[y] = valid[y].asfactor()

"""
Explanation: Import data
End of explanation
"""


# NN with random hyperparameter search
# train many different NN models with random hyperparameters
# and select best model based on validation error

# define random grid search parameters
hyper_parameters = {'hidden': [[500, 500], [250, 250, 250, 250], [1000, 500], [500, 1000], [1000, 500, 250], [1000, 1000]],
                    'l1':[s/1e4 for s in range(0, 1000, 100)],
                    'l2':[s/1e5 for s in range(0, 1000, 100)],
                    'input_dropout_ratio':[s/1e2 for s in range(0, 20, 2)]}

# define search strategy
search_criteria = {'strategy':'RandomDiscrete',
                   'max_models':100,
                   'max_runtime_secs':60000}

# initialize grid search
gsearch = H2OGridSearch(H2ODeepLearningEstimator,
                        hyper_params=hyper_parameters,
                        search_criteria=search_criteria)

# execute training w/ grid search
gsearch.train(x=X,
              y=y,
              training_frame=train,
              validation_frame=valid, 
              activation='RectifierWithDropout', 
              epochs=8000, 
              stopping_rounds=20,
              sparse=True, # handles data w/ many zeros more efficiently                     
              ignore_const_cols=True,              
              adaptive_rate=True)

# view detailed results at http://host:ip/flow/index.html

"""
Explanation: Train MLP using random grid search
End of explanation
"""


# show grid search results
gsearch.show()

# select best model
mnist_model = gsearch.get_grid()[0]

# print model information
mnist_model

# hit-ratio = ((TP + TN)/(TP + TN + FP + FN)), for two-classes


"""
Explanation: Select best model
End of explanation
"""


"""

best_model = H2ODeepLearningEstimator(
                activation = 'RectifierWithDropout', 
                hidden = [1024,1024,2048],
                epochs = 8000, 
                l1 = 1e-5, 
                input_dropout_ratio = 0.2,
                train_samples_per_iteration = -1, 
                classification_stop = -1)
                
"""

"""
Explanation: Best known H2O MLP for MNIST

Can you train it?
End of explanation
"""


"""
# create time stamp
import re
import time
time_stamp = re.sub('[: ]', '_', time.asctime())

# score unlabeled test data
sub = mnist_model.predict(test)

# save file for submission
sub = sub['predict']

import numpy as np # create ID column
sub = h2o.H2OFrame(np.arange(1, 28001)).cbind(sub) 

sub.columns = ['ImageId', 'Label']

print(sub.head())

sub_fname = '../data/submission_' + str(time_stamp) + '.csv'
h2o.download_csv(sub, sub_fname)
"""

# shutdown h2o - this will erase all your unsaved frames and models in H2O
h2o.cluster().shutdown(prompt=True)

"""
Explanation: Create Submission
End of explanation
"""


