<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 H2O Tutorial
Step1:  If you already have an H2O cluster running that you'd like to connect to (for example, in a multi-node Hadoop environment), then you can specify the IP and port of that cluster as follows
Step2:  Download EEG Data
The following code downloads a copy of the EEG Eye State dataset.  All data is from one continuous EEG measurement with the Emotiv EEG Neuroheadset. The duration of the measurement was 117 seconds. The eye state was detected via a camera during the EEG measurement and added later manually to the file after analysing the video frames. '1' indicates the eye-closed and '0' the eye-open state. All values are in chronological order with the first measured value at the top of the data.
We can import the data directly into H2O using the import_file method in the Python API.  The import path can be a URL, a local path, a path to an HDFS file, or a file on Amazon S3.
Step3:  Explore Data
Once we have loaded the data, let's take a quick look.  First the dimension of the frame
Step4:  Now let's take a look at the top of the frame
Step5:  The first 14 columns are numeric values that represent EEG measurements from the headset.  The "eyeDetection" column is the response.  There is an additional column called "split" that was added (by me) in order to specify partitions of the data (so we can easily benchmark against other tools outside of H2O using the same splits).  I randomly divided the dataset into three partitions
Step6:  To select a subset of the columns to look at, typical Pandas indexing applies
Step7:  Now let's select a single column, for example -- the response column, and look at the data more closely
Step8:  It looks like a binary response, but let's validate that assumption
Step9:  If you don't specify the column types when you import the file, H2O makes a guess at what your column types are.  If there are 0's and 1's in a column, H2O will automatically parse that as numeric by default.  
Therefore, we should convert the response column to a more efficient "enum" representation -- in this case it is a categorial variable with two levels, 0 and 1.  If the only column in my data that is categorical is the response, I typically don't bother specifying the column type during the parse, and instead use this one-liner to convert it aftewards
Step10:  Now we can check that there are two levels in our response column
Step11:  We can query the categorical "levels" as well ('0' and '1' stand for "eye open" and "eye closed") to see what they are
Step12:  We may want to check if there are any missing values, so let's look for NAs in our dataset.  For tree-based methods like GBM and RF, H2O handles missing feature values automatically, so it's not a problem if we are missing certain feature values.  However, it is always a good idea to check to make sure that you are not missing any of the training labels.  
To figure out which, if any, values are missing, we can use the isna method on the diagnosis column.  The columns in an H2O Frame are also H2O Frames themselves, so all the methods that apply to a Frame also apply to a single column.
Step13:  The isna method doesn't directly answer the question, "Does the response column contain any NAs?", rather it returns a 0 if that cell is not missing (Is NA? FALSE == 0) and a 1 if it is missing (Is NA? TRUE == 1).  So if there are no missing values, then summing over the whole column should produce a summand equal to 0.0.  Let's take a look
Step14:  Great, no missing labels.  
Step15:  The sum is still zero, so there are no missing values in any of the cells.
The next thing I may wonder about in a binary classification problem is the distribution of the response in the training data.  Is one of the two outcomes under-represented in the training set?  Many real datasets have what's called an "imbalanace" problem, where one of the classes has far fewer training examples than the other class.  Let's take a look at the distribution
Step16:  Ok, the data is not exactly evenly distributed between the two classes -- there are more 0's than 1's in the dataset.  However, this level of imbalance shouldn't be much of an issue for the machine learning algos.  (We will revisit this later in the modeling section below).
Let's calculate the percentage that each class represents
Step17:  Split H2O Frame into a train and test set
So far we have explored the original dataset (all rows).  For the machine learning portion of this tutorial, we will break the dataset into three parts
Step18:  Machine Learning in H2O
We will do a quick demo of the H2O software using a Gradient Boosting Machine (GBM).  The goal of this problem is to train a model to predict eye state (open vs closed) from EEG data. 
Train and Test a GBM model
Step19:  We first create a model object of class, "H2OGradientBoostingEstimator".  This does not actually do any training, it just sets the model up for training by specifying model parameters.
Step20:  Specify the predictor set and response
The model object, like all H2O estimator objects, has a train method, which will actually perform model training.  At this step we specify the training and (optionally) a validation set, along with the response and predictor variables.
The x argument should be a list of predictor names in the training frame, and y specifies the response column.  We have already set y = "eyeDetector" above, but we still need to specify x.
Step21:  Now that we have specified x and y, we can train the model
Step22:  Inspect Model
The type of results shown when you print a model, are determined by the following
Step23:  Model Performance on a Test Set
Once a model has been trained, you can also use it to make predictions on a test set.  In the case above, we just ran the model once, so our validation set (passed as validation_frame), could have also served as a "test set."  We technically have already created test set predictions and evaluated test set performance.  
However, when performing model selection over a variety of model parameters, it is common for users to train a variety of models (using different parameters) using the training set, train, and a validation set, valid.  Once the user selects the best model (based on validation set performance), the true test of model performance is performed by making a final set of predictions on the held-out (never been used before) test set, test.
You can use the model_performance method to generate predictions on a new dataset.  The results are stored in an object of class, "H2OBinomialModelMetrics".
Step24:  Individual model performance metrics can be extracted using methods like r2, auc and mse.  In the case of binary classification, we may be most interested in evaluating test set Area Under the ROC Curve (AUC).
Step25:  Cross-validated Performance
To perform k-fold cross-validation, you use the same code as above, but you specify nfolds as an integer greater than 1, or add a "fold_column" to your H2O Frame which indicates a fold ID for each row.
Unless you have a specific reason to manually assign the observations to folds, you will find it easiest to simply use the nfolds argument.
When performing cross-validation, you can still pass a validation_frame, but you can also choose to use the original dataset that contains all the rows.  We will cross-validate a model below using the original H2O Frame which is called data.
Step26:  This time around, we will simply pull the training and cross-validation metrics out of the model.  To do so, you use the auc method again, and you can specify train or xval as True to get the correct metric.
Step27:  Grid Search
One way of evaluting models with different parameters is to perform a grid search over a set of parameter values.  For example, in GBM, here are three model parameters that may be useful to search over
Step28:  Define an "H2OGridSearch" object by specifying the algorithm (GBM) and the hyper parameters
Step29:  An "H2OGridSearch" object also has a train method, which is used to train all the models in the grid.
Step30:  Compare Models
Step31:  The "best" model in terms of validation set AUC is listed first in auc_table.
Step32:  The last thing we may want to do is generate predictions on the test set using the "best" model, and evaluate the test set AUC.
<ASSISTANT_TASK:>
Python Code:
import h2o
# Start an H2O Cluster on your local machine
h2o.init()
Explanation: H2O Tutorial: EEG Eye State Classification
Author: Erin LeDell
Contact: erin@h2o.ai
This tutorial steps through a quick introduction to H2O's Python API. The goal of this tutorial is to introduce through a complete example H2O's capabilities from Python. 
Most of the functionality for a Pandas DataFrame is exactly the same syntax for an H2OFrame, so if you are comfortable with Pandas, data frame manipulation will come naturally to you in H2O.  The modeling syntax in the H2O Python API may also remind you of scikit-learn.  
References: H2O Python API documentation and H2O general documentation
Install H2O in Python
Prerequisites
This tutorial assumes you have Python 2.7 installed.  The h2o Python package has a few dependencies which can be installed using pip. The packages that are required are (which also have their own dependencies):
bash
pip install requests
pip install tabulate
pip install scikit-learn
If you have any problems (for example, installing the scikit-learn package), check out this page for tips.
Install h2o
Once the dependencies are installed, you can install H2O.  We will use the latest stable version of the h2o package, which is currently "Tibshirani-8."  The installation instructions are on the "Install in Python" tab on this page.
```bash
The following command removes the H2O module for Python (if it already exists).
pip uninstall h2o
Next, use pip to install this version of the H2O Python module.
pip install http://h2o-release.s3.amazonaws.com/h2o/rel-tibshirani/8/Python/h2o-3.6.0.8-py2.py3-none-any.whl
```
For reference, the Python documentation for the latest stable release of H2O is here.
Start up an H2O cluster
In a Python terminal, we can import the h2o package and start up an H2O cluster.
End of explanation
# This will not actually do anything since it's a fake IP address
# h2o.init(ip="123.45.67.89", port=54321)
Explanation: If you already have an H2O cluster running that you'd like to connect to (for example, in a multi-node Hadoop environment), then you can specify the IP and port of that cluster as follows:
End of explanation
#csv_url = "http://www.stat.berkeley.edu/~ledell/data/eeg_eyestate_splits.csv"
csv_url = "https://h2o-public-test-data.s3.amazonaws.com/eeg_eyestate_splits.csv"
data = h2o.import_file(csv_url)
Explanation: Download EEG Data
The following code downloads a copy of the EEG Eye State dataset.  All data is from one continuous EEG measurement with the Emotiv EEG Neuroheadset. The duration of the measurement was 117 seconds. The eye state was detected via a camera during the EEG measurement and added later manually to the file after analysing the video frames. '1' indicates the eye-closed and '0' the eye-open state. All values are in chronological order with the first measured value at the top of the data.
We can import the data directly into H2O using the import_file method in the Python API.  The import path can be a URL, a local path, a path to an HDFS file, or a file on Amazon S3.
End of explanation
data.shape
Explanation: Explore Data
Once we have loaded the data, let's take a quick look.  First the dimension of the frame:
End of explanation
data.head()
Explanation: Now let's take a look at the top of the frame:
End of explanation
data.columns
Explanation: The first 14 columns are numeric values that represent EEG measurements from the headset.  The "eyeDetection" column is the response.  There is an additional column called "split" that was added (by me) in order to specify partitions of the data (so we can easily benchmark against other tools outside of H2O using the same splits).  I randomly divided the dataset into three partitions: train (60%), valid (%20) and test (20%) and marked which split each row belongs to in the "split" column.
Let's take a look at the column names.  The data contains derived features from the medical images of the tumors.
End of explanation
columns = ['AF3', 'eyeDetection', 'split']
data[columns].head()
Explanation: To select a subset of the columns to look at, typical Pandas indexing applies:
End of explanation
y = 'eyeDetection'
data[y]
Explanation: Now let's select a single column, for example -- the response column, and look at the data more closely:
End of explanation
data[y].unique()
Explanation: It looks like a binary response, but let's validate that assumption:
End of explanation
data[y] = data[y].asfactor()
Explanation: If you don't specify the column types when you import the file, H2O makes a guess at what your column types are.  If there are 0's and 1's in a column, H2O will automatically parse that as numeric by default.  
Therefore, we should convert the response column to a more efficient "enum" representation -- in this case it is a categorial variable with two levels, 0 and 1.  If the only column in my data that is categorical is the response, I typically don't bother specifying the column type during the parse, and instead use this one-liner to convert it aftewards:
End of explanation
data[y].nlevels()
Explanation: Now we can check that there are two levels in our response column:
End of explanation
data[y].levels()
Explanation: We can query the categorical "levels" as well ('0' and '1' stand for "eye open" and "eye closed") to see what they are:
End of explanation
data.isna()
data[y].isna()
Explanation: We may want to check if there are any missing values, so let's look for NAs in our dataset.  For tree-based methods like GBM and RF, H2O handles missing feature values automatically, so it's not a problem if we are missing certain feature values.  However, it is always a good idea to check to make sure that you are not missing any of the training labels.  
To figure out which, if any, values are missing, we can use the isna method on the diagnosis column.  The columns in an H2O Frame are also H2O Frames themselves, so all the methods that apply to a Frame also apply to a single column.
End of explanation
data[y].isna().sum()
Explanation: The isna method doesn't directly answer the question, "Does the response column contain any NAs?", rather it returns a 0 if that cell is not missing (Is NA? FALSE == 0) and a 1 if it is missing (Is NA? TRUE == 1).  So if there are no missing values, then summing over the whole column should produce a summand equal to 0.0.  Let's take a look:
End of explanation
data.isna().sum()
Explanation: Great, no missing labels.  :-)
Out of curiosity, let's see if there is any missing data in this frame:
End of explanation
data[y].table()
Explanation: The sum is still zero, so there are no missing values in any of the cells.
The next thing I may wonder about in a binary classification problem is the distribution of the response in the training data.  Is one of the two outcomes under-represented in the training set?  Many real datasets have what's called an "imbalanace" problem, where one of the classes has far fewer training examples than the other class.  Let's take a look at the distribution:
End of explanation
n = data.shape[0]  # Total number of training samples
data[y].table()['Count']/n
Explanation: Ok, the data is not exactly evenly distributed between the two classes -- there are more 0's than 1's in the dataset.  However, this level of imbalance shouldn't be much of an issue for the machine learning algos.  (We will revisit this later in the modeling section below).
Let's calculate the percentage that each class represents:
End of explanation
train = data[data['split']=="train"]
train.shape
valid = data[data['split']=="valid"]
valid.shape
test = data[data['split']=="test"]
test.shape
Explanation: Split H2O Frame into a train and test set
So far we have explored the original dataset (all rows).  For the machine learning portion of this tutorial, we will break the dataset into three parts: a training set, validation set and a test set.
If you want H2O to do the splitting for you, you can use the split_frame method.  However, we have explicit splits that we want (for reproducibility reasons), so we can just subset the Frame to get the partitions we want.  
Subset the data H2O Frame on the "split" column:
End of explanation
# Import H2O GBM:
from h2o.estimators.gbm import H2OGradientBoostingEstimator
Explanation: Machine Learning in H2O
We will do a quick demo of the H2O software using a Gradient Boosting Machine (GBM).  The goal of this problem is to train a model to predict eye state (open vs closed) from EEG data. 
Train and Test a GBM model
End of explanation
model = H2OGradientBoostingEstimator(distribution='bernoulli',
                                    ntrees=100,
                                    max_depth=4,
                                    learn_rate=0.1)
