INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Deprecated since 2016 - 12 - 12 use grid. get_grid () instead.
def sort_by(self, metric, increasing=True): """Deprecated since 2016-12-12, use grid.get_grid() instead.""" if metric[-1] != ')': metric += '()' c_values = [list(x) for x in zip(*sorted(eval('self.' + metric + '.items()'), key=lambda k_v: k_v[1]))] c_values.insert(1, [self.get_hyperpara...
Obtain the reconstruction error for the input test_data.
def anomaly(self, test_data, per_feature=False): """ Obtain the reconstruction error for the input test_data. :param H2OFrame test_data: The dataset upon which the reconstruction error is computed. :param bool per_feature: Whether to return the square reconstruction error per feature. O...
Get the F1 values for a set of thresholds for the models explored.
def F1(self, thresholds=None, train=False, valid=False, xval=False): """ Get the F1 values for a set of thresholds for the models explored. If all are False (default), then return the training metric value. If more than one options is set to True, then return a dictionary of metrics whe...
Get the confusion matrix for the specified metrics/ thresholds.
def confusion_matrix(self, metrics=None, thresholds=None, train=False, valid=False, xval=False): """ Get the confusion matrix for the specified metrics/thresholds. If all are False (default), then return the training metric value. If more than one options is set to True, then return a d...
Retrieve the index in this metric s threshold list at which the given threshold is located.
def find_idx_by_threshold(self, threshold, train=False, valid=False, xval=False): """ Retrieve the index in this metric's threshold list at which the given threshold is located. If all are False (default), then return the training metric value. If more than one options is set to True, t...
Returns a confusion matrix based of H2O s default prediction threshold for a dataset.
def confusion_matrix(self, data): """ Returns a confusion matrix based of H2O's default prediction threshold for a dataset. :param data: metric for which the confusion matrix will be calculated. """ return {model.model_id: model.confusion_matrix(data) for model in self.models}
Return the Importance of components associcated with a pca model.
def varimp(self, use_pandas=False): """ Return the Importance of components associcated with a pca model. use_pandas: ``bool`` (default: ``False``). """ model = self._model_json["output"] if "importance" in list(model.keys()) and model["importance"]: vals = ...
The archetypes ( Y ) of the GLRM model.
def archetypes(self): """The archetypes (Y) of the GLRM model.""" o = self._model_json["output"] yvals = o["archetypes"].cell_values archetypes = [] for yidx, yval in enumerate(yvals): archetypes.append(list(yvals[yidx])[1:]) return archetypes
Convert archetypes of the model into original feature space.
def proj_archetypes(self, test_data, reverse_transform=False): """ Convert archetypes of the model into original feature space. :param H2OFrame test_data: The dataset upon which the model was trained. :param bool reverse_transform: Whether the transformation of the training data during ...
Produce the scree plot.
def screeplot(self, type="barplot", **kwargs): """ Produce the scree plot. Library ``matplotlib`` is required for this function. :param str type: either ``"barplot"`` or ``"lines"``. """ # check for matplotlib. exit if absent. is_server = kwargs.pop("server") ...
Convert names with underscores into camelcase.
def translate_name(name): """ Convert names with underscores into camelcase. For example: "num_rows" => "numRows" "very_long_json_name" => "veryLongJsonName" "build_GBM_model" => "buildGbmModel" "KEY" => "key" "middle___underscores" => "middleUnderscores" "_e...
Dedent text to the specific indentation level.
def dedent(ind, text): """ Dedent text to the specific indentation level. :param ind: common indentation level for the resulting text (number of spaces to append to every line) :param text: text that should be transformed. :return: ``text`` with all common indentation removed, and then the specifie...
Generate schema Java class.
def generate_schema(class_name, schema): """ Generate schema Java class. :param class_name: name of the class :param schema: information about the class """ superclass = schema["superclass"] if superclass == "Schema": superclass = "Object" has_map = False is_model_builder = False ...
Generate a Retrofit Proxy class.
def generate_proxy(classname, endpoints): """ Generate a Retrofit Proxy class. Retrofit interfaces look like this: public interface GitHubService { @GET("/users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); } :param classname: name of th...
Main program.
def main(argv): """ Main program. @return: none """ global g_script_name global g_parse_log_path g_script_name = os.path.basename(argv[0]) parse_args(argv) if (g_parse_log_path is None): print("") print("ERROR: -f not specified") usage() d = Dataset(g...
Parse file specified by constructor.
def parse(self): """ Parse file specified by constructor. """ f = open(self.parse_log_path, "r") self.parse2(f) f.close()
Parse file specified by constructor.
def parse2(self, f): """ Parse file specified by constructor. """ line_num = 0 s = f.readline() while (len(s) > 0): line_num += 1 # Check for beginning of parsed data set. match_groups = re.search(r"Parse result for (.*) .(\d+) rows.:"...
Obtain the reconstruction error for the input test_data.
def anomaly(self, test_data, per_feature=False): """ Obtain the reconstruction error for the input test_data. :param H2OFrame test_data: The dataset upon which the reconstruction error is computed. :param bool per_feature: Whether to return the square reconstruction error per feature. ...
This function will extract the various operation time for GLRM model building iterations.
def extractRunInto(javaLogText): """ This function will extract the various operation time for GLRM model building iterations. :param javaLogText: :return: """ global g_initialXY global g_reguarlize_Y global g_regularize_X_objective global g_updateX global g_updateY global g...
Main program. Take user input parse it and call other functions to execute the commands and extract run summary and store run result in json file
def main(argv): """ Main program. Take user input, parse it and call other functions to execute the commands and extract run summary and store run result in json file @return: none """ global g_test_root_dir global g_temp_filename if len(argv) < 2: print("invoke this script as...
func_name: Descriptive text continued text another_func_name: Descriptive text func_name1 func_name2: meth: func_name func_name3
def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name...
.. index: default: refguide: something else and more
def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['d...
Fill this instance from given dictionary. The method only uses keys which corresponds to properties this class throws exception on unknown property name.: param conf: dictionary of parameters: return: a new instance of this class filled with values from given dictionary: raises H2OValueError: if input config contains u...
def _fill_from_config(self, config): """ Fill this instance from given dictionary. The method only uses keys which corresponds to properties this class, throws exception on unknown property name. :param conf: dictionary of parameters :return: a new instance of this clas...
r Establish connection to an existing H2O server.
def open(server=None, url=None, ip=None, port=None, name=None, https=None, auth=None, verify_ssl_certificates=True, proxy=None, cookies=None, verbose=True, _msgs=None): r""" Establish connection to an existing H2O server. The connection is not kept alive, so what this method actual...
Perform a REST API request to the backend H2O server.
def request(self, endpoint, data=None, json=None, filename=None, save_to=None): """ Perform a REST API request to the backend H2O server. :param endpoint: (str) The endpoint's URL, for example "GET /4/schemas/KeyV4" :param data: data payload for POST (and sometimes GET) requests. This s...
Close an existing connection ; once closed it cannot be used again.
def close(self): """ Close an existing connection; once closed it cannot be used again. Strictly speaking it is not necessary to close all connection that you opened -- we have several mechanisms in place that will do so automatically (__del__(), __exit__() and atexit() handlers), howev...
Return the session id of the current connection.
def session_id(self): """ Return the session id of the current connection. The session id is issued (through an API request) the first time it is requested, but no sooner. This is because generating a session id puts it into the DKV on the server, which effectively locks the cluster. On...
Start logging all API requests to the provided destination.
def start_logging(self, dest=None): """ Start logging all API requests to the provided destination. :param dest: Where to write the log: either a filename (str), or an open file handle (file). If not given, then a new temporary file will be created. """ assert_is_typ...
Make a copy of the data object preparing it to be sent to the server.
def _prepare_data_payload(data): """ Make a copy of the `data` object, preparing it to be sent to the server. The data will be sent via x-www-form-urlencoded or multipart/form-data mechanisms. Both of them work with plain lists of key/value pairs, so this method converts the data into s...
Prepare filename to be sent to the server.
def _prepare_file_payload(filename): """ Prepare `filename` to be sent to the server. The "preparation" consists of creating a data structure suitable for passing to requests.request(). """ if not filename: return None absfilename = os.path.abspath(filename) ...
Log the beginning of an API request.
def _log_start_transaction(self, endpoint, data, json, files, params): """Log the beginning of an API request.""" # TODO: add information about the caller, i.e. which module + line of code called the .request() method # This can be done by fetching current traceback and then traversing it ...
Log response from an API request.
def _log_end_transaction(self, start_time, response): """Log response from an API request.""" if not self._is_logging: return elapsed_time = int((time.time() - start_time) * 1000) msg = "<<< HTTP %d %s (%d ms)\n" % (response.status_code, response.reason, elapsed_time) if "Conte...
Log the message msg to the destination self. _logging_dest.
def _log_message(self, msg): """ Log the message `msg` to the destination `self._logging_dest`. If this destination is a file name, then we append the message to the file and then close the file immediately. If the destination is an open file handle, then we simply write the message the...
Given a response object prepare it to be handed over to the external caller.
def _process_response(response, save_to): """ Given a response object, prepare it to be handed over to the external caller. Preparation steps include: * detect if the response has error status, and convert it to an appropriate exception; * detect Content-Type, and based on...
Helper function to print connection status messages when in verbose mode.
def _print(self, msg, flush=False, end="\n"): """Helper function to print connection status messages when in verbose mode.""" if self._verbose: print2(msg, end=end, flush=flush)
approxEqual ( float1 float2 [ tol = 1e - 18 rel = 1e - 7 ] ) - > True|False approxEqual ( obj1 obj2 [ * args ** kwargs ] ) - > True|False
def approxEqual(x, y, *args, **kwargs): """approxEqual(float1, float2[, tol=1e-18, rel=1e-7]) -> True|False approxEqual(obj1, obj2[, *args, **kwargs]) -> True|False Return True if x and y are approximately equal, otherwise False. If x and y are floats, return True if y is within either absolute error ...
Represent instance of a class as JSON. Arguments: obj -- any object Return: String that represent JSON - encoded object.
def json_repr(obj, curr_depth=0, max_depth=4): """Represent instance of a class as JSON. Arguments: obj -- any object Return: String that represent JSON-encoded object. """ def serialize(obj, curr_depth): """Recursively walk object's hierarchy. Limit to max_depth""" if curr_d...
Retrieve information about an AutoML instance.
def get_automl(project_name): """ Retrieve information about an AutoML instance. :param str project_name: A string indicating the project_name of the automl instance to retrieve. :returns: A dictionary containing the project_name, leader model, and leaderboard. """ automl_json = h2o.api("GET /...
Begins an AutoML task a background task that automatically builds a number of models with various algorithms and tracks their performance in a leaderboard. At any point in the process you may use H2O s performance or prediction functions on the resulting models.
def train(self, x = None, y = None, training_frame = None, fold_column = None, weights_column = None, validation_frame = None, leaderboard_frame = None, blending_frame = None): """ Begins an AutoML task, a background task that automatically builds a number of models with various a...
Predict on a dataset.
def predict(self, test_data): """ Predict on a dataset. :param H2OFrame test_data: Data on which to make predictions. :returns: A new H2OFrame of predictions. :examples: >>> # Set up an H2OAutoML object >>> aml = H2OAutoML(max_runtime_secs=30) >>> # Lau...
Download the POJO for the leader model in AutoML to the directory specified by path.
def download_pojo(self, path="", get_genmodel_jar=False, genmodel_name=""): """ Download the POJO for the leader model in AutoML to the directory specified by path. If path is an empty string, then dump the output to screen. :param path: An absolute path to the directory where POJO sh...
Download the leader model in AutoML in MOJO format.
def download_mojo(self, path=".", get_genmodel_jar=False, genmodel_name=""): """ Download the leader model in AutoML in MOJO format. :param path: the path where MOJO file should be saved. :param get_genmodel_jar: if True, then also download h2o-genmodel.jar and store it in folder ``path...
Fit this object by computing the means and standard deviations used by the transform method.
def fit(self, X, y=None, **params): """ Fit this object by computing the means and standard deviations used by the transform method. :param X: An H2OFrame; may contain NAs and/or categoricals. :param y: None (Ignored) :param params: Ignored :returns: This H2OScaler insta...
Scale an H2OFrame with the fitted means and standard deviations.
def transform(self, X, y=None, **params): """ Scale an H2OFrame with the fitted means and standard deviations. :param X: An H2OFrame; may contain NAs and/or categoricals. :param y: None (Ignored) :param params: (Ignored) :returns: A scaled H2OFrame. """ r...
Undo the scale transformation.
def inverse_transform(self, X, y=None, **params): """ Undo the scale transformation. :param X: An H2OFrame; may contain NAs and/or categoricals. :param y: None (Ignored) :param params: (Ignored) :returns: An H2OFrame """ for i in range(X.ncol): ...
Main program.
def main(argv): """ Main program. @return: none """ global g_script_name g_script_name = os.path.basename(argv[0]) parse_config_file() parse_args(argv) url = 'https://0xdata.atlassian.net/rest/api/2/search?jql=' \ + 'project+in+(PUBDEV,HEXDEV)' \ + '+and+' \ ...
remove extra characters before the actual string we are looking for. The Jenkins console output is encoded using utf - 8. However the stupid redirect function can only encode using ASCII. I have googled for half a day with no results to how to resolve the issue. Hence we are going to the heat and just manually get rid ...
def extract_true_string(string_content): """ remove extra characters before the actual string we are looking for. The Jenkins console output is encoded using utf-8. However, the stupid redirect function can only encode using ASCII. I have googled for half a day with no results to how to resolve t...
calculate the approximate date/ time from the timestamp about when the job was built. This information was then saved in dict g_failed_test_info_dict. In addition it will delete this particular function handle off the temp_func_list as we do not need to perform this action again.
def find_time(each_line,temp_func_list): """ calculate the approximate date/time from the timestamp about when the job was built. This information was then saved in dict g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to ...
Find the slave machine where a Jenkins job was executed on. It will save this information in g_failed_test_info_dict. In addition it will delete this particular function handle off the temp_func_list as we do not need to perform this action again.
def find_node_name(each_line,temp_func_list): """ Find the slave machine where a Jenkins job was executed on. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again....
Find the git hash and branch info that a Jenkins job was taken from. It will save this information in g_failed_test_info_dict. In addition it will delete this particular function handle off the temp_func_list as we do not need to perform this action again.
def find_git_hash_branch(each_line,temp_func_list): """ Find the git hash and branch info that a Jenkins job was taken from. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this a...
Find if a Jenkins job has taken too long to finish and was killed. It will save this information in g_failed_test_info_dict.
def find_build_timeout(each_line,temp_func_list): """ Find if a Jenkins job has taken too long to finish and was killed. It will save this information in g_failed_test_info_dict. Parameters ---------- each_line : str contains a line read in from jenkins console temp_func_list : ...
Find if a Jenkins job has failed to build. It will save this information in g_failed_test_info_dict. In addition it will delete this particular function handle off the temp_func_list as we do not need to perform this action again.
def find_build_failure(each_line,temp_func_list): """ Find if a Jenkins job has failed to build. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ...
Find if all the java_ * _0. out. txt files that were mentioned in the console output. It will save this information in g_java_filenames as a list of strings.
def find_java_filename(each_line,temp_func_list): """ Find if all the java_*_0.out.txt files that were mentioned in the console output. It will save this information in g_java_filenames as a list of strings. Parameters ---------- each_line : str contains a line read in from jenkins co...
Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition it will delete this particular function handle off the temp_func_list as we do not need to perform this action again.
def find_build_id(each_line,temp_func_list): """ Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters --------...
From user input grab the jenkins job name and saved it in g_failed_test_info_dict. In addition it will grab the jenkins url and the view name into g_jenkins_url and g_view_name.
def extract_job_build_url(url_string): """ From user input, grab the jenkins job name and saved it in g_failed_test_info_dict. In addition, it will grab the jenkins url and the view name into g_jenkins_url, and g_view_name. Parameters ---------- url_string : str contains informatio...
scan through the java output text and extract the bad java messages that may or may not happened when unit tests are run. It will not record any bad java messages that are stored in g_ok_java_messages.
def grab_java_message(): """scan through the java output text and extract the bad java messages that may or may not happened when unit tests are run. It will not record any bad java messages that are stored in g_ok_java_messages. :return: none """ global g_temp_filename global g_current_testn...
Insert Java messages into java_messages and java_message_types if they are associated with a unit test or into g_java_general_bad_messages/ g_java_general_bad_message_types otherwise.
def addJavaMessages(tempMessage,messageType,java_messages,java_message_types): """ Insert Java messages into java_messages and java_message_types if they are associated with a unit test or into g_java_general_bad_messages/g_java_general_bad_message_types otherwise. Parameters ---------- tem...
loop through java_ * _0. out. txt and extract potentially dangerous WARN/ ERRR/ FATAL messages associated with a test. The test may even pass but something terrible has actually happened.
def extract_java_messages(): """ loop through java_*_0.out.txt and extract potentially dangerous WARN/ERRR/FATAL messages associated with a test. The test may even pass but something terrible has actually happened. :return: none """ global g_jenkins_url global g_failed_test_info_dict ...
Save the log scraping results into logs denoted by g_output_filename_failed_tests and g_output_filename_passed_tests.
def save_dict(): """ Save the log scraping results into logs denoted by g_output_filename_failed_tests and g_output_filename_passed_tests. :return: none """ global g_test_root_dir global g_output_filename_failed_tests global g_output_filename_passed_tests global g_output_pickle_fil...
Write key/ value into log file when the value is a string and not a list.
def write_general_build_message(key,val,text_file): """ Write key/value into log file when the value is a string and not a list. Parameters ---------- key : str key value in g_failed_test_info_dict value : str corresponding value associated with the key in key text_file : ...
Concatecate all log file into a summary text file to be sent to users at the end of a daily log scraping.
def update_summary_file(): """ Concatecate all log file into a summary text file to be sent to users at the end of a daily log scraping. :return: none """ global g_summary_text_filename global g_output_filename_failed_tests global g_output_filename_passed_tests with open(g_summary_...
Write one log file into the summary text file.
def write_file_content(fhandle,file2read): """ Write one log file into the summary text file. Parameters ---------- fhandle : Python file handle file handle to the summary text file file2read : Python file handle file handle to log file where we want to add its content to the s...
Loop through all java messages that are not associated with a unit test and write them into a log file.
def write_java_message(key,val,text_file): """ Loop through all java messages that are not associated with a unit test and write them into a log file. Parameters ---------- key : str 9.general_bad_java_messages val : list of list of str contains the bad java messages and th...
Load in pickle file that contains dict structure with bad java messages to ignore per unit test or for all cases. The ignored bad java info is stored in g_ok_java_messages dict.
def load_java_messages_to_ignore(): """ Load in pickle file that contains dict structure with bad java messages to ignore per unit test or for all cases. The ignored bad java info is stored in g_ok_java_messages dict. :return: """ global g_ok_java_messages global g_java_message_pickle_file...
Main program.
def main(argv): """ Main program. @return: none """ global g_script_name global g_test_root_dir global g_temp_filename global g_output_filename_failed_tests global g_output_filename_passed_tests global g_output_pickle_filename global g_failure_occurred global g_failed_te...
Return enum constant s converted to a canonical snake - case.
def normalize_enum_constant(s): """Return enum constant `s` converted to a canonical snake-case.""" if s.islower(): return s if s.isupper(): return s.lower() return "".join(ch if ch.islower() else "_" + ch.lower() for ch in s).strip("_")
Find synonyms using a word2vec model.
def find_synonyms(self, word, count=20): """ Find synonyms using a word2vec model. :param str word: A single word to find synonyms for. :param int count: The first "count" synonyms will be returned. :returns: the approximate reconstruction of the training data. """ ...
Transform words ( or sequences of words ) to vectors using a word2vec model.
def transform(self, words, aggregate_method): """ Transform words (or sequences of words) to vectors using a word2vec model. :param str words: An H2OFrame made of a single column containing source words. :param str aggregate_method: Specifies how to aggregate sequences of words. If meth...
Wait until the job finishes.
def poll(self, verbose_model_scoring_history = False): """ Wait until the job finishes. This method will continuously query the server about the status of the job, until the job reaches a completion. During this time we will display (in stdout) a progress bar with % completion status. ...
Convert the munging operations performed on H2OFrame into a POJO.
def to_pojo(self, pojo_name="", path="", get_jar=True): """ Convert the munging operations performed on H2OFrame into a POJO. :param pojo_name: (str) Name of POJO :param path: (str) path of POJO. :param get_jar: (bool) Whether to also download the h2o-genmodel.jar file needed ...
To perform the munging operations on a frame specified in steps on the frame fr.
def fit(self, fr): """ To perform the munging operations on a frame specified in steps on the frame fr. :param fr: H2OFrame where munging operations are to be performed on. :return: H2OFrame after munging operations are completed. """ assert_is_type(fr, H2OFrame) ...
Find the percentile of a list of values.
def percentileOnSortedList(N, percent, key=lambda x:x, interpolate='mean'): # 5 ways of resolving fractional # floor, ceil, funky, linear, mean interpolateChoices = ['floor', 'ceil', 'funky', 'linear', 'mean'] if interpolate not in interpolateChoices: print "Bad choice for interpolate:", interpo...
Get the parameters and the actual/ default values only.
def params(self): """ Get the parameters and the actual/default values only. :returns: A dictionary of parameters used to build this model. """ params = {} for p in self.parms: params[p] = {"default": self.parms[p]["default_value"], "...
Dictionary of the default parameters of the model.
def default_params(self): """Dictionary of the default parameters of the model.""" params = {} for p in self.parms: params[p] = self.parms[p]["default_value"] return params
Dictionary of actual parameters of the model.
def actual_params(self): """Dictionary of actual parameters of the model.""" params_to_select = {"model_id": "name", "response_column": "column_name", "training_frame": "name", "validation_frame": "name"} params ...
Predict on a dataset and return the leaf node assignment ( only for tree - based models ).
def predict_leaf_node_assignment(self, test_data, type="Path"): """ Predict on a dataset and return the leaf node assignment (only for tree-based models). :param H2OFrame test_data: Data on which to make predictions. :param Enum type: How to identify the leaf node. Nodes can be either i...
Predict class probabilities at each stage of an H2O Model ( only GBM models ).
def staged_predict_proba(self, test_data): """ Predict class probabilities at each stage of an H2O Model (only GBM models). The output structure is analogous to the output of function predict_leaf_node_assignment. For each tree t and class c there will be a column Tt.Cc (eg. T3.C1 for t...
Predict on a dataset.
def predict(self, test_data, custom_metric = None, custom_metric_func = None): """ Predict on a dataset. :param H2OFrame test_data: Data on which to make predictions. :param custom_metric: custom evaluation function defined as class reference, the class get uploaded into cluste...
Return a Model object.
def get_xval_models(self, key=None): """ Return a Model object. :param key: If None, return all cross-validated models; otherwise return the model that key points to. :returns: A model or list of models. """ return h2o.get_model(key) if key is not None else [h2o.get_mod...
Return hidden layer details.
def deepfeatures(self, test_data, layer): """ Return hidden layer details. :param test_data: Data to create a feature space on :param layer: 0 index hidden layer """ if test_data is None: raise ValueError("Must specify test data") if str(layer).isdigit(): ...
Return the frame for the respective weight matrix.
def weights(self, matrix_id=0): """ Return the frame for the respective weight matrix. :param: matrix_id: an integer, ranging from 0 to number of layers, that specifies the weight matrix to return. :returns: an H2OFrame which represents the weight matrix identified by matrix_id ...
Return the frame for the respective bias vector.
def biases(self, vector_id=0): """ Return the frame for the respective bias vector. :param: vector_id: an integer, ranging from 0 to number of layers, that specifies the bias vector to return. :returns: an H2OFrame which represents the bias vector identified by vector_id """ ...
Generate model metrics for this model on test_data.
def model_performance(self, test_data=None, train=False, valid=False, xval=False): """ Generate model metrics for this model on test_data. :param H2OFrame test_data: Data set for which model metrics shall be computed against. All three of train, valid and xval arguments are ignored ...
Retrieve Model Score History.
def scoring_history(self): """ Retrieve Model Score History. :returns: The score history as an H2OTwoDimTable or a Pandas DataFrame. """ model = self._model_json["output"] if "scoring_history" in model and model["scoring_history"] is not None: return model["s...
Print innards of model without regards to type.
def show(self): """Print innards of model, without regards to type.""" if self._future: self._job.poll_once() return if self._model_json is None: print("No model trained yet") return if self.model_id is None: print("This H2OEsti...
Pretty print the variable importances or return them in a list.
def varimp(self, use_pandas=False): """ Pretty print the variable importances, or return them in a list. :param use_pandas: If True, then the variable importances will be returned as a pandas data frame. :returns: A list or Pandas DataFrame. """ model = self._model_json...
Retreive the residual degress of freedom if this model has the attribute or None otherwise.
def residual_degrees_of_freedom(self, train=False, valid=False, xval=False): """ Retreive the residual degress of freedom if this model has the attribute, or None otherwise. :param bool train: Get the residual dof for the training set. If both train and valid are False, then train i...
Return the coefficients which can be applied to the non - standardized data.
def coef(self): """ Return the coefficients which can be applied to the non-standardized data. Note: standardize = True by default, if set to False then coef() return the coefficients which are fit directly. """ tbl = self._model_json["output"]["coefficients_table"] if t...
Return coefficients fitted on the standardized data ( requires standardize = True which is on by default ).
def coef_norm(self): """ Return coefficients fitted on the standardized data (requires standardize = True, which is on by default). These coefficients can be used to evaluate variable importance. """ if self._model_json["output"]["model_category"]=="Multinomial": tbl...
Download the POJO for this model to the directory specified by path.
def download_pojo(self, path="", get_genmodel_jar=False, genmodel_name=""): """ Download the POJO for this model to the directory specified by path. If path is an empty string, then dump the output to screen. :param path: An absolute path to the directory where POJO should be saved. ...
Download the model in MOJO format.
def download_mojo(self, path=".", get_genmodel_jar=False, genmodel_name=""): """ Download the model in MOJO format. :param path: the path where MOJO file should be saved. :param get_genmodel_jar: if True, then also download h2o-genmodel.jar and store it in folder ``path``. :para...
Save an H2O Model as MOJO ( Model Object Optimized ) to disk.
def save_mojo(self, path="", force=False): """ Save an H2O Model as MOJO (Model Object, Optimized) to disk. :param model: The model object to save. :param path: a path to save the model at (hdfs, s3, local) :param force: if True overwrite destination directory in case it exists,...
Save Model Details of an H2O Model in JSON Format to disk.
def save_model_details(self, path="", force=False): """ Save Model Details of an H2O Model in JSON Format to disk. :param model: The model object to save. :param path: a path to save the model details at (hdfs, s3, local) :param force: if True overwrite destination directory in ...
Create partial dependence plot which gives a graphical depiction of the marginal effect of a variable on the response. The effect of a variable is measured in change in the mean response.
def partial_plot(self, data, cols, destination_key=None, nbins=20, weight_column=None, plot=True, plot_stddev = True, figsize=(7, 10), server=False, include_na=False, user_splits=None, save_to_file=None): """ Create partial dependence plot which gives a graphica...
Plot the variable importance for a trained model.
def varimp_plot(self, num_of_features=None, server=False): """ Plot the variable importance for a trained model. :param num_of_features: the number of features shown in the plot (default is 10 or all if less than 10). :param server: ? :returns: None. """ assert_...
Plot a GLM model s standardized coefficient magnitudes.
def std_coef_plot(self, num_of_features=None, server=False): """ Plot a GLM model"s standardized coefficient magnitudes. :param num_of_features: the number of features shown in the plot. :param server: ? :returns: None. """ assert_is_type(num_of_features, None, ...
Check that y_actual and y_predicted have the same length.
def _check_targets(y_actual, y_predicted): """Check that y_actual and y_predicted have the same length. :param H2OFrame y_actual: :param H2OFrame y_predicted: :returns: None """ if len(y_actual) != len(y_predicted): raise ValueError("Row mismatch: [{},{}]".f...
Obtain a list of cross - validation models.
def cross_validation_models(self): """ Obtain a list of cross-validation models. :returns: list of H2OModel objects. """ cvmodels = self._model_json["output"]["cross_validation_models"] if cvmodels is None: return None m = [] for p in cvmodels: m.append(h...
Obtain the ( out - of - sample ) holdout predictions of all cross - validation models on their holdout data.
def cross_validation_predictions(self): """ Obtain the (out-of-sample) holdout predictions of all cross-validation models on their holdout data. Note that the predictions are expanded to the full number of rows of the training data, with 0 fill-in. :returns: list of H2OFrame objects. ...
GBM model demo.
def gbm(interactive=True, echo=True, testing=False): """GBM model demo.""" def demo_body(go): """ Demo of H2O's Gradient Boosting estimator. This demo uploads a dataset to h2o, parses it, and shows a description. Then it divides the dataset into training and test sets, builds a...