Copyright 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.
Based on: Craven, Mark W. and Shavlik, Jude W. Extracting tree structured representations of trained networks. Advances in Neural Information Processing Systems, pp. 24–30, 1996.
https://papers.nips.cc/paper/1152-extracting-tree-structured-representations-of-trained-networks.pdf
Requires GraphViz
For MacOS: brew install graphviz
In [1]:
# imports
import h2o
from h2o.estimators.gbm import H2OGradientBoostingEstimator
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.backend import H2OLocalServer
from IPython.display import Image
from IPython.display import display
import os
import re
import subprocess
from subprocess import CalledProcessError
import time
In [2]:
# start and connect to h2o server
h2o.init(max_mem_size='12G')
In [3]:
# load clean data
path = '../../03_regression/data/train.csv'
frame = h2o.import_file(path=path)
In [4]:
# assign target and inputs
y = 'SalePrice'
X = [name for name in frame.columns if name not in [y, 'Id']]
In [5]:
# determine column types
# impute
reals, enums = [], []
for key, val in frame.types.items():
if key in X:
if val == 'enum':
enums.append(key)
else:
reals.append(key)
_ = frame[reals].impute(method='median')
_ = frame[enums].impute(method='mode')
In [6]:
# split into training an validation, and 30% test
train, valid = frame.split_frame([0.7])
In [7]:
# initialize pre-tuned nn model
nn_model = H2ODeepLearningEstimator(
epochs=50, # read over the data 50 times, but in mini-batches
hidden=[170, 320], # 100 hidden units in 1 hidden layer
activation='Tanh', # bounded activation function that allows for dropout, tanh
l2=0.007, # L2 penalty can increase stability in presence of highly correlated inputs
adaptive_rate=True, # adjust magnitude of weight updates automatically (+stability, +accuracy)
stopping_rounds=2, # stop after validation error does not decrease for 5 iterations
score_each_iteration=True, # score validation error on every iteration
reproducible=True,
seed=12345)
# train nn model
nn_model.train(
x=X,
y=y,
training_frame=train,
validation_frame=valid)
In [8]:
# measure nn AUC
print(nn_model.rmsle(train=True))
print(nn_model.rmsle(valid=True))
In [9]:
# cbind predictions to training frame
# give them a nice name
preds = nn_model.predict(frame)
preds.columns = ['predicted_SalePrice']
frame_yhat = frame.cbind(preds)
In [10]:
yhat = 'predicted_SalePrice'
model_id = 'dt_surrogate_mojo'
# train single tree surrogate model
surrogate = H2OGradientBoostingEstimator(ntrees=1,
sample_rate=1,
col_sample_rate=1,
max_depth=3,
seed=12345,
model_id=model_id)
_ = surrogate.train(x=X, y=yhat, training_frame=frame_yhat)
# persist MOJO (compiled, representation of trained model)
# from which to generate plot of surrogate
mojo_path = surrogate.download_mojo(path='.')
print(surrogate)
print('Generated MOJO path:\n', mojo_path)
In [11]:
details = False # print more info on tree, details = True
title = 'Home Prices Decision Tree Surrogate'
hs = H2OLocalServer()
h2o_jar_path = hs._find_jar()
print('Discovered H2O jar path:\n', h2o_jar_path)
gv_file_name = model_id + '.gv'
gv_args = str('-cp ' + h2o_jar_path +
' hex.genmodel.tools.PrintMojo --tree 0 -i '
+ mojo_path + ' -o').split()
gv_args.insert(0, 'java')
gv_args.append(gv_file_name)
if details:
gv_args.append('--detail')
if title is not None:
gv_args = gv_args + ['--title', title]
print()
print('Calling external process ...')
print(' '.join(gv_args))
_ = subprocess.call(gv_args)
In [12]:
png_file_name = model_id + '.png'
png_args = str('dot -Tpng ' + gv_file_name + ' -o ' + png_file_name)
png_args = png_args.split()
print('Calling external process ...')
print(' '.join(png_args))
_ = subprocess.call(png_args)
In [ ]:
display(Image((png_file_name)))
In [ ]:
# shutdown h2o
h2o.cluster().shutdown(prompt=True)