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.
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()
In [3]:
# load 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], seed=12345)
In [7]:
# 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, training_frame=train, validation_frame=valid)
preds = valid.cbind(model.predict(valid))
In [8]:
model.varimp_plot()
In [9]:
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
sale_quantile_dict = get_quantile_dict('SalePrice', 'Id', preds)
pred_quantile_dict = get_quantile_dict('predict', 'Id', preds)
print('SalePrice quantiles:\n', sale_quantile_dict)
print()
print('prediction quantiles:\n',pred_quantile_dict)
In [10]:
print('lowest SalePrice:\n', preds[preds['Id'] == int(sale_quantile_dict[0])]['SalePrice'])
print('lowest prediction:\n', preds[preds['Id'] == int(pred_quantile_dict[0])]['predict'])
print('highest SalePrice:\n', preds[preds['Id'] == int(sale_quantile_dict[99])]['SalePrice'])
print('highest prediction:\n', preds[preds['Id'] == int(pred_quantile_dict[99])]['predict'])
This result alone is interesting. The model appears to be struggling to accurately predict low and high values for SalePrice. This behavior should be corrected to increase the accuracy of predictions. A strategy for improving predictions for these homes with extreme values might be to weight them higher during training using observation weights, or they may need their own models.
In [11]:
# look at current row
print(preds[preds['Id'] == int(pred_quantile_dict[0])])
In [12]:
# find current error
observed = preds[preds['Id'] == int(pred_quantile_dict[0])]['SalePrice'][0,0]
predicted = preds[preds['Id'] == int(pred_quantile_dict[0])]['predict'][0,0]
print('Error: %.2f%%' % (100*(abs(observed - predicted)/observed)))
In [13]:
# change value of important variables
test_case = preds[preds['Id'] == int(pred_quantile_dict[0])]
test_case = test_case.drop('predict')
test_case['OverallQual'] = 0
test_case['Neighborhood'] = 'IDOTRR'
test_case['GrLivArea'] = 500
test_case = test_case.cbind(model.predict(test_case))
print(test_case)
# recalculate error
observed = test_case['SalePrice'][0,0]
predicted = test_case['predict'][0,0]
print('Error: %.2f%%' % (100*(abs(observed - predicted)/observed)))
While the model does not seem to handle low-valued homes very well, making the home with the lowest predicted price less appealling does not seem to make the model's predictions any worse. While this prediction behavior appears somewhat stable, which would normally be desirable, this is not particularly good news as the underlying prediction is so inaccurate.
In [14]:
# look at current row
print(preds[preds['Id'] == int(pred_quantile_dict[99])])
In [15]:
# find current error
observed = preds[preds['Id'] == int(pred_quantile_dict[99])]['SalePrice'][0,0]
predicted = preds[preds['Id'] == int(pred_quantile_dict[99])]['predict'][0,0]
print('Error: %.2f%%' % (100*(abs(observed - predicted)/observed)))
In [16]:
# change value of important variables
test_case = preds[preds['Id'] == int(pred_quantile_dict[99])]
test_case = test_case.drop('predict')
test_case['Neighborhood'] = 'StoneBr'
test_case['GrLivArea'] = 5000
test_case = test_case.cbind(model.predict(test_case))
print(test_case)
# recalculate error
observed = test_case['SalePrice'][0,0]
predicted = test_case['predict'][0,0]
print('Error: %.2f%%' % (100*(abs(observed - predicted)/observed)))
This result may point to unstable predictions for the higher end of SalesPrice.
In [17]:
h2o.cluster().shutdown(prompt=True)