Explanation: We first create a model object of class, "H2OGradientBoostingEstimator".  This does not actually do any training, it just sets the model up for training by specifying model parameters.
End of explanation
x = list(train.columns)
x
del x[12:14]  #Remove the 13th and 14th columns, 'eyeDetection' and 'split'
x
Explanation: Specify the predictor set and response
The model object, like all H2O estimator objects, has a train method, which will actually perform model training.  At this step we specify the training and (optionally) a validation set, along with the response and predictor variables.
The x argument should be a list of predictor names in the training frame, and y specifies the response column.  We have already set y = "eyeDetector" above, but we still need to specify x.
End of explanation
model.train(x=x, y=y, training_frame=train, validation_frame=valid)
Explanation: Now that we have specified x and y, we can train the model:
End of explanation
print(model)
Explanation: Inspect Model
The type of results shown when you print a model, are determined by the following:
- Model class of the estimator (e.g. GBM, RF, GLM, DL)
- The type of machine learning problem (e.g. binary classification, multiclass classification, regression)
- The data you specify (e.g. training_frame only, training_frame and validation_frame, or training_frame and nfolds)
Below, we see a GBM Model Summary, as well as training and validation metrics since we supplied a validation_frame.  Since this a binary classification task, we are shown the relevant performance metrics, which inclues: MSE, R^2, LogLoss, AUC and Gini.  Also, we are shown a Confusion Matrix, where the threshold for classification is chosen automatically (by H2O) as the threshold which maximizes the F1 score.
The scoring history is also printed, which shows the performance metrics over some increment such as "number of trees" in the case of GBM and RF.
Lastly, for tree-based methods (GBM and RF), we also print variable importance.
End of explanation
perf = model.model_performance(test)
print(perf.__class__)
Explanation: Model Performance on a Test Set
Once a model has been trained, you can also use it to make predictions on a test set.  In the case above, we just ran the model once, so our validation set (passed as validation_frame), could have also served as a "test set."  We technically have already created test set predictions and evaluated test set performance.  
However, when performing model selection over a variety of model parameters, it is common for users to train a variety of models (using different parameters) using the training set, train, and a validation set, valid.  Once the user selects the best model (based on validation set performance), the true test of model performance is performed by making a final set of predictions on the held-out (never been used before) test set, test.
You can use the model_performance method to generate predictions on a new dataset.  The results are stored in an object of class, "H2OBinomialModelMetrics".
End of explanation
perf.r2()
perf.auc()
perf.mse()
Explanation: Individual model performance metrics can be extracted using methods like r2, auc and mse.  In the case of binary classification, we may be most interested in evaluating test set Area Under the ROC Curve (AUC).
End of explanation
cvmodel = H2OGradientBoostingEstimator(distribution='bernoulli',
                                       ntrees=100,
                                       max_depth=4,
                                       learn_rate=0.1,
                                       nfolds=5)
cvmodel.train(x=x, y=y, training_frame=data)
Explanation: Cross-validated Performance
To perform k-fold cross-validation, you use the same code as above, but you specify nfolds as an integer greater than 1, or add a "fold_column" to your H2O Frame which indicates a fold ID for each row.
Unless you have a specific reason to manually assign the observations to folds, you will find it easiest to simply use the nfolds argument.
When performing cross-validation, you can still pass a validation_frame, but you can also choose to use the original dataset that contains all the rows.  We will cross-validate a model below using the original H2O Frame which is called data.
End of explanation
print(cvmodel.auc(train=True))
print(cvmodel.auc(xval=True))
Explanation: This time around, we will simply pull the training and cross-validation metrics out of the model.  To do so, you use the auc method again, and you can specify train or xval as True to get the correct metric.
End of explanation
ntrees_opt = [5,50,100]
max_depth_opt = [2,3,5]
learn_rate_opt = [0.1,0.2]
hyper_params = {'ntrees': ntrees_opt, 
                'max_depth': max_depth_opt,
                'learn_rate': learn_rate_opt}
Explanation: Grid Search
One way of evaluting models with different parameters is to perform a grid search over a set of parameter values.  For example, in GBM, here are three model parameters that may be useful to search over:
- ntrees: Number of trees
- max_depth: Maximum depth of a tree
- learn_rate: Learning rate in the GBM
We will define a grid as follows:
End of explanation
from h2o.grid.grid_search import H2OGridSearch
gs = H2OGridSearch(H2OGradientBoostingEstimator, hyper_params = hyper_params)
Explanation: Define an "H2OGridSearch" object by specifying the algorithm (GBM) and the hyper parameters:
End of explanation
gs.train(x=x, y=y, training_frame=train, validation_frame=valid)
Explanation: An "H2OGridSearch" object also has a train method, which is used to train all the models in the grid.
End of explanation
print(gs)
# print out the auc for all of the models
auc_table = gs.sort_by('auc(valid=True)',increasing=False)
print(auc_table)
Explanation: Compare Models
End of explanation
best_model = h2o.get_model(auc_table['Model Id'][0])
best_model.auc()
Explanation: The "best" model in terms of validation set AUC is listed first in auc_table.
End of explanation
best_perf = best_model.model_performance(test)
best_perf.auc()
Explanation: The last thing we may want to do is generate predictions on the test set using the "best" model, and evaluate the test set AUC.
End of explanation
<END_TASK>