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.
In [1]:
# imports
import h2o
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
from h2o.estimators.kmeans import H2OKMeansEstimator
from h2o.estimators.pca import H2OPrincipalComponentAnalysisEstimator
In [2]:
# display matplotlib graphics in notebook
%matplotlib inline
In [3]:
# start and connect to h2o server
h2o.init()
In [4]:
# load clean data
path = '/Users/phall/workspace/GWU_data_mining/03_regression/data/loan_clean.csv'
In [5]:
# define input variable measurement levels
# strings automatically parsed as enums (nominal)
# numbers automatically parsed as numeric
col_types = {'bad_loan': 'enum',
'GRP_addr_state': 'enum',
'GRP_home_ownership': 'enum',
'GRP_verification_status': 'enum',
'GRP_REP_home_ownership': 'enum',
'GRP_purpose': 'enum'}
In [6]:
frame = h2o.import_file(path=path, col_types=col_types) # multi-threaded import
In [7]:
frame.describe()
In [8]:
# assign target and inputs
y = 'bad_loan'
X = [name for name in frame.columns if name not in ['id', '_WARN_', y]]
print(y)
print(X)
In [9]:
# train k-means cluster model
# data is already standardized
# w/ 3 clusters
# print summary
clusters = H2OKMeansEstimator(standardize=False, k=3, seed=12345)
clusters.train(x=X, training_frame=frame)
print(clusters)
In [10]:
# join cluster labels to original data for further analysis
labels = clusters.predict(frame)
labeled_frame = frame.cbind(labels)
labeled_frame[-1].head()
Out[10]:
In [11]:
# determine column types
reals, enums = [], []
for key, val in labeled_frame.types.items():
if key in X:
if val == 'enum':
enums.append(key)
else:
reals.append(key)
print(enums)
print(reals)
In [12]:
# profile clusters by means
grouped = labeled_frame.group_by(by=['predict'])
means = grouped.mean(col=reals).get_frame()
print(means)
In [13]:
# profile clusters by modes
grouped = labeled_frame.group_by(by=['predict'])
modes = grouped.mode(col=enums).get_frame()
print(modes)
In [14]:
# define a function for plotting clusters in 2-d
def plot(_2d_labeled_frame):
_0 = plt.scatter(features_pandas[_2d_labeled_frame.label == 0].iloc[0:750, 0],
features_pandas[_2d_labeled_frame.label == 0].iloc[0:750, 1],
color='m', marker='^', alpha=.15)
_1 = plt.scatter(features_pandas[_2d_labeled_frame.label == 1].iloc[0:750, 0],
features_pandas[_2d_labeled_frame.label == 1].iloc[0:750, 1],
color='c', alpha=.15)
_2 = plt.scatter(features_pandas[_2d_labeled_frame.label == 2].iloc[0:750, 0],
features_pandas[_2d_labeled_frame.label == 2].iloc[0:750, 1],
color='g', marker='s', alpha=.15)
plt.legend([_0, _1, _2],
['Cluster 0', 'Cluster 1', 'Cluster 2'],
bbox_to_anchor=(1.05, 0.0),
loc=3, borderaxespad=0.)
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
In [15]:
# project training data onto 2-D using principal components
# join with clusters labels
# plot
pca = H2OPrincipalComponentAnalysisEstimator(k=2) # project onto 2 PCs
pca.train(x=X, training_frame=labeled_frame)
features = pca.predict(labeled_frame)
features_pandas = features.as_data_frame()
features_pandas['label'] = labeled_frame[-1].as_data_frame()
print(features_pandas.head())
plot(features_pandas)
In [16]:
# shutdown h2o
h2o.cluster().shutdown(prompt=False)