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: Lei, Jing, G’Sell, Max, Rinaldo, Alessandro, Tibshirani, Ryan J., and Wasserman, Larry. Distribution-free predictive inference for regression. Journal of the American Statistical Association, 2017.
http://www.stat.cmu.edu/~ryantibs/papers/conformal.pdf
Instead of dropping one variable and retraining a model to understand the importance of that variable in a model, these examples set a variable to missing and rescore this new, corrupted sample with the original model. This is approach may be more appropriate for nonlineaer models in which nonlinear dependencies can allow variables to nearly completely replace one another when a model is retrained.
In [1]:
# imports
import h2o
import numpy as np
import pandas as pd
from h2o.estimators.gbm import H2OGradientBoostingEstimator
In [2]:
# start h2o
h2o.init()
h2o.remove_all()
h2o.show_progress()
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 and validation
train, valid = frame.split_frame([0.7])
In [7]:
# print out linearly correlated pairs
corr = train[reals].cor().as_data_frame()
for i in range(0, corr.shape[0]):
for j in range(0, corr.shape[1]):
if i != j:
if np.abs(corr.iat[i, j]) > 0.7:
print(corr.columns[i], corr.columns[j])
It's likely that even more nonlinearly dependent relationships exist between inputs. Nonlinearly relationships can also behave differently at global and local scales.
In [8]:
X_reals_decorr = [i for i in reals if i not in ['GarageYrBlt', 'TotRmsAbvGrd', 'TotalBsmtSF', 'GarageCars']]
In [9]:
# train GBM model
model = H2OGradientBoostingEstimator(ntrees=100,
max_depth=10,
distribution='huber',
learn_rate=0.1,
stopping_rounds=5,
seed=12345)
model.train(y=y, x=X_reals_decorr, training_frame=train, validation_frame=valid)
preds = valid['Id'].cbind(model.predict(valid))
In [10]:
h2o.no_progress()
for k, i in enumerate(X_reals_decorr):
# train and predict with Xi set to missing
valid_loco = h2o.deep_copy(valid, 'valid_loco')
valid_loco[i] = np.nan
preds_loco = model.predict(valid_loco)
# create a new, named column for the LOCO prediction
preds_loco.columns = [i]
preds = preds.cbind(preds_loco)
# subtract the LOCO prediction from
preds[i] = preds[i] - preds['predict']
print('LOCO Progress: ' + i + ' (' + str(k+1) + '/' + str(len(X_reals_decorr)) + ') ...')
print('Done.')
preds.head()
Out[10]:
The numeric values in each column are an estimate of how much each variable contributed to each decision. These values can tell you how a variable and it's values were weighted in any given decision by the model. These values are crucially important for machine learning interpretability and are often to referred to "local feature importance", "reason codes", or "turn-down codes." The latter phrases are borrowed from credit scoring. Credit lenders must provide reasons for turning down a credit application, even for automated decisions. Reason codes can be easily extracted from LOCO local feature importance values, by simply ranking the variables that played the largest role in any given decision.
In [11]:
def get_quantile_dict(y, id_, frame):
""" Returns the percentiles of a column y as the indices for another column id_.
Args:
y: Column in which to find percentiles.
id_: Id column that stores indices for percentiles of y.
frame: H2OFrame containing y and id_.
Returns:
Dictionary of percentile values and index column values.
"""
quantiles_df = frame.as_data_frame()
quantiles_df.sort_values(y, inplace=True)
quantiles_df.reset_index(inplace=True)
percentiles_dict = {}
percentiles_dict[0] = quantiles_df.loc[0, id_]
percentiles_dict[99] = quantiles_df.loc[quantiles_df.shape[0]-1, id_]
inc = quantiles_df.shape[0]//10
for i in range(1, 10):
percentiles_dict[i * 10] = quantiles_df.loc[i * inc, id_]
return percentiles_dict
quantile_dict = get_quantile_dict('predict', 'Id', preds)
print(quantile_dict)
In [12]:
%matplotlib inline
In [13]:
median_loco = preds[preds['Id'] == int(quantile_dict[50]), :].as_data_frame().drop(['Id', 'predict'], axis=1)
median_loco = median_loco.T.sort_values(by=0)[:5]
_ = median_loco.plot(kind='bar',
title='Negative Reason Codes for the Median of Predicted Sale Price\n',
legend=False)
In [14]:
median_loco = preds[preds['Id'] == int(quantile_dict[50]), :].as_data_frame().drop(['Id', 'predict'], axis=1)
median_loco = median_loco.T.sort_values(by=0, ascending=False)[:5]
_ = median_loco.plot(kind='bar',
title='Positive Reason Codes for the Median of Predicted Sale Price\n',
color='r',
legend=False)
In [15]:
n_models = 10 # select number of models
models = []
pred_frames = []
for i in range(0, n_models):
# store models
models.append(H2OGradientBoostingEstimator(ntrees=500,
max_depth=2 * (i + 1),
distribution='huber',
learn_rate=0.01 * (i + 1),
stopping_rounds=5,
seed=i + 1))
# train models
models[i].train(y=y, x=X_reals_decorr, training_frame=train, validation_frame=valid)
# store predictions
pred_frames.append(valid['Id'].cbind(models[i].predict(valid)))
print('Training Progress: model %d/%d ...' % (i + 1, n_models))
print('Done.')
In [16]:
for k, model in enumerate(models):
for i in X_reals_decorr:
# train and predict with Xi set to missing
valid_loco = h2o.deep_copy(valid, 'valid_loco')
valid_loco[i] = np.nan
preds_loco = model.predict(valid_loco)
# create a new, named column for the LOCO prediction
preds_loco.columns = [i]
pred_frames[k] = pred_frames[k].cbind(preds_loco)
# subtract the LOCO prediction from
pred_frames[k][i] = pred_frames[k][i] - pred_frames[k]['predict']
print('LOCO Progress: model %d/%d ...' % (k + 1, n_models))
print('Done.')
In [17]:
median_loco_frames = []
col_names = ['Loco ' + str(i) for i in range(1, n_models + 1)]
for i in range(0, n_models):
# collect LOCO as a column vector in a Pandas df
preds = pred_frames[i]
median_loco_frames.append(preds[preds['Id'] == int(quantile_dict[50]), :]\
.as_data_frame()\
.drop(['Id', 'predict'], axis=1)
.T)
loco_ensemble = pd.concat(median_loco_frames, axis=1)
loco_ensemble.columns = col_names
loco_ensemble['Mean Local Importance'] = loco_ensemble.mean(axis=1)
loco_ensemble['Std. Dev. Local Importance'] = loco_ensemble.std(axis=1)
loco_ensemble
Out[17]:
In [18]:
median_mean_loco = loco_ensemble['Mean Local Importance'].sort_values()[:5]
_ = median_mean_loco.plot(kind='bar',
title='Negative Mean Reason Codes for the Median of Predicted Sale Price\n',
legend=False)
In [19]:
median_mean_loco = loco_ensemble['Mean Local Importance'].sort_values(ascending=False)[:5]
_ = median_mean_loco.plot(kind='bar',
title='Positive Mean Reason Codes for the Median of Predicted Sale Price\n',
color='r',
legend=False)
In [20]:
h2o.cluster().shutdown(prompt=True)