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.
http://xgboost.readthedocs.io/en/latest//tutorials/monotonic.html
Monotonicity is an important facet of intepretability. Monotonicity constraints ensure that the modeled relationship between inputs and the target move in only direction, i.e. as an input increases the target can only increase or as input increases the target can only decrease. Such monotonic relationships are usually easier to explain and understand than non-monotonic relationships.
In [1]:
# imports
import h2o
from h2o.estimators.xgboost import H2OXGBoostEstimator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import pandas as pd
import xgboost as xgb
In [2]:
# start h2o
h2o.init()
h2o.remove_all()
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')
In [6]:
# split into training and validation
train, valid = frame.split_frame([0.7], seed=12345)
In [7]:
# for convenience create a tuple for xgboost monotone_constraints parameter
mono_constraints = tuple(int(i) for i in np.ones(shape=(int(1), len(reals))).tolist()[0])
In [8]:
# Check log transform - looks good
%matplotlib inline
train['SalePrice'].log().as_data_frame().hist()
# Execute log transform
train['SalePrice'] = train['SalePrice'].log()
valid['SalePrice'] = valid['SalePrice'].log()
print(train[0:3, 'SalePrice'])
In [9]:
ave_y = train['SalePrice'].mean()[0]
# XGBoost uses SVMLight data structure, not Numpy arrays or Pandas data frames
dtrain = xgb.DMatrix(train.as_data_frame()[reals],
train.as_data_frame()['SalePrice'])
dvalid = xgb.DMatrix(valid.as_data_frame()[reals],
valid.as_data_frame()['SalePrice'])
# tuning parameters
params = {
'objective': 'reg:linear',
'booster': 'gbtree',
'eval_metric': 'rmse',
'eta': 0.005,
'subsample': 0.1,
'colsample_bytree': 0.8,
'max_depth': 5,
'reg_alpha' : 0.01,
'reg_lambda' : 0.0,
'monotone_constraints':mono_constraints,
'base_score': ave_y,
'silent': 0,
'seed': 12345,
}
# watchlist is used for early stopping
watchlist = [(dtrain, 'train'), (dvalid, 'eval')]
# train model
xgb_model1 = xgb.train(params,
dtrain,
1000,
evals=watchlist,
early_stopping_rounds=50,
verbose_eval=True)
In [10]:
_ = xgb.plot_importance(xgb_model1)
In [11]:
def par_dep(xs, frame, model, resolution=20, bins=None):
""" Creates Pandas dataframe containing partial dependence for a single variable.
Args:
xs: Variable for which to calculate partial dependence.
frame: H2OFrame for which to calculate partial dependence.
model: XGBoost model for which to calculate partial dependence.
resolution: The number of points across the domain of xs for which to calculate partial dependence.
Returns:
Pandas dataframe containing partial dependence values.
"""
# don't show progress bars for parse
h2o.no_progress()
# init empty Pandas frame w/ correct col names
par_dep_frame = pd.DataFrame(columns=[xs, 'partial_dependence'])
# cache original data
col_cache = h2o.deep_copy(frame[xs], xid='col_cache')
# determine values at which to calculate partial dependency
if bins == None:
min_ = frame[xs].min()
max_ = frame[xs].max()
by = (max_ - min_)/resolution
bins = np.arange(min_, max_, by)
# calculate partial dependency
# by setting column of interest to constant
for j in bins:
frame[xs] = j
dframe = xgb.DMatrix(frame.as_data_frame(),)
par_dep_i = h2o.H2OFrame(model.predict(dframe).tolist())
par_dep_j = par_dep_i.mean()[0]
par_dep_frame = par_dep_frame.append({xs:j,
'partial_dependence': par_dep_j},
ignore_index=True)
# return input frame to original cached state
frame[xs] = h2o.get_frame('col_cache')
return par_dep_frame
In [12]:
par_dep_OverallCond = par_dep('OverallCond', valid[reals], xgb_model1)
par_dep_GrLivArea = par_dep('GrLivArea', valid[reals], xgb_model1)
par_dep_LotArea = par_dep('LotArea', valid[reals], xgb_model1)
In [13]:
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
In [14]:
quantile_dict = get_quantile_dict('SalePrice', 'Id', valid)
In [15]:
bins_OverallCond = list(par_dep_OverallCond['OverallCond'])
bins_GrLivArea = list(par_dep_GrLivArea['GrLivArea'])
bins_LotArea = list(par_dep_LotArea['LotArea'])
for i in sorted(quantile_dict.keys()):
col_name = 'Percentile_' + str(i)
par_dep_OverallCond[col_name] = par_dep('OverallCond',
valid[valid['Id'] == int(quantile_dict[i])][reals],
xgb_model1,
bins=bins_OverallCond)['partial_dependence']
par_dep_GrLivArea[col_name] = par_dep('GrLivArea',
valid[valid['Id'] == int(quantile_dict[i])][reals],
xgb_model1,
bins=bins_GrLivArea)['partial_dependence']
par_dep_LotArea[col_name] = par_dep('LotArea',
valid[valid['Id'] == int(quantile_dict[i])][reals],
xgb_model1,
bins=bins_LotArea)['partial_dependence']
In [16]:
# OverallCond
fig, ax = plt.subplots()
par_dep_OverallCond.drop('partial_dependence', axis=1).plot(x='OverallCond', colormap='gnuplot', ax=ax)
par_dep_OverallCond.plot(title='Partial Dependence and ICE for OverallCond',
x='OverallCond',
y='partial_dependence',
style='r-',
linewidth=3,
ax=ax)
_ = plt.legend(bbox_to_anchor=(1.05, 0),
loc=3,
borderaxespad=0.)
In [17]:
# GrLivArea
fig, ax = plt.subplots()
par_dep_GrLivArea.drop('partial_dependence', axis=1).plot(x='GrLivArea', colormap='gnuplot', ax=ax)
par_dep_GrLivArea.plot(title='Partial Dependence and ICE for GrLivArea',
x='GrLivArea',
y='partial_dependence',
style='r-',
linewidth=3,
ax=ax)
_ = plt.legend(bbox_to_anchor=(1.05, 0),
loc=3,
borderaxespad=0.)
In [18]:
# LotArea
fig, ax = plt.subplots()
par_dep_LotArea.drop('partial_dependence', axis=1).plot(x='LotArea', colormap='gnuplot', ax=ax)
par_dep_LotArea.plot(title='Partial Dependence and ICE for LotArea',
x='LotArea',
y='partial_dependence',
style='r-',
linewidth=3,
ax=ax)
_ = plt.legend(bbox_to_anchor=(1.05, 0),
loc=3,
borderaxespad=0.)
In [19]:
h2o.cluster().shutdown(prompt=True